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
1614bf51368f058a8f08be033d22e749f61623dd
40,569
cpp
C++
src/dawn/native/d3d12/ShaderModuleD3D12.cpp
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
9
2021-11-05T11:08:14.000Z
2022-03-18T05:14:34.000Z
src/dawn/native/d3d12/ShaderModuleD3D12.cpp
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
2
2021-12-01T05:08:59.000Z
2022-02-18T08:14:30.000Z
src/dawn/native/d3d12/ShaderModuleD3D12.cpp
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
1
2022-02-11T17:39:44.000Z
2022-02-11T17:39:44.000Z
// Copyright 2017 The Dawn 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 "dawn/native/d3d12/ShaderModuleD3D12.h" #include <d3dcompiler.h> #include <map> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "dawn/common/Assert.h" #include "dawn/common/BitSetIterator.h" #include "dawn/common/Log.h" #include "dawn/common/WindowsUtils.h" #include "dawn/native/Pipeline.h" #include "dawn/native/TintUtils.h" #include "dawn/native/d3d12/BindGroupLayoutD3D12.h" #include "dawn/native/d3d12/D3D12Error.h" #include "dawn/native/d3d12/DeviceD3D12.h" #include "dawn/native/d3d12/PipelineLayoutD3D12.h" #include "dawn/native/d3d12/PlatformFunctions.h" #include "dawn/native/d3d12/UtilsD3D12.h" #include "dawn/platform/DawnPlatform.h" #include "dawn/platform/tracing/TraceEvent.h" #include "tint/tint.h" namespace dawn::native::d3d12 { namespace { ResultOrError<uint64_t> GetDXCompilerVersion(ComPtr<IDxcValidator> dxcValidator) { ComPtr<IDxcVersionInfo> versionInfo; DAWN_TRY(CheckHRESULT(dxcValidator.As(&versionInfo), "D3D12 QueryInterface IDxcValidator to IDxcVersionInfo")); uint32_t compilerMajor, compilerMinor; DAWN_TRY(CheckHRESULT(versionInfo->GetVersion(&compilerMajor, &compilerMinor), "IDxcVersionInfo::GetVersion")); // Pack both into a single version number. return (uint64_t(compilerMajor) << uint64_t(32)) + compilerMinor; } uint64_t GetD3DCompilerVersion() { return D3D_COMPILER_VERSION; } struct CompareBindingPoint { constexpr bool operator()(const tint::transform::BindingPoint& lhs, const tint::transform::BindingPoint& rhs) const { if (lhs.group != rhs.group) { return lhs.group < rhs.group; } else { return lhs.binding < rhs.binding; } } }; void Serialize(std::stringstream& output, const tint::ast::Access& access) { output << access; } void Serialize(std::stringstream& output, const tint::transform::BindingPoint& binding_point) { output << "(BindingPoint"; output << " group=" << binding_point.group; output << " binding=" << binding_point.binding; output << ")"; } template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value>::type> void Serialize(std::stringstream& output, const T& val) { output << val; } template <typename T> void Serialize(std::stringstream& output, const std::unordered_map<tint::transform::BindingPoint, T>& map) { output << "(map"; std::map<tint::transform::BindingPoint, T, CompareBindingPoint> sorted(map.begin(), map.end()); for (auto& [bindingPoint, value] : sorted) { output << " "; Serialize(output, bindingPoint); output << "="; Serialize(output, value); } output << ")"; } void Serialize(std::stringstream& output, const tint::writer::ArrayLengthFromUniformOptions& arrayLengthFromUniform) { output << "(ArrayLengthFromUniformOptions"; output << " ubo_binding="; Serialize(output, arrayLengthFromUniform.ubo_binding); output << " bindpoint_to_size_index="; Serialize(output, arrayLengthFromUniform.bindpoint_to_size_index); output << ")"; } // 32 bit float has 7 decimal digits of precision so setting n to 8 should be enough std::string FloatToStringWithPrecision(float v, std::streamsize n = 8) { std::ostringstream out; out.precision(n); out << std::fixed << v; return out.str(); } std::string GetHLSLValueString(EntryPointMetadata::OverridableConstant::Type dawnType, const OverridableConstantScalar* entry, double value = 0) { switch (dawnType) { case EntryPointMetadata::OverridableConstant::Type::Boolean: return std::to_string(entry ? entry->b : static_cast<int32_t>(value)); case EntryPointMetadata::OverridableConstant::Type::Float32: return FloatToStringWithPrecision(entry ? entry->f32 : static_cast<float>(value)); case EntryPointMetadata::OverridableConstant::Type::Int32: return std::to_string(entry ? entry->i32 : static_cast<int32_t>(value)); case EntryPointMetadata::OverridableConstant::Type::Uint32: return std::to_string(entry ? entry->u32 : static_cast<uint32_t>(value)); default: UNREACHABLE(); } } constexpr char kSpecConstantPrefix[] = "WGSL_SPEC_CONSTANT_"; void GetOverridableConstantsDefines( std::vector<std::pair<std::string, std::string>>* defineStrings, const PipelineConstantEntries* pipelineConstantEntries, const EntryPointMetadata::OverridableConstantsMap* shaderEntryPointConstants) { std::unordered_set<std::string> overriddenConstants; // Set pipeline overridden values for (const auto& [name, value] : *pipelineConstantEntries) { overriddenConstants.insert(name); // This is already validated so `name` must exist const auto& moduleConstant = shaderEntryPointConstants->at(name); defineStrings->emplace_back( kSpecConstantPrefix + std::to_string(static_cast<int32_t>(moduleConstant.id)), GetHLSLValueString(moduleConstant.type, nullptr, value)); } // Set shader initialized default values for (const auto& iter : *shaderEntryPointConstants) { const std::string& name = iter.first; if (overriddenConstants.count(name) != 0) { // This constant already has overridden value continue; } const auto& moduleConstant = shaderEntryPointConstants->at(name); // Uninitialized default values are okay since they ar only defined to pass // compilation but not used defineStrings->emplace_back( kSpecConstantPrefix + std::to_string(static_cast<int32_t>(moduleConstant.id)), GetHLSLValueString(moduleConstant.type, &moduleConstant.defaultValue)); } } // The inputs to a shader compilation. These have been intentionally isolated from the // device to help ensure that the pipeline cache key contains all inputs for compilation. struct ShaderCompilationRequest { enum Compiler { FXC, DXC }; // Common inputs Compiler compiler; const tint::Program* program; const char* entryPointName; SingleShaderStage stage; uint32_t compileFlags; bool disableSymbolRenaming; tint::transform::BindingRemapper::BindingPoints remappedBindingPoints; tint::transform::BindingRemapper::AccessControls remappedAccessControls; bool isRobustnessEnabled; bool usesNumWorkgroups; uint32_t numWorkgroupsRegisterSpace; uint32_t numWorkgroupsShaderRegister; tint::writer::ArrayLengthFromUniformOptions arrayLengthFromUniform; std::vector<std::pair<std::string, std::string>> defineStrings; // FXC/DXC common inputs bool disableWorkgroupInit; // FXC inputs uint64_t fxcVersion; // DXC inputs uint64_t dxcVersion; const D3D12DeviceInfo* deviceInfo; bool hasShaderFloat16Feature; static ResultOrError<ShaderCompilationRequest> Create( const char* entryPointName, SingleShaderStage stage, const PipelineLayout* layout, uint32_t compileFlags, const Device* device, const tint::Program* program, const EntryPointMetadata& entryPoint, const ProgrammableStage& programmableStage) { Compiler compiler; uint64_t dxcVersion = 0; if (device->IsToggleEnabled(Toggle::UseDXC)) { compiler = Compiler::DXC; DAWN_TRY_ASSIGN(dxcVersion, GetDXCompilerVersion(device->GetDxcValidator())); } else { compiler = Compiler::FXC; } using tint::transform::BindingPoint; using tint::transform::BindingRemapper; BindingRemapper::BindingPoints remappedBindingPoints; BindingRemapper::AccessControls remappedAccessControls; tint::writer::ArrayLengthFromUniformOptions arrayLengthFromUniform; arrayLengthFromUniform.ubo_binding = { layout->GetDynamicStorageBufferLengthsRegisterSpace(), layout->GetDynamicStorageBufferLengthsShaderRegister()}; const BindingInfoArray& moduleBindingInfo = entryPoint.bindings; for (BindGroupIndex group : IterateBitSet(layout->GetBindGroupLayoutsMask())) { const BindGroupLayout* bgl = ToBackend(layout->GetBindGroupLayout(group)); const auto& groupBindingInfo = moduleBindingInfo[group]; // d3d12::BindGroupLayout packs the bindings per HLSL register-space. We modify // the Tint AST to make the "bindings" decoration match the offset chosen by // d3d12::BindGroupLayout so that Tint produces HLSL with the correct registers // assigned to each interface variable. for (const auto& [binding, bindingInfo] : groupBindingInfo) { BindingIndex bindingIndex = bgl->GetBindingIndex(binding); BindingPoint srcBindingPoint{static_cast<uint32_t>(group), static_cast<uint32_t>(binding)}; BindingPoint dstBindingPoint{static_cast<uint32_t>(group), bgl->GetShaderRegister(bindingIndex)}; if (srcBindingPoint != dstBindingPoint) { remappedBindingPoints.emplace(srcBindingPoint, dstBindingPoint); } // Declaring a read-only storage buffer in HLSL but specifying a storage // buffer in the BGL produces the wrong output. Force read-only storage // buffer bindings to be treated as UAV instead of SRV. Internal storage // buffer is a storage buffer used in the internal pipeline. const bool forceStorageBufferAsUAV = (bindingInfo.buffer.type == wgpu::BufferBindingType::ReadOnlyStorage && (bgl->GetBindingInfo(bindingIndex).buffer.type == wgpu::BufferBindingType::Storage || bgl->GetBindingInfo(bindingIndex).buffer.type == kInternalStorageBufferBinding)); if (forceStorageBufferAsUAV) { remappedAccessControls.emplace(srcBindingPoint, tint::ast::Access::kReadWrite); } } // Add arrayLengthFromUniform options { for (const auto& bindingAndRegisterOffset : layout->GetDynamicStorageBufferLengthInfo()[group] .bindingAndRegisterOffsets) { BindingNumber binding = bindingAndRegisterOffset.binding; uint32_t registerOffset = bindingAndRegisterOffset.registerOffset; BindingPoint bindingPoint{static_cast<uint32_t>(group), static_cast<uint32_t>(binding)}; // Get the renamed binding point if it was remapped. auto it = remappedBindingPoints.find(bindingPoint); if (it != remappedBindingPoints.end()) { bindingPoint = it->second; } arrayLengthFromUniform.bindpoint_to_size_index.emplace(bindingPoint, registerOffset); } } } ShaderCompilationRequest request; request.compiler = compiler; request.program = program; request.entryPointName = entryPointName; request.stage = stage; request.compileFlags = compileFlags; request.disableSymbolRenaming = device->IsToggleEnabled(Toggle::DisableSymbolRenaming); request.remappedBindingPoints = std::move(remappedBindingPoints); request.remappedAccessControls = std::move(remappedAccessControls); request.isRobustnessEnabled = device->IsRobustnessEnabled(); request.disableWorkgroupInit = device->IsToggleEnabled(Toggle::DisableWorkgroupInit); request.usesNumWorkgroups = entryPoint.usesNumWorkgroups; request.numWorkgroupsShaderRegister = layout->GetNumWorkgroupsShaderRegister(); request.numWorkgroupsRegisterSpace = layout->GetNumWorkgroupsRegisterSpace(); request.arrayLengthFromUniform = std::move(arrayLengthFromUniform); request.fxcVersion = compiler == Compiler::FXC ? GetD3DCompilerVersion() : 0; request.dxcVersion = compiler == Compiler::DXC ? dxcVersion : 0; request.deviceInfo = &device->GetDeviceInfo(); request.hasShaderFloat16Feature = device->IsFeatureEnabled(Feature::ShaderFloat16); GetOverridableConstantsDefines( &request.defineStrings, &programmableStage.constants, &programmableStage.module->GetEntryPoint(programmableStage.entryPoint) .overridableConstants); return std::move(request); } ResultOrError<PersistentCacheKey> CreateCacheKey() const { // Generate the WGSL from the Tint program so it's normalized. // TODO(tint:1180): Consider using a binary serialization of the tint AST for a more // compact representation. auto result = tint::writer::wgsl::Generate(program, tint::writer::wgsl::Options{}); if (!result.success) { std::ostringstream errorStream; errorStream << "Tint WGSL failure:" << std::endl; errorStream << "Generator: " << result.error << std::endl; return DAWN_INTERNAL_ERROR(errorStream.str().c_str()); } std::stringstream stream; // Prefix the key with the type to avoid collisions from another type that could // have the same key. stream << static_cast<uint32_t>(PersistentKeyType::Shader); stream << "\n"; stream << result.wgsl.length(); stream << "\n"; stream << result.wgsl; stream << "\n"; stream << "(ShaderCompilationRequest"; stream << " compiler=" << compiler; stream << " entryPointName=" << entryPointName; stream << " stage=" << uint32_t(stage); stream << " compileFlags=" << compileFlags; stream << " disableSymbolRenaming=" << disableSymbolRenaming; stream << " remappedBindingPoints="; Serialize(stream, remappedBindingPoints); stream << " remappedAccessControls="; Serialize(stream, remappedAccessControls); stream << " useNumWorkgroups=" << usesNumWorkgroups; stream << " numWorkgroupsRegisterSpace=" << numWorkgroupsRegisterSpace; stream << " numWorkgroupsShaderRegister=" << numWorkgroupsShaderRegister; stream << " arrayLengthFromUniform="; Serialize(stream, arrayLengthFromUniform); stream << " shaderModel=" << deviceInfo->shaderModel; stream << " disableWorkgroupInit=" << disableWorkgroupInit; stream << " isRobustnessEnabled=" << isRobustnessEnabled; stream << " fxcVersion=" << fxcVersion; stream << " dxcVersion=" << dxcVersion; stream << " hasShaderFloat16Feature=" << hasShaderFloat16Feature; stream << " defines={"; for (const auto& [name, value] : defineStrings) { stream << " <" << name << "," << value << ">"; } stream << " }"; stream << ")"; stream << "\n"; return PersistentCacheKey(std::istreambuf_iterator<char>{stream}, std::istreambuf_iterator<char>{}); } }; std::vector<const wchar_t*> GetDXCArguments(uint32_t compileFlags, bool enable16BitTypes) { std::vector<const wchar_t*> arguments; if (compileFlags & D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY) { arguments.push_back(L"/Gec"); } if (compileFlags & D3DCOMPILE_IEEE_STRICTNESS) { arguments.push_back(L"/Gis"); } constexpr uint32_t d3dCompileFlagsBits = D3DCOMPILE_OPTIMIZATION_LEVEL2; if (compileFlags & d3dCompileFlagsBits) { switch (compileFlags & D3DCOMPILE_OPTIMIZATION_LEVEL2) { case D3DCOMPILE_OPTIMIZATION_LEVEL0: arguments.push_back(L"/O0"); break; case D3DCOMPILE_OPTIMIZATION_LEVEL2: arguments.push_back(L"/O2"); break; case D3DCOMPILE_OPTIMIZATION_LEVEL3: arguments.push_back(L"/O3"); break; } } if (compileFlags & D3DCOMPILE_DEBUG) { arguments.push_back(L"/Zi"); } if (compileFlags & D3DCOMPILE_PACK_MATRIX_ROW_MAJOR) { arguments.push_back(L"/Zpr"); } if (compileFlags & D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR) { arguments.push_back(L"/Zpc"); } if (compileFlags & D3DCOMPILE_AVOID_FLOW_CONTROL) { arguments.push_back(L"/Gfa"); } if (compileFlags & D3DCOMPILE_PREFER_FLOW_CONTROL) { arguments.push_back(L"/Gfp"); } if (compileFlags & D3DCOMPILE_RESOURCES_MAY_ALIAS) { arguments.push_back(L"/res_may_alias"); } if (enable16BitTypes) { // enable-16bit-types are only allowed in -HV 2018 (default) arguments.push_back(L"/enable-16bit-types"); } arguments.push_back(L"-HV"); arguments.push_back(L"2018"); return arguments; } ResultOrError<ComPtr<IDxcBlob>> CompileShaderDXC(IDxcLibrary* dxcLibrary, IDxcCompiler* dxcCompiler, const ShaderCompilationRequest& request, const std::string& hlslSource) { ComPtr<IDxcBlobEncoding> sourceBlob; DAWN_TRY( CheckHRESULT(dxcLibrary->CreateBlobWithEncodingOnHeapCopy( hlslSource.c_str(), hlslSource.length(), CP_UTF8, &sourceBlob), "DXC create blob")); std::wstring entryPointW; DAWN_TRY_ASSIGN(entryPointW, ConvertStringToWstring(request.entryPointName)); std::vector<const wchar_t*> arguments = GetDXCArguments(request.compileFlags, request.hasShaderFloat16Feature); // Build defines for overridable constants std::vector<std::pair<std::wstring, std::wstring>> defineStrings; defineStrings.reserve(request.defineStrings.size()); for (const auto& [name, value] : request.defineStrings) { defineStrings.emplace_back(UTF8ToWStr(name.c_str()), UTF8ToWStr(value.c_str())); } std::vector<DxcDefine> dxcDefines; dxcDefines.reserve(defineStrings.size()); for (const auto& [name, value] : defineStrings) { dxcDefines.push_back({name.c_str(), value.c_str()}); } ComPtr<IDxcOperationResult> result; DAWN_TRY(CheckHRESULT( dxcCompiler->Compile(sourceBlob.Get(), nullptr, entryPointW.c_str(), request.deviceInfo->shaderProfiles[request.stage].c_str(), arguments.data(), arguments.size(), dxcDefines.data(), dxcDefines.size(), nullptr, &result), "DXC compile")); HRESULT hr; DAWN_TRY(CheckHRESULT(result->GetStatus(&hr), "DXC get status")); if (FAILED(hr)) { ComPtr<IDxcBlobEncoding> errors; DAWN_TRY(CheckHRESULT(result->GetErrorBuffer(&errors), "DXC get error buffer")); return DAWN_FORMAT_VALIDATION_ERROR("DXC compile failed with: %s", static_cast<char*>(errors->GetBufferPointer())); } ComPtr<IDxcBlob> compiledShader; DAWN_TRY(CheckHRESULT(result->GetResult(&compiledShader), "DXC get result")); return std::move(compiledShader); } std::string CompileFlagsToStringFXC(uint32_t compileFlags) { struct Flag { uint32_t value; const char* name; }; constexpr Flag flags[] = { // Populated from d3dcompiler.h #define F(f) Flag{f, #f} F(D3DCOMPILE_DEBUG), F(D3DCOMPILE_SKIP_VALIDATION), F(D3DCOMPILE_SKIP_OPTIMIZATION), F(D3DCOMPILE_PACK_MATRIX_ROW_MAJOR), F(D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR), F(D3DCOMPILE_PARTIAL_PRECISION), F(D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT), F(D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT), F(D3DCOMPILE_NO_PRESHADER), F(D3DCOMPILE_AVOID_FLOW_CONTROL), F(D3DCOMPILE_PREFER_FLOW_CONTROL), F(D3DCOMPILE_ENABLE_STRICTNESS), F(D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY), F(D3DCOMPILE_IEEE_STRICTNESS), F(D3DCOMPILE_RESERVED16), F(D3DCOMPILE_RESERVED17), F(D3DCOMPILE_WARNINGS_ARE_ERRORS), F(D3DCOMPILE_RESOURCES_MAY_ALIAS), F(D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES), F(D3DCOMPILE_ALL_RESOURCES_BOUND), F(D3DCOMPILE_DEBUG_NAME_FOR_SOURCE), F(D3DCOMPILE_DEBUG_NAME_FOR_BINARY), #undef F }; std::string result; for (const Flag& f : flags) { if ((compileFlags & f.value) != 0) { result += f.name + std::string("\n"); } } // Optimization level must be handled separately as two bits are used, and the values // don't map neatly to 0-3. constexpr uint32_t d3dCompileFlagsBits = D3DCOMPILE_OPTIMIZATION_LEVEL2; switch (compileFlags & d3dCompileFlagsBits) { case D3DCOMPILE_OPTIMIZATION_LEVEL0: result += "D3DCOMPILE_OPTIMIZATION_LEVEL0"; break; case D3DCOMPILE_OPTIMIZATION_LEVEL1: result += "D3DCOMPILE_OPTIMIZATION_LEVEL1"; break; case D3DCOMPILE_OPTIMIZATION_LEVEL2: result += "D3DCOMPILE_OPTIMIZATION_LEVEL2"; break; case D3DCOMPILE_OPTIMIZATION_LEVEL3: result += "D3DCOMPILE_OPTIMIZATION_LEVEL3"; break; } result += std::string("\n"); return result; } ResultOrError<ComPtr<ID3DBlob>> CompileShaderFXC(const PlatformFunctions* functions, const ShaderCompilationRequest& request, const std::string& hlslSource) { const char* targetProfile = nullptr; switch (request.stage) { case SingleShaderStage::Vertex: targetProfile = "vs_5_1"; break; case SingleShaderStage::Fragment: targetProfile = "ps_5_1"; break; case SingleShaderStage::Compute: targetProfile = "cs_5_1"; break; } ComPtr<ID3DBlob> compiledShader; ComPtr<ID3DBlob> errors; // Build defines for overridable constants const D3D_SHADER_MACRO* pDefines = nullptr; std::vector<D3D_SHADER_MACRO> fxcDefines; if (request.defineStrings.size() > 0) { fxcDefines.reserve(request.defineStrings.size() + 1); for (const auto& [name, value] : request.defineStrings) { fxcDefines.push_back({name.c_str(), value.c_str()}); } // d3dCompile D3D_SHADER_MACRO* pDefines is a nullptr terminated array fxcDefines.push_back({nullptr, nullptr}); pDefines = fxcDefines.data(); } DAWN_INVALID_IF(FAILED(functions->d3dCompile( hlslSource.c_str(), hlslSource.length(), nullptr, pDefines, nullptr, request.entryPointName, targetProfile, request.compileFlags, 0, &compiledShader, &errors)), "D3D compile failed with: %s", static_cast<char*>(errors->GetBufferPointer())); return std::move(compiledShader); } ResultOrError<std::string> TranslateToHLSL(dawn::platform::Platform* platform, const ShaderCompilationRequest& request, std::string* remappedEntryPointName) { std::ostringstream errorStream; errorStream << "Tint HLSL failure:" << std::endl; tint::transform::Manager transformManager; tint::transform::DataMap transformInputs; if (request.isRobustnessEnabled) { transformManager.Add<tint::transform::Robustness>(); } transformManager.Add<tint::transform::BindingRemapper>(); transformManager.Add<tint::transform::SingleEntryPoint>(); transformInputs.Add<tint::transform::SingleEntryPoint::Config>(request.entryPointName); transformManager.Add<tint::transform::Renamer>(); if (request.disableSymbolRenaming) { // We still need to rename HLSL reserved keywords transformInputs.Add<tint::transform::Renamer::Config>( tint::transform::Renamer::Target::kHlslKeywords); } // D3D12 registers like `t3` and `c3` have the same bindingOffset number in // the remapping but should not be considered a collision because they have // different types. const bool mayCollide = true; transformInputs.Add<tint::transform::BindingRemapper::Remappings>( std::move(request.remappedBindingPoints), std::move(request.remappedAccessControls), mayCollide); tint::Program transformedProgram; tint::transform::DataMap transformOutputs; { TRACE_EVENT0(platform, General, "RunTransforms"); DAWN_TRY_ASSIGN(transformedProgram, RunTransforms(&transformManager, request.program, transformInputs, &transformOutputs, nullptr)); } if (auto* data = transformOutputs.Get<tint::transform::Renamer::Data>()) { auto it = data->remappings.find(request.entryPointName); if (it != data->remappings.end()) { *remappedEntryPointName = it->second; } else { DAWN_INVALID_IF(!request.disableSymbolRenaming, "Could not find remapped name for entry point."); *remappedEntryPointName = request.entryPointName; } } else { return DAWN_FORMAT_VALIDATION_ERROR("Transform output missing renamer data."); } tint::writer::hlsl::Options options; options.disable_workgroup_init = request.disableWorkgroupInit; if (request.usesNumWorkgroups) { options.root_constant_binding_point.group = request.numWorkgroupsRegisterSpace; options.root_constant_binding_point.binding = request.numWorkgroupsShaderRegister; } // TODO(dawn:549): HLSL generation outputs the indices into the // array_length_from_uniform buffer that were actually used. When the blob cache can // store more than compiled shaders, we should reflect these used indices and store // them as well. This would allow us to only upload root constants that are actually // read by the shader. options.array_length_from_uniform = request.arrayLengthFromUniform; TRACE_EVENT0(platform, General, "tint::writer::hlsl::Generate"); auto result = tint::writer::hlsl::Generate(&transformedProgram, options); DAWN_INVALID_IF(!result.success, "An error occured while generating HLSL: %s", result.error); return std::move(result.hlsl); } template <typename F> MaybeError CompileShader(dawn::platform::Platform* platform, const PlatformFunctions* functions, IDxcLibrary* dxcLibrary, IDxcCompiler* dxcCompiler, ShaderCompilationRequest&& request, bool dumpShaders, F&& DumpShadersEmitLog, CompiledShader* compiledShader) { // Compile the source shader to HLSL. std::string hlslSource; std::string remappedEntryPoint; DAWN_TRY_ASSIGN(hlslSource, TranslateToHLSL(platform, request, &remappedEntryPoint)); if (dumpShaders) { std::ostringstream dumpedMsg; dumpedMsg << "/* Dumped generated HLSL */" << std::endl << hlslSource; DumpShadersEmitLog(WGPULoggingType_Info, dumpedMsg.str().c_str()); } request.entryPointName = remappedEntryPoint.c_str(); switch (request.compiler) { case ShaderCompilationRequest::Compiler::DXC: { TRACE_EVENT0(platform, General, "CompileShaderDXC"); DAWN_TRY_ASSIGN(compiledShader->compiledDXCShader, CompileShaderDXC(dxcLibrary, dxcCompiler, request, hlslSource)); break; } case ShaderCompilationRequest::Compiler::FXC: { TRACE_EVENT0(platform, General, "CompileShaderFXC"); DAWN_TRY_ASSIGN(compiledShader->compiledFXCShader, CompileShaderFXC(functions, request, hlslSource)); break; } } if (dumpShaders && request.compiler == ShaderCompilationRequest::Compiler::FXC) { std::ostringstream dumpedMsg; dumpedMsg << "/* FXC compile flags */ " << std::endl << CompileFlagsToStringFXC(request.compileFlags) << std::endl; dumpedMsg << "/* Dumped disassembled DXBC */" << std::endl; ComPtr<ID3DBlob> disassembly; if (FAILED(functions->d3dDisassemble( compiledShader->compiledFXCShader->GetBufferPointer(), compiledShader->compiledFXCShader->GetBufferSize(), 0, nullptr, &disassembly))) { dumpedMsg << "D3D disassemble failed" << std::endl; } else { dumpedMsg << reinterpret_cast<const char*>(disassembly->GetBufferPointer()); } DumpShadersEmitLog(WGPULoggingType_Info, dumpedMsg.str().c_str()); } return {}; } } // anonymous namespace // static ResultOrError<Ref<ShaderModule>> ShaderModule::Create(Device* device, const ShaderModuleDescriptor* descriptor, ShaderModuleParseResult* parseResult) { Ref<ShaderModule> module = AcquireRef(new ShaderModule(device, descriptor)); DAWN_TRY(module->Initialize(parseResult)); return module; } ShaderModule::ShaderModule(Device* device, const ShaderModuleDescriptor* descriptor) : ShaderModuleBase(device, descriptor) { } MaybeError ShaderModule::Initialize(ShaderModuleParseResult* parseResult) { ScopedTintICEHandler scopedICEHandler(GetDevice()); return InitializeBase(parseResult); } ResultOrError<CompiledShader> ShaderModule::Compile(const ProgrammableStage& programmableStage, SingleShaderStage stage, const PipelineLayout* layout, uint32_t compileFlags) { TRACE_EVENT0(GetDevice()->GetPlatform(), General, "ShaderModuleD3D12::Compile"); ASSERT(!IsError()); ScopedTintICEHandler scopedICEHandler(GetDevice()); Device* device = ToBackend(GetDevice()); CompiledShader compiledShader = {}; tint::transform::Manager transformManager; tint::transform::DataMap transformInputs; const tint::Program* program = GetTintProgram(); tint::Program programAsValue; AddExternalTextureTransform(layout, &transformManager, &transformInputs); if (stage == SingleShaderStage::Vertex) { transformManager.Add<tint::transform::FirstIndexOffset>(); transformInputs.Add<tint::transform::FirstIndexOffset::BindingPoint>( layout->GetFirstIndexOffsetShaderRegister(), layout->GetFirstIndexOffsetRegisterSpace()); } tint::transform::DataMap transformOutputs; DAWN_TRY_ASSIGN(programAsValue, RunTransforms(&transformManager, program, transformInputs, &transformOutputs, nullptr)); program = &programAsValue; if (stage == SingleShaderStage::Vertex) { if (auto* data = transformOutputs.Get<tint::transform::FirstIndexOffset::Data>()) { // TODO(dawn:549): Consider adding this information to the pipeline cache once we // can store more than the shader blob in it. compiledShader.firstOffsetInfo.usesVertexIndex = data->has_vertex_index; if (compiledShader.firstOffsetInfo.usesVertexIndex) { compiledShader.firstOffsetInfo.vertexIndexOffset = data->first_vertex_offset; } compiledShader.firstOffsetInfo.usesInstanceIndex = data->has_instance_index; if (compiledShader.firstOffsetInfo.usesInstanceIndex) { compiledShader.firstOffsetInfo.instanceIndexOffset = data->first_instance_offset; } } } ShaderCompilationRequest request; DAWN_TRY_ASSIGN( request, ShaderCompilationRequest::Create( programmableStage.entryPoint.c_str(), stage, layout, compileFlags, device, program, GetEntryPoint(programmableStage.entryPoint), programmableStage)); PersistentCacheKey shaderCacheKey; DAWN_TRY_ASSIGN(shaderCacheKey, request.CreateCacheKey()); DAWN_TRY_ASSIGN( compiledShader.cachedShader, device->GetPersistentCache()->GetOrCreate( shaderCacheKey, [&](auto doCache) -> MaybeError { DAWN_TRY(CompileShader( device->GetPlatform(), device->GetFunctions(), device->IsToggleEnabled(Toggle::UseDXC) ? device->GetDxcLibrary().Get() : nullptr, device->IsToggleEnabled(Toggle::UseDXC) ? device->GetDxcCompiler().Get() : nullptr, std::move(request), device->IsToggleEnabled(Toggle::DumpShaders), [&](WGPULoggingType loggingType, const char* message) { GetDevice()->EmitLog(loggingType, message); }, &compiledShader)); const D3D12_SHADER_BYTECODE shader = compiledShader.GetD3D12ShaderBytecode(); doCache(shader.pShaderBytecode, shader.BytecodeLength); return {}; })); return std::move(compiledShader); } D3D12_SHADER_BYTECODE CompiledShader::GetD3D12ShaderBytecode() const { if (cachedShader.buffer != nullptr) { return {cachedShader.buffer.get(), cachedShader.bufferSize}; } else if (compiledFXCShader != nullptr) { return {compiledFXCShader->GetBufferPointer(), compiledFXCShader->GetBufferSize()}; } else if (compiledDXCShader != nullptr) { return {compiledDXCShader->GetBufferPointer(), compiledDXCShader->GetBufferSize()}; } UNREACHABLE(); return {}; } } // namespace dawn::native::d3d12
47.616197
100
0.55959
[ "vector", "transform" ]
1617584e00ba488160970276e1e79dd0bf70ad93
12,262
inl
C++
Sources/Maths/Vector4.inl
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
43
2017-08-09T04:03:38.000Z
2018-07-17T15:25:32.000Z
Sources/Maths/Vector4.inl
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
3
2018-01-23T06:44:41.000Z
2018-05-29T19:22:41.000Z
Sources/Maths/Vector4.inl
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
6
2017-11-03T10:48:20.000Z
2018-04-28T21:44:59.000Z
#pragma once #include "Files/Node.hpp" #include "Maths.hpp" #include "Vector4.hpp" namespace acid { template<typename T> constexpr Vector4<T>::Vector4(const T &a): x(a), y(a), z(a), w(a) { } template<typename T> constexpr Vector4<T>::Vector4(const T &x, const T &y, const T &z, const T &w): x(x), y(y), z(z), w(w) { } template<typename T> template<typename K, typename J, typename H, typename F> constexpr Vector4<T>::Vector4(const K &x, const J &y, const H &z, const F &w) : x(static_cast<T>(x)), y(static_cast<T>(y)), z(static_cast<T>(z)), w(static_cast<T>(w)) { } template<typename T> template<typename K, typename J> constexpr Vector4<T>::Vector4(const Vector2<K> &left, const Vector2<J> &right): x(static_cast<T>(left.x)), y(static_cast<T>(left.y)), z(static_cast<T>(right.x)), w(static_cast<T>(right.y)) { } template<typename T> template<typename K, typename J> constexpr Vector4<T>::Vector4(const Vector3<K> &source, const J &w): x(static_cast<T>(source.x)), y(static_cast<T>(source.y)), z(static_cast<T>(source.z)), w(static_cast<T>(w)) { } template<typename T> template<typename K> constexpr Vector4<T>::Vector4(const Vector4<K> &source): x(static_cast<T>(source.x)), y(static_cast<T>(source.y)), z(static_cast<T>(source.z)), w(static_cast<T>(source.w)) { } template<typename T> template<typename K> constexpr auto Vector4<T>::Add(const Vector4<K> &other) const { return Vector4<decltype(x + other.x)>(x + other.x, y + other.y, z + other.z, w + other.w); } template<typename T> template<typename K> constexpr auto Vector4<T>::Subtract(const Vector4<K> &other) const { return Vector4<decltype(x - other.x)>(x - other.x, y - other.y, z - other.z, w - other.w); } template<typename T> template<typename K> constexpr auto Vector4<T>::Multiply(const Vector4<K> &other) const { return Vector4<decltype(x * other.x)>(x * other.x, y * other.y, z * other.z, w * other.w); } template<typename T> template<typename K> constexpr auto Vector4<T>::Divide(const Vector4<K> &other) const { return Vector4<decltype(x / other.x)>(x / other.x, y / other.y, z / other.z, w / other.w); } template<typename T> template<typename K> auto Vector4<T>::Angle(const Vector4<K> &other) const { auto dls = Dot(other) / (Length() * other.Length()); if (dls < -1) { dls = -1; } else if (dls > 1) { dls = 1; } return std::acos(dls); } template<typename T> template<typename K> constexpr auto Vector4<T>::Dot(const Vector4<K> &other) const { return x * other.x + y * other.y + z * other.z + w * other.w; } template<typename T> template<typename K, typename J> constexpr auto Vector4<T>::Lerp(const Vector4<K> &other, const J &progression) const { auto ta = *this * (1 - progression); auto tb = other * progression; return ta + tb; } template<typename T> template<typename K> constexpr auto Vector4<T>::Scale(const K &scalar) const { return Vector4<decltype(x * scalar)>(x * scalar, y * scalar, z * scalar, w * scalar); } template<typename T> auto Vector4<T>::Normalize() const { auto l = Length(); if (l == 0) { throw std::runtime_error("Can't normalize a zero length vector"); } return *this / l; } template<typename T> constexpr auto Vector4<T>::LengthSquared() const { return x * x + y * y + z * z + w * w; } template<typename T> auto Vector4<T>::Length() const { return std::sqrt(LengthSquared()); } template<typename T> auto Vector4<T>::Abs() const { return Vector2<T>(std::abs(x), std::abs(y), std::abs(z), std::abs(w)); } template<typename T> constexpr auto Vector4<T>::Min() const { return std::min({x, y, z, w}); } template<typename T> constexpr auto Vector4<T>::Max() const { return std::max({x, y, z, w}); } template<typename T> constexpr auto Vector4<T>::MinMax() const { return std::minmax({x, y, z, w}); } template<typename T> template<typename K> constexpr auto Vector4<T>::Min(const Vector4<K> &other) { using THighestP = decltype(x + other.x); return Vector4<THighestP>(std::min<THighestP>(x, other.x), std::min<THighestP>(y, other.y), std::min<THighestP>(z, other.z), std::min<THighestP>(w, other.w)); } template<typename T> template<typename K> constexpr auto Vector4<T>::Max(const Vector4<K> &other) { using THighestP = decltype(x + other.x); return Vector4<THighestP>(std::max<THighestP>(x, other.x), std::max<THighestP>(y, other.y), std::max<THighestP>(z, other.z), std::max<THighestP>(w, other.w)); } template<typename T> template<typename K> constexpr auto Vector4<T>::DistanceSquared(const Vector4<K> &other) const { auto dx = x - other.x; auto dy = y - other.y; auto dz = z - other.z; auto dw = w - other.w; return dx * dx + dy * dy + dz * dz + dw * dw; } template<typename T> template<typename K> auto Vector4<T>::Distance(const Vector4<K> &other) const { return std::sqrt(DistanceSquared(other)); } template<typename T> template<typename K> constexpr auto Vector4<T>::DistanceVector(const Vector4<K> &other) const { return (*this - other) * (*this - other); } template<typename T> template<typename K, typename J> constexpr auto Vector4<T>::SmoothDamp(const Vector4<K> &target, const Vector4<J> &rate) const { return Maths::SmoothDamp(*this, target, rate); } template<typename T> constexpr const T &Vector4<T>::operator[](uint32_t index) const { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw std::runtime_error("Vector4 index out of bounds!"); } } template<typename T> constexpr T &Vector4<T>::operator[](uint32_t index) { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw std::runtime_error("Vector4 index out of bounds!"); } } template<typename T> template<typename K> constexpr bool Vector4<T>::operator==(const Vector4<K> &other) const { return x == other.x && y == other.y && z == other.z && w == other.w; } template<typename T> template<typename K> constexpr bool Vector4<T>::operator!=(const Vector4<K> &other) const { return !operator==(other); } template<typename T> template<typename U> constexpr auto Vector4<T>::operator-() const -> std::enable_if_t<std::is_signed_v<U>, Vector4<T>> { return {-x, -y, -z, -w}; } template<typename T> template<typename U> constexpr auto Vector4<T>::operator~() const -> std::enable_if_t<std::is_integral_v<U>, Vector4<T>> { return {~x, ~y, ~z, ~w}; } template<typename T> template<typename K> constexpr Vector4<T> &Vector4<T>::operator+=(const Vector4<K> &other) { return *this = Add(other); } template<typename T> template<typename K> constexpr Vector4<T> &Vector4<T>::operator-=(const Vector4<K> &other) { return *this = Subtract(other); } template<typename T> template<typename K> constexpr Vector4<T> &Vector4<T>::operator*=(const Vector4<K> &other) { return *this = Multiply(other); } template<typename T> template<typename K> constexpr Vector4<T> &Vector4<T>::operator/=(const Vector4<K> &other) { return *this = Divide(other); } template<typename T> constexpr Vector4<T> &Vector4<T>::operator+=(const T &other) { return *this = Add(Vector4<T>(other)); } template<typename T> constexpr Vector4<T> &Vector4<T>::operator-=(const T &other) { return *this = Subtract(Vector4<T>(other)); } template<typename T> constexpr Vector4<T> &Vector4<T>::operator*=(const T &other) { return *this = Multiply(Vector4<T>(other)); } template<typename T> constexpr Vector4<T> &Vector4<T>::operator/=(const T &other) { return *this = Divide(Vector4<T>(other)); } template<typename K> const Node &operator>>(const Node &node, Vector4<K> &vector) { node["x"].Get(vector.x); node["y"].Get(vector.y); node["z"].Get(vector.z); node["w"].Get(vector.w); return node; } template<typename K> Node &operator<<(Node &node, const Vector4<K> &vector) { node["x"].Set(vector.x); node["y"].Set(vector.y); node["z"].Set(vector.z); node["w"].Set(vector.w); return node; } template<typename K> std::ostream &operator<<(std::ostream &stream, const Vector4<K> &vector) { return stream << vector.x << ", " << vector.y << ", " << vector.z << ", " << vector.w; } template<typename K, typename J> constexpr auto operator+(const Vector4<K> &left, const Vector4<J> &right) { return left.Add(right); } template<typename K, typename J> constexpr auto operator-(const Vector4<K> &left, const Vector4<J> &right) { return left.Subtract(right); } template<typename K, typename J> constexpr auto operator*(const Vector4<K> &left, const Vector4<J> &right) { return left.Multiply(right); } template<typename K, typename J> constexpr auto operator/(const Vector4<K> &left, const Vector4<J> &right) { return left.Divide(right); } template<typename K, typename J> constexpr auto operator+(const K &left, const Vector4<J> &right) { return Vector4<K>(left).Add(right); } template<typename K, typename J> constexpr auto operator-(const K &left, const Vector4<J> &right) { return Vector4<K>(left).Subtract(right); } template<typename K, typename J> constexpr auto operator*(const K &left, const Vector4<J> &right) { return Vector4<K>(left).Multiply(right); } template<typename K, typename J> constexpr auto operator/(const K &left, const Vector4<J> &right) { return Vector4<K>(left).Divide(right); } template<typename K, typename J> constexpr auto operator+(const Vector4<K> &left, const J &right) { return left.Add(Vector4<J>(right)); } template<typename K, typename J> constexpr auto operator-(const Vector4<K> &left, const J &right) { return left.Subtract(Vector4<J>(right)); } template<typename K, typename J> constexpr auto operator*(const Vector4<K> &left, const J &right) { return left.Multiply(Vector4<J>(right)); } template<typename K, typename J> constexpr auto operator/(const Vector4<K> &left, const J &right) { return left.Divide(Vector4<J>(right)); } template<typename K, typename J> constexpr auto operator&(const Vector4<K> &left, const Vector4<J> &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x & right.x, left.y & right.y, left.z & right.z, left.w & right.w}; } template<typename K, typename J> constexpr auto operator|(const Vector4<K> &left, const Vector4<J> &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x | right.x, left.y | right.y, left.z | right.z, left.w | right.w}; } template<typename K, typename J> constexpr auto operator>>(const Vector4<K> &left, const Vector4<J> &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x >> right.x, left.y >> right.y, left.z >> right.z, left.w >> right.w}; } template<typename K, typename J> constexpr auto operator<<(const Vector4<K> &left, const Vector4<J> &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x << right.x, left.y << right.y, left.z << right.z, left.w << right.w}; } template<typename K, typename J> constexpr auto operator&(const Vector4<K> &left, const J &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x & right, left.y & right, left.z & right, left.w & right}; } template<typename K, typename J> constexpr auto operator|(const Vector4<K> &left, const J &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x | right, left.y | right, left.z | right, left.w | right}; } template<typename K, typename J> constexpr auto operator>>(const Vector4<K> &left, const J &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x >> right, left.y >> right, left.z >> right, left.w >> right}; } template<typename K, typename J> constexpr auto operator<<(const Vector4<K> &left, const J &right) -> std::enable_if_t<std::is_integral_v<K> &&std::is_integral_v<J>, Vector4<J>> { return {left.x << right, left.y << right, left.z << right, left.w << right}; } } namespace std { template<typename T> struct hash<acid::Vector4<T>> { size_t operator()(const acid::Vector4<T> &vector) const noexcept { size_t seed = 0; acid::Maths::HashCombine(seed, vector.x); acid::Maths::HashCombine(seed, vector.y); acid::Maths::HashCombine(seed, vector.z); acid::Maths::HashCombine(seed, vector.w); return seed; } }; }
27.868182
155
0.68488
[ "vector" ]
16193ec7d95f07c128266e6dbef6bf526aeb0fd4
2,764
cpp
C++
libsrc/leddevice/LedDevice.cpp
maximkulkin/hyperion.ng
77299ba077f6ba1457e4c6612b11b5d994847ef8
[ "MIT" ]
1
2020-05-13T21:45:10.000Z
2020-05-13T21:45:10.000Z
libsrc/leddevice/LedDevice.cpp
maximkulkin/hyperion.ng
77299ba077f6ba1457e4c6612b11b5d994847ef8
[ "MIT" ]
null
null
null
libsrc/leddevice/LedDevice.cpp
maximkulkin/hyperion.ng
77299ba077f6ba1457e4c6612b11b5d994847ef8
[ "MIT" ]
null
null
null
#include <leddevice/LedDevice.h> #include <sstream> //QT include #include <QResource> #include <QStringList> #include <QDir> #include <QDateTime> #include "hyperion/Hyperion.h" #include <utils/JsonUtils.h> #include <QDebug> LedDevice::LedDevice(const QJsonObject& config, QObject* parent) : QObject(parent) , _devConfig(config) , _log(Logger::getInstance("LEDDEVICE")) , _ledBuffer(0) , _deviceReady(true) , _refresh_timer() , _refresh_timer_interval(0) , _last_write_time(QDateTime::currentMSecsSinceEpoch()) , _latchTime_ms(0) , _componentRegistered(false) , _enabled(true) { // setup timer _refresh_timer.setInterval(0); connect(&_refresh_timer, SIGNAL(timeout()), this, SLOT(rewriteLeds())); } LedDevice::~LedDevice() { } // dummy implemention int LedDevice::open() { return 0; } void LedDevice::setEnable(bool enable) { // emit signal when state changed if (_enabled != enable) emit enableStateChanged(enable); // set black to leds when they should go off if ( _enabled && !enable) switchOff(); _enabled = enable; } void LedDevice::setActiveDevice(QString dev) { _activeDevice = dev; } bool LedDevice::init(const QJsonObject &deviceConfig) { _colorOrder = deviceConfig["colorOrder"].toString("RGB"); _activeDevice = deviceConfig["type"].toString("file").toLower(); setLedCount(deviceConfig["currentLedCount"].toInt(1)); // property injected to reflect real led count _latchTime_ms = deviceConfig["latchTime"].toInt(_latchTime_ms); _refresh_timer.setInterval( deviceConfig["rewriteTime"].toInt( _refresh_timer_interval) ); if (_refresh_timer.interval() <= (signed)_latchTime_ms ) { Warning(_log, "latchTime(%d) is bigger/equal rewriteTime(%d)", _refresh_timer.interval(), _latchTime_ms); _refresh_timer.setInterval(_latchTime_ms+10); } return true; } int LedDevice::setLedValues(const std::vector<ColorRgb>& ledValues) { int retval = 0; if (!_deviceReady || !_enabled) return -1; // restart the timer if (_refresh_timer.interval() > 0) { _refresh_timer.start(); } if (_latchTime_ms == 0 || QDateTime::currentMSecsSinceEpoch()-_last_write_time >= _latchTime_ms) { _ledValues = ledValues; retval = write(ledValues); _last_write_time = QDateTime::currentMSecsSinceEpoch(); } //else Debug(_log, "latch %d", QDateTime::currentMSecsSinceEpoch()-_last_write_time); return retval; } int LedDevice::switchOff() { return _deviceReady ? write(std::vector<ColorRgb>(_ledCount, ColorRgb::BLACK )) : -1; } int LedDevice::switchOn() { return 0; } void LedDevice::setLedCount(int ledCount) { _ledCount = ledCount; _ledRGBCount = _ledCount * sizeof(ColorRgb); _ledRGBWCount = _ledCount * sizeof(ColorRgbw); } int LedDevice::rewriteLeds() { return _enabled ? write(_ledValues) : -1; }
22.290323
107
0.730825
[ "vector" ]
161cc659bf971a758406d42573a43299327f0b43
15,714
hpp
C++
include/mesos/scheduler.hpp
jeid64/mesos
3a69423b850cdc2f8fc4a334c72a38c8580f44c2
[ "Apache-2.0" ]
null
null
null
include/mesos/scheduler.hpp
jeid64/mesos
3a69423b850cdc2f8fc4a334c72a38c8580f44c2
[ "Apache-2.0" ]
null
null
null
include/mesos/scheduler.hpp
jeid64/mesos
3a69423b850cdc2f8fc4a334c72a38c8580f44c2
[ "Apache-2.0" ]
null
null
null
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MESOS_SCHEDULER_HPP__ #define __MESOS_SCHEDULER_HPP__ #include <string> #include <vector> #include <mesos/mesos.hpp> /** * Mesos scheduler interface and scheduler driver. A scheduler is used * to interact with Mesos in order run distributed computations. * * IF YOU FIND YOURSELF MODIFYING COMMENTS HERE PLEASE CONSIDER MAKING * THE SAME MODIFICATIONS FOR OTHER LANGUAGE BINDINGS (e.g., Java: * src/java/src/org/apache/mesos, Python: src/python/src, etc.). */ namespace mesos { // A few forward declarations. class SchedulerDriver; namespace internal { class MasterDetector; class SchedulerProcess; } /** * Callback interface to be implemented by frameworks' * schedulers. Note that only one callback will be invoked at a time, * so it is not recommended that you block within a callback because * it may cause a deadlock. * * Each callback includes a pointer to the scheduler driver that was * used to run this scheduler. The pointer will not change for the * duration of a scheduler (i.e., from the point you do * SchedulerDriver::start() to the point that SchedulerDriver::join() * returns). This is intended for convenience so that a scheduler * doesn't need to store a pointer to the driver itself. */ class Scheduler { public: /** * Empty virtual destructor (necessary to instantiate subclasses). */ virtual ~Scheduler() {} /** * Invoked when the scheduler successfully registers with a Mesos * master. A unique ID (generated by the master) used for * distinguishing this framework from others and MasterInfo * with the ip and port of the current master are provided as arguments. */ virtual void registered(SchedulerDriver* driver, const FrameworkID& frameworkId, const MasterInfo& masterInfo) = 0; /** * Invoked when the scheduler re-registers with a newly elected Mesos master. * This is only called when the scheduler has previously been registered. * MasterInfo containing the updated information about the elected master * is provided as an argument. */ virtual void reregistered(SchedulerDriver* driver, const MasterInfo& masterInfo) = 0; /** * Invoked when the scheduler becomes "disconnected" from the master * (e.g., the master fails and another is taking over). */ virtual void disconnected(SchedulerDriver* driver) = 0; /** * Invoked when resources have been offered to this framework. A * single offer will only contain resources from a single slave. * Resources associated with an offer will not be re-offered to * _this_ framework until either (a) this framework has rejected * those resources (see SchedulerDriver::launchTasks) or (b) those * resources have been rescinded (see Scheduler::offerRescinded). * Note that resources may be concurrently offered to more than one * framework at a time (depending on the allocator being used). In * that case, the first framework to launch tasks using those * resources will be able to use them while the other frameworks * will have those resources rescinded (or if a framework has * already launched tasks with those resources then those tasks will * fail with a TASK_LOST status and a message saying as much). */ virtual void resourceOffers(SchedulerDriver* driver, const std::vector<Offer>& offers) = 0; /** * Invoked when an offer is no longer valid (e.g., the slave was * lost or another framework used resources in the offer). If for * whatever reason an offer is never rescinded (e.g., dropped * message, failing over framework, etc.), a framwork that attempts * to launch tasks using an invalid offer will receive TASK_LOST * status updates for those tasks (see Scheduler::resourceOffers). */ virtual void offerRescinded(SchedulerDriver* driver, const OfferID& offerId) = 0; /** * Invoked when the status of a task has changed (e.g., a slave is * lost and so the task is lost, a task finishes and an executor * sends a status update saying so, etc). Note that returning from * this callback _acknowledges_ receipt of this status update! If * for whatever reason the scheduler aborts during this callback (or * the process exits) another status update will be delivered (note, * however, that this is currently not true if the slave sending the * status update is lost/fails during that time). */ virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status) = 0; /** * Invoked when an executor sends a message. These messages are best * effort; do not expect a framework message to be retransmitted in * any reliable fashion. */ virtual void frameworkMessage(SchedulerDriver* driver, const ExecutorID& executorId, const SlaveID& slaveId, const std::string& data) = 0; /** * Invoked when a slave has been determined unreachable (e.g., * machine failure, network partition). Most frameworks will need to * reschedule any tasks launched on this slave on a new slave. */ virtual void slaveLost(SchedulerDriver* driver, const SlaveID& slaveId) = 0; /** * Invoked when an executor has exited/terminated. Note that any * tasks running will have TASK_LOST status updates automagically * generated. */ virtual void executorLost(SchedulerDriver* driver, const ExecutorID& executorId, const SlaveID& slaveId, int status) = 0; /** * Invoked when there is an unrecoverable error in the scheduler or * scheduler driver. The driver will be aborted BEFORE invoking this * callback. */ virtual void error(SchedulerDriver* driver, const std::string& message) = 0; }; /** * Abstract interface for connecting a scheduler to Mesos. This * interface is used both to manage the scheduler's lifecycle (start * it, stop it, or wait for it to finish) and to interact with Mesos * (e.g., launch tasks, kill tasks, etc.). See MesosSchedulerDriver * below for a concrete example of a SchedulerDriver. */ class SchedulerDriver { public: /** * Empty virtual destructor (necessary to instantiate subclasses). * It is expected that 'stop()' is called before this is called. */ virtual ~SchedulerDriver() {} /** * Starts the scheduler driver. This needs to be called before any * other driver calls are made. */ virtual Status start() = 0; /** * Stops the scheduler driver. If the 'failover' flag is set to * false then it is expected that this framework will never * reconnect to Mesos and all of its executors and tasks can be * terminated. Otherwise, all executors and tasks will remain * running (for some framework specific failover timeout) allowing the * scheduler to reconnect (possibly in the same process, or from a * different process, for example, on a different machine). */ virtual Status stop(bool failover = false) = 0; /** * Aborts the driver so that no more callbacks can be made to the * scheduler. The semantics of abort and stop have deliberately been * separated so that code can detect an aborted driver (i.e., via * the return status of SchedulerDriver::join, see below), and * instantiate and start another driver if desired (from within the * same process). Note that 'stop()' is not automatically called * inside 'abort()'. */ virtual Status abort() = 0; /** * Waits for the driver to be stopped or aborted, possibly * _blocking_ the current thread indefinitely. The return status of * this function can be used to determine if the driver was aborted * (see mesos.proto for a description of Status). */ virtual Status join() = 0; /** * Starts and immediately joins (i.e., blocks on) the driver. */ virtual Status run() = 0; /** * Requests resources from Mesos (see mesos.proto for a description * of Request and how, for example, to request resources * from specific slaves). Any resources available are offered to the * framework via Scheduler::resourceOffers callback, asynchronously. */ virtual Status requestResources(const std::vector<Request>& requests) = 0; /** * Launches the given set of tasks. Any resources remaining (i.e., * not used by the tasks or their executors) will be considered * declined. The specified filters are applied on all unused * resources (see mesos.proto for a description of Filters). * Invoking this function with an empty collection of tasks declines * this offer in its entirety (see Scheduler::declineOffer). Note * that currently tasks can only be launched per offer. In the * future, frameworks will be allowed to aggregate offers * (resources) to launch their tasks. */ virtual Status launchTasks(const OfferID& offerId, const std::vector<TaskInfo>& tasks, const Filters& filters = Filters()) = 0; /** * Kills the specified task. Note that attempting to kill a task is * currently not reliable. If, for example, a scheduler fails over * while it was attempting to kill a task it will need to retry in * the future. Likewise, if unregistered / disconnected, the request * will be dropped (these semantics may be changed in the future). */ virtual Status killTask(const TaskID& taskId) = 0; /** * Declines an offer in its entirety and applies the specified * filters on the resources (see mesos.proto for a description of * Filters). Note that this can be done at any time, it is not * necessary to do this within the Scheduler::resourceOffers * callback. */ virtual Status declineOffer(const OfferID& offerId, const Filters& filters = Filters()) = 0; /** * Removes all filters previously set by the framework (via * launchTasks()). This enables the framework to receive offers from * those filtered slaves. */ virtual Status reviveOffers() = 0; /** * Sends a message from the framework to one of its executors. These * messages are best effort; do not expect a framework message to be * retransmitted in any reliable fashion. */ virtual Status sendFrameworkMessage(const ExecutorID& executorId, const SlaveID& slaveId, const std::string& data) = 0; /** * Reconciliation of tasks causes the master to send status updates for tasks * whose status differs from the status sent here. */ virtual Status reconcileTasks( const std::vector<TaskStatus>& statuses) = 0; }; /** * Concrete implementation of a SchedulerDriver that connects a * Scheduler with a Mesos master. The MesosSchedulerDriver is * thread-safe. * * Note that scheduler failover is supported in Mesos. After a * scheduler is registered with Mesos it may failover (to a new * process on the same machine or across multiple machines) by * creating a new driver with the ID given to it in * Scheduler::registered. * * The driver is responsible for invoking the Scheduler callbacks as * it communicates with the Mesos master. * * Note that blocking on the MesosSchedulerDriver (e.g., via * MesosSchedulerDriver::join) doesn't affect the scheduler callbacks * in anyway because they are handled by a different thread. * * See src/examples/test_framework.cpp for an example of using the * MesosSchedulerDriver. */ class MesosSchedulerDriver : public SchedulerDriver { public: /** * Creates a new driver for the specified scheduler. The master * should be one of: * * host:port * zk://host1:port1,host2:port2,.../path * zk://username:password@host1:port1,host2:port2,.../path * file:///path/to/file (where file contains one of the above) * * The driver will attempt to "failover" if the specified * FrameworkInfo includes a valid FrameworkID. * * Any Mesos configuration options are read from environment * variables, as well as any configuration files found through the * environment variables. * * TODO(vinod): Deprecate this once 'MesosSchedulerDriver' can * take 'Option<Credential>' as parameter. Currently it cannot * because 'stout' is not visible from here. */ MesosSchedulerDriver(Scheduler* scheduler, const FrameworkInfo& framework, const std::string& master); /** * Same as the above constructor but takes 'credential' as argument. * * The credential will be used for authenticating with the master. */ MesosSchedulerDriver(Scheduler* scheduler, const FrameworkInfo& framework, const std::string& master, const Credential& credential); /** * This destructor will block indefinitely if * MesosSchedulerDriver::start was invoked successfully (possibly * via MesosSchedulerDriver::run) and MesosSchedulerDriver::stop has * not been invoked. */ virtual ~MesosSchedulerDriver(); /** * See SchedulerDriver for descriptions of these. */ virtual Status start(); virtual Status stop(bool failover = false); virtual Status abort(); virtual Status join(); virtual Status run(); virtual Status requestResources(const std::vector<Request>& requests); virtual Status launchTasks(const OfferID& offerId, const std::vector<TaskInfo>& tasks, const Filters& filters = Filters()); virtual Status killTask(const TaskID& taskId); virtual Status declineOffer(const OfferID& offerId, const Filters& filters = Filters()); virtual Status reviveOffers(); virtual Status sendFrameworkMessage(const ExecutorID& executorId, const SlaveID& slaveId, const std::string& data); virtual Status reconcileTasks( const std::vector<TaskStatus>& statuses); private: Scheduler* scheduler; FrameworkInfo framework; std::string master; // Used for communicating with the master. internal::SchedulerProcess* process; // URL for the master (e.g., zk://, file://, etc). std::string url; // Mutex to enforce all non-callbacks are execute serially. pthread_mutex_t mutex; // Condition variable for waiting until driver terminates. pthread_cond_t cond; // Current status of the driver. Status status; const Credential* credential; protected: // Used to detect (i.e., choose) the master. internal::MasterDetector* detector; }; } // namespace mesos { #endif // __MESOS_SCHEDULER_HPP__
37.86506
79
0.68964
[ "vector" ]
161cf8f8bbb1bdc056d1af577ef956b7ce510e30
174,685
cpp
C++
src/modules/keyboardmanager/test/BufferValidationTests.cpp
MikkoWrightson/PowerToys
3375ddcdb666146c1641e15f12fefc31d64a892a
[ "MIT" ]
2
2021-08-29T16:26:08.000Z
2021-10-31T09:43:46.000Z
src/modules/keyboardmanager/test/BufferValidationTests.cpp
MikkoWrightson/PowerToys
3375ddcdb666146c1641e15f12fefc31d64a892a
[ "MIT" ]
2
2022-02-15T12:30:12.000Z
2022-02-28T03:21:12.000Z
src/modules/keyboardmanager/test/BufferValidationTests.cpp
MikkoWrightson/PowerToys
3375ddcdb666146c1641e15f12fefc31d64a892a
[ "MIT" ]
1
2021-02-12T16:22:53.000Z
2021-02-12T16:22:53.000Z
#include "pch.h" #include "CppUnitTest.h" #include <keyboardmanager/ui/BufferValidationHelpers.h> #include "TestHelpers.h" #include <common/keyboard_layout.h> #include <common/shared_constants.h> #include <functional> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace TestHelpers; namespace RemappingUITests { // Tests for methods in the BufferValidationHelpers namespace TEST_CLASS (BufferValidationTests) { std::wstring testApp1 = L"testprocess1.exe"; std::wstring testApp2 = L"testprocess2.exe"; LayoutMap keyboardLayout; struct ValidateAndUpdateKeyBufferElementArgs { int elementRowIndex; int elementColIndex; int selectedIndexFromDropDown; }; struct ValidateShortcutBufferElementArgs { int elementRowIndex; int elementColIndex; uint32_t indexOfDropDownLastModified; std::vector<int32_t> selectedIndicesOnDropDowns; std::wstring targetAppNameInTextBox; bool isHybridColumn; RemapBufferRow bufferRow; }; void RunTestCases(const std::vector<ValidateShortcutBufferElementArgs>& testCases, std::function<void(const ValidateShortcutBufferElementArgs&)> testMethod) { for (int i = 0; i < testCases.size(); i++) { testMethod(testCases[i]); } } public: TEST_METHOD_INITIALIZE(InitializeTestEnv) { } // Test if the ValidateAndUpdateKeyBufferElement method is successful when setting a key to null in a new row TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldUpdateAndReturnNoError_OnSettingKeyToNullInANewRow) { RemapBuffer remapBuffer; // Add 2 empty rows remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, NULL }), std::wstring())); remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, NULL }), std::wstring())); // Validate and update the element when -1 i.e. null selection is made on an empty row. ValidateAndUpdateKeyBufferElementArgs args = { 0, 0, -1 }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is validated and buffer is updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[0].first[0])); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[0].first[1])); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[1].first[0])); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[1].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is successful when setting a key to non-null in a new row TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldUpdateAndReturnNoError_OnSettingKeyToNonNullInANewRow) { RemapBuffer remapBuffer; // Add an empty row remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, NULL }), std::wstring())); // Validate and update the element when selecting B on an empty row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 0, 0, GetDropDownIndexFromDropDownList(0x42, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is validated and buffer is updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual((DWORD)0x42, std::get<DWORD>(remapBuffer[0].first[0])); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[0].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is successful when setting a key to non-null in a valid key to key TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldUpdateAndReturnNoError_OnSettingKeyToNonNullInAValidKeyToKeyRow) { RemapBuffer remapBuffer; // Add a row with A as the target remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, 0x41 }), std::wstring())); // Validate and update the element when selecting B on a row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 0, 0, GetDropDownIndexFromDropDownList(0x42, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is validated and buffer is updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual((DWORD)0x42, std::get<DWORD>(remapBuffer[0].first[0])); Assert::AreEqual((DWORD)0x41, std::get<DWORD>(remapBuffer[0].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is successful when setting a key to non-null in a valid key to shortcut TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldUpdateAndReturnNoError_OnSettingKeyToNonNullInAValidKeyToShortcutRow) { RemapBuffer remapBuffer; // Add a row with Ctrl+A as the target remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, Shortcut(std::vector<DWORD>{ VK_CONTROL, 0x41 }) }), std::wstring())); // Validate and update the element when selecting B on a row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 0, 0, GetDropDownIndexFromDropDownList(0x42, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is validated and buffer is updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual((DWORD)0x42, std::get<DWORD>(remapBuffer[0].first[0])); Assert::AreEqual(true, Shortcut(std::vector<DWORD>{ VK_CONTROL, 0x41 }) == std::get<Shortcut>(remapBuffer[0].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is unsuccessful when setting first column to the same value as the right column TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldReturnMapToSameKeyError_OnSettingFirstColumnToSameValueAsRightColumn) { RemapBuffer remapBuffer; // Add a row with A as the target remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, 0x41 }), std::wstring())); // Validate and update the element when selecting A on a row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 0, 0, GetDropDownIndexFromDropDownList(0x41, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is invalid and buffer is not updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::MapToSameKey); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[0].first[0])); Assert::AreEqual((DWORD)0x41, std::get<DWORD>(remapBuffer[0].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is unsuccessful when setting first column of a key to key row to the same value as in another row TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldReturnSameKeyPreviouslyMappedError_OnSettingFirstColumnOfAKeyToKeyRowToSameValueAsInAnotherRow) { RemapBuffer remapBuffer; // Add a row from A->B and a row with C as target remapBuffer.push_back(std::make_pair(RemapBufferItem({ 0x41, 0x42 }), std::wstring())); remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, 0x43 }), std::wstring())); // Validate and update the element when selecting A on second row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 1, 0, GetDropDownIndexFromDropDownList(0x41, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is invalid and buffer is not updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::SameKeyPreviouslyMapped); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[1].first[0])); Assert::AreEqual((DWORD)0x43, std::get<DWORD>(remapBuffer[1].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is unsuccessful when setting first column of a key to shortcut row to the same value as in another row TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldReturnSameKeyPreviouslyMappedError_OnSettingFirstColumnOfAKeyToShortcutRowToSameValueAsInAnotherRow) { RemapBuffer remapBuffer; // Add a row from A->B and a row with Ctrl+A as target remapBuffer.push_back(std::make_pair(RemapBufferItem({ 0x41, 0x42 }), std::wstring())); remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, Shortcut(std::vector<DWORD>{ VK_CONTROL, 0x41 }) }), std::wstring())); // Validate and update the element when selecting A on second row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 1, 0, GetDropDownIndexFromDropDownList(0x41, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is invalid and buffer is not updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::SameKeyPreviouslyMapped); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[1].first[0])); Assert::AreEqual(true, Shortcut(std::vector<DWORD>{ VK_CONTROL, 0x41 }) == std::get<Shortcut>(remapBuffer[1].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is unsuccessful when setting first column of a key to key row to a conflicting modifier with another row TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldReturnConflictingModifierKeyError_OnSettingFirstColumnOfAKeyToKeyRowToConflictingModifierWithAnotherRow) { RemapBuffer remapBuffer; // Add a row from Ctrl->B and a row with C as target remapBuffer.push_back(std::make_pair(RemapBufferItem({ VK_CONTROL, 0x42 }), std::wstring())); remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, 0x43 }), std::wstring())); // Validate and update the element when selecting LCtrl on second row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 1, 0, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is invalid and buffer is not updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::ConflictingModifierKey); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[1].first[0])); Assert::AreEqual((DWORD)0x43, std::get<DWORD>(remapBuffer[1].first[1])); } // Test if the ValidateAndUpdateKeyBufferElement method is unsuccessful when setting first column of a key to shortcut row to a conflicting modifier with another row TEST_METHOD (ValidateAndUpdateKeyBufferElement_ShouldReturnConflictingModifierKeyError_OnSettingFirstColumnOfAKeyToShortcutRowToConflictingModifierWithAnotherRow) { RemapBuffer remapBuffer; // Add a row from Ctrl->B and a row with Ctrl+A as target remapBuffer.push_back(std::make_pair(RemapBufferItem({ VK_CONTROL, 0x42 }), std::wstring())); remapBuffer.push_back(std::make_pair(RemapBufferItem({ NULL, Shortcut(std::vector<DWORD>{ VK_CONTROL, 0x41 }) }), std::wstring())); // Validate and update the element when selecting LCtrl on second row std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(false); ValidateAndUpdateKeyBufferElementArgs args = { 1, 0, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList) }; KeyboardManagerHelper::ErrorType error = BufferValidationHelpers::ValidateAndUpdateKeyBufferElement(args.elementRowIndex, args.elementColIndex, args.selectedIndexFromDropDown, keyboardLayout.GetKeyCodeList(false), remapBuffer); // Assert that the element is invalid and buffer is not updated Assert::AreEqual(true, error == KeyboardManagerHelper::ErrorType::ConflictingModifierKey); Assert::AreEqual((DWORD)NULL, std::get<DWORD>(remapBuffer[1].first[0])); Assert::AreEqual(true, Shortcut(std::vector<DWORD>{ VK_CONTROL, 0x41 }) == std::get<Shortcut>(remapBuffer[1].first[1])); } // Test if the ValidateShortcutBufferElement method is successful and no drop down action is required on setting a column to null in a new or valid row TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndNoAction_OnSettingColumnToNullInANewOrValidRow) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when making null-selection (-1 index) on first column of empty shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when making null-selection (-1 index) on second column of empty shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when making null-selection (-1 index) on first column of empty shortcut to key row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), NULL }, std::wstring()) }); // Case 4: Validate the element when making null-selection (-1 index) on second column of empty shortcut to key row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), NULL }, std::wstring()) }); // Case 5: Validate the element when making null-selection (-1 index) on first dropdown of first column of valid shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>({ -1, GetDropDownIndexFromDropDownList(0x43, keyList) }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 6: Validate the element when making null-selection (-1 index) on first dropdown of second column of valid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>({ -1, GetDropDownIndexFromDropDownList(0x41, keyList) }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 7: Validate the element when making null-selection (-1 index) on first dropdown of second column of valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>({ -1, GetDropDownIndexFromDropDownList(0x41, keyList) }), std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 8: Validate the element when making null-selection (-1 index) on second dropdown of first column of valid shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1 }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 9: Validate the element when making null-selection (-1 index) on second dropdown of second column of valid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1 }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 10: Validate the element when making null-selection (-1 index) on second dropdown of second column of valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1 }), std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 11: Validate the element when making null-selection (-1 index) on first dropdown of first column of valid 3 key shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>({ -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x44, keyList) }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 12: Validate the element when making null-selection (-1 index) on first dropdown of second column of valid 3 key shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>({ -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 13: Validate the element when making null-selection (-1 index) on first dropdown of second column of valid hybrid 3 key shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>({ -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }), std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 14: Validate the element when making null-selection (-1 index) on second dropdown of first column of valid 3 key shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x44, keyList) }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 15: Validate the element when making null-selection (-1 index) on second dropdown of second column of valid 3 key shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x42, keyList) }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 16: Validate the element when making null-selection (-1 index) on second dropdown of second column of valid hybrid 3 key shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x42, keyList) }), std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 17: Validate the element when making null-selection (-1 index) on third dropdown of first column of valid 3 key shortcut to shortcut row testCases.push_back({ 0, 0, 2, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), -1 }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 18: Validate the element when making null-selection (-1 index) on third dropdown of second column of valid 3 key shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), -1 }), std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 19: Validate the element when making null-selection (-1 index) on third dropdown of second column of valid hybrid 3 key shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>({ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), -1 }), std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x44 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and no drop down action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutStartWithModifier error and no drop down action is required on setting first drop down to an action key on a non-hybrid control column TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutStartWithModifierErrorAndNoAction_OnSettingFirstDropDownToActionKeyOnANonHybridColumn) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on first dropdown of first column of empty shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41) on first dropdown of second column of empty shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when selecting A (0x41) on first dropdown of first column of empty shortcut to key row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), NULL }, std::wstring()) }); // Case 4: Validate the element when selecting A (0x41) on first dropdown of first column of valid shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no drop down action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutStartWithModifier); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns no error and no drop down action is required on setting first drop down to an action key on an empty hybrid control column TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndNoAction_OnSettingFirstDropDownToActionKeyOnAnEmptyHybridColumn) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on first dropdown of second column of empty shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41) on first dropdown of second column of empty shortcut to key row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), NULL }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and no drop down action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutNotMoreThanOneActionKey error and no drop down action is required on setting first drop down to an action key on a hybrid control column with full shortcut TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutNotMoreThanOneActionKeyAndNoAction_OnSettingNonLastDropDownToActionKeyOnAHybridColumnWithFullShortcut) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on first dropdown of second column of hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41) on second dropdown of second column of hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no drop down action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutNotMoreThanOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutNotMoreThanOneActionKey error and no drop down action is required on setting non first non last drop down to an action key on a non hybrid control column with full shortcut TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutNotMoreThanOneActionKeyAndNoAction_OnSettingNonFirstNonLastDropDownToActionKeyOnANonHybridColumnWithFullShortcut) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on second dropdown of first column of shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41)on second dropdown of second column of shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no drop down action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutNotMoreThanOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns no error and no drop down action is required on setting last drop down to an action key on a column with atleast two drop downs TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndNoAction_OnSettingLastDropDownToActionKeyOnAColumnWithAtleastTwoDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on last dropdown of first column of three key shortcut to shortcut row testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41) on last dropdown of second column of three key shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting A (0x41) on last dropdown of hybrid second column of three key shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting A (0x41) on last dropdown of first column of two key shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 5: Validate the element when selecting A (0x41) on last dropdown of second column of two key shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 6: Validate the element when selecting A (0x41) on last dropdown of hybrid second column of two key shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and no drop down action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns no error and ClearUnusedDropDowns action is required on setting non first drop down to an action key on a column if all the drop downs after it are empty TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndClearUnusedDropDownsAction_OnSettingNonFirstDropDownToActionKeyOnAColumnIfAllTheDropDownsAfterItAreEmpty) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on second dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41) on second dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting A (0x41) on second dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting A (0x41) on second dropdown of first column of empty 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting A (0x41) on second dropdown of second column of empty 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 6: Validate the element when selecting A (0x41) on second dropdown of second column of empty 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and ClearUnusedDropDowns action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::ClearUnusedDropDowns); }); } // Test if the ValidateShortcutBufferElement method returns no error and ClearUnusedDropDowns action is required on setting first drop down to an action key on a hybrid column if all the drop downs after it are empty TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndClearUnusedDropDownsAction_OnSettingFirstDropDownToActionKeyOnAHybridColumnIfAllTheDropDownsAfterItAreEmpty) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on first dropdown of second column of empty 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList), -1, -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and ClearUnusedDropDowns action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::ClearUnusedDropDowns); }); } // Test if the ValidateShortcutBufferElement method returns no error and AddDropDown action is required on setting last drop down to a non-repeated modifier key on a column there are less than 3 drop downs TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndAddDropDownAction_OnSettingLastDropDownToNonRepeatedModifierKeyOnAColumnIfThereAreLessThan3DropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column of 2 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting Shift (VK_SHIFT) on second dropdown of second column of 2 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting Shift (VK_SHIFT) on second dropdown of second column of 2 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of first column of 1 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 1 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 6: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 1 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 7: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 1 dropdown hybrid shortcut to key row with an action key selected testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), 0x44 }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and AddDropDown action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::AddDropDown); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutCannotHaveRepeatedModifier error and no action is required on setting last drop down to a repeated modifier key on a column there are less than 3 drop downs TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutCannotHaveRepeatedModifierErrorAndNoAction_OnSettingLastDropDownToRepeatedModifierKeyOnAColumnIfThereAreLessThan3DropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting LCtrl (VK_LCONTROL) on second dropdown of first column of 2 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting LCtrl (VK_LCONTROL) on second dropdown of second column of 2 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting LCtrl (VK_LCONTROL) on second dropdown of second column of 2 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutCannotHaveRepeatedModifier); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutMaxShortcutSizeOneActionKey error and no action is required on setting last drop down to a non repeated modifier key on a column there 3 or more drop downs TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutMaxShortcutSizeOneActionKeyErrorAndNoAction_OnSettingLastDropDownToNonRepeatedModifierKeyOnAColumnIfThereAre3OrMoreDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of first column of 3 dropdown shortcut to shortcut row with middle empty testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of second column of 3 dropdown shortcut to shortcut row with middle empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of second column of 3 dropdown hybrid shortcut to shortcut row with middle empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of first column of 3 dropdown shortcut to shortcut row with first two empty testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ -1, -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of second column of 3 dropdown shortcut to shortcut row with first two empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ -1, -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 6: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of second column of 3 dropdown hybrid shortcut to shortcut row with first two empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ -1, -1, GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 7: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 8: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 9: Validate the element when selecting Shift (VK_SHIFT) on last dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutMaxShortcutSizeOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutMaxShortcutSizeOneActionKey error and no action is required on setting last drop down to a repeated modifier key on a column there 3 or more drop downs TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutMaxShortcutSizeOneActionKeyErrorAndNoAction_OnSettingLastDropDownToRepeatedModifierKeyOnAColumnIfThereAre3OrMoreDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Ctrl (VK_CONTROL) on last dropdown of first column of 3 dropdown shortcut to shortcut row with middle empty testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting Ctrl (VK_CONTROL) on last dropdown of second column of 3 dropdown shortcut to shortcut row with middle empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting Ctrl (VK_CONTROL) on last dropdown of second column of 3 dropdown hybrid shortcut to shortcut row with middle empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting Ctrl (VK_CONTROL) on last dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 5: Validate the element when selecting Ctrl (VK_CONTROL) on last dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 6: Validate the element when selecting Ctrl (VK_CONTROL) on last dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutMaxShortcutSizeOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns no error and no action is required on setting non-last drop down to a non repeated modifier key on a column TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndNoAction_OnSettingNonLastDropDownToNonRepeatedModifierKeyOnAColumn) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of first column of 2 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 2 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 2 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 5: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 6: Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 7: Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 8: Validate the element when selecting Shift (VK_SHIFT) on second dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 9: Validate the element when selecting Shift (VK_SHIFT) on second dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutCannotHaveRepeatedModifier error and no action is required on setting non-last drop down to a repeated modifier key on a column TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutCannotHaveRepeatedModifierErrorAndNoAction_OnSettingNonLastDropDownToRepeatedModifierKeyOnAColumn) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column of 3 dropdown shortcut to shortcut row with first empty testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 2: Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of second column of 3 dropdown shortcut to shortcut row with first empty testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 3: Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of second column of 3 dropdown hybrid shortcut to shortcut row with first empty testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting Alt (VK_MENU) on first dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 5: Validate the element when selecting Alt (VK_MENU) on first dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 6: Validate the element when selecting Alt (VK_MENU) on first dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 7: Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of first column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 8: Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of second column of 3 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 9: Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of second column of 3 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutCannotHaveRepeatedModifier); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutStartWithModifier error and no action is required on setting first drop down to None on a non-hybrid column with one drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutStartWithModifierErrorAndNoAction_OnSettingFirstDropDownToNoneOnNonHybridColumnWithOneDropDown) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on first dropdown of first column of 1 dropdown shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting None (0) on first dropdown of second column of 1 dropdown shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutStartWithModifier); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutOneActionKey error and no action is required on setting first drop down to None on a hybrid column with one drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutOneActionKeyErrorAndNoAction_OnSettingFirstDropDownToNoneOnHybridColumnWithOneDropDown) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on first dropdown of first column of 1 dropdown hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutAtleast2Keys error and no action is required on setting first drop down to None on a non-hybrid column with two drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutAtleast2KeysAndNoAction_OnSettingFirstDropDownToNoneOnNonHybridColumnWithTwoDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on first dropdown of first column of 2 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ 0, -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting None (0) on first dropdown of second column of 2 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when selecting None (0) on first dropdown of second column of 2 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting None (0) on first dropdown of second column of 2 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutAtleast2Keys); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutOneActionKey error and no action is required on setting second drop down to None on a non-hybrid column with two drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutOneActionKeyAndNoAction_OnSettingSecondDropDownToNoneOnNonHybridColumnWithTwoDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on second dropdown of first column of 2 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ -1, 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting None (0) on second dropdown of second column of 2 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when selecting None (0) on second dropdown of second column of 2 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting None (0) on second dropdown of second column of 2 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns no error and DeleteDropDown action is required on setting drop down to None on a hybrid column with two drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndDeleteDropDownAction_OnSettingDropDownToNoneOnHybridColumnWithTwoDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on first dropdown of second column of 2 dropdown empty hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting None (0) on second dropdown of second column of 2 dropdown empty hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, 0 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when selecting None (0) on first dropdown of second column of 2 dropdown valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); // Case 4: Validate the element when selecting None (0) on second dropdown of second column of 2 dropdown valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0 }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and DeleteDropDown action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::DeleteDropDown); }); } // Test if the ValidateShortcutBufferElement method returns no error and DeleteDropDown action is required on setting non last drop down to None on a column with three drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoErrorAndDeleteDropDownAction_OnSettingNonLastDropDownToNoneOnColumnWithThreeDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on first dropdown of first column of 3 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ 0, -1, -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, -1, -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown empty hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, -1, -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 4: Validate the element when selecting None (0) on second dropdown of first column of 3 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ -1, 0, -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting None (0) on second dropdown of second column of 3 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, 0, -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 6: Validate the element when selecting None (0) on second dropdown of second column of 3 dropdown empty hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, 0, -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 7: Validate the element when selecting None (0) on first dropdown of first column of 3 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 8: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 9: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 10: Validate the element when selecting None (0) on first dropdown of first column of 3 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 11: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 12: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x42, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid and DeleteDropDown action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::DeleteDropDown); }); } // Test if the ValidateShortcutBufferElement method returns ShortcutOneActionKey error and no action is required on setting last drop down to None on a column with three drop down TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnShortcutOneActionKeyErrorAndNoAction_OnSettingLastDropDownToNoneOnColumnWithThreeDropDowns) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting None (0) on first dropdown of first column of 3 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ -1, -1, 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown empty shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ -1, -1, 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 3: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown empty hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ -1, -1, 0 }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), Shortcut() }, std::wstring()) }); // Case 4: Validate the element when selecting None (0) on first dropdown of first column of 3 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 5: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown valid shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), 0 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); // Case 6: Validate the element when selecting None (0) on first dropdown of second column of 3 dropdown valid hybrid shortcut to shortcut row testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), 0 }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_MENU, 0x42 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid and no action is required Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutOneActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); }); } // Test if the ValidateShortcutBufferElement method returns WinL error on setting a drop down to Win or L on a column resulting in Win+L TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnWinLError_OnSettingDropDownToWinOrLOnColumnResultingInWinL) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting L (0x4C) on second dropdown of first column of LWin+Empty shortcut testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LWIN }, Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting L (0x4C) on second dropdown of second column of LWin+Empty shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_LWIN } }, std::wstring()) }); // Case 3: Validate the element when selecting L (0x4C) on second dropdown of second column of hybrid LWin+Empty shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_LWIN } }, std::wstring()) }); // Case 4: Validate the element when selecting L (0x4C) on second dropdown of first column of Win+Empty shortcut testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(CommonSharedConstants::VK_WIN_BOTH, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ CommonSharedConstants::VK_WIN_BOTH }, Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting L (0x4C) on second dropdown of second column of Win+Empty shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(CommonSharedConstants::VK_WIN_BOTH, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ CommonSharedConstants::VK_WIN_BOTH } }, std::wstring()) }); // Case 6: Validate the element when selecting L (0x4C) on second dropdown of second column of hybrid Win+Empty shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(CommonSharedConstants::VK_WIN_BOTH, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ CommonSharedConstants::VK_WIN_BOTH } }, std::wstring()) }); // Case 7: Validate the element when selecting LWin (VK_LWIN) on first dropdown of first column of Empty+L shortcut testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x4C }, Shortcut() }, std::wstring()) }); // Case 8: Validate the element when selecting LWin (VK_LWIN) on first dropdown of second column of Empty+L shortcut testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ 0x4C } }, std::wstring()) }); // Case 9: Validate the element when selecting LWin (VK_LWIN) on first dropdown of second column of hybrid Empty+L shortcut testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ 0x4C } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::WinL); }); } // Test if the ValidateShortcutBufferElement method returns WinL error on setting a drop down to null or none on a column resulting in Win+L TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnWinLError_OnSettingDropDownToNullOrNoneOnColumnResultingInWinL) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Null (-1) on second dropdown of first column of LWin + Ctrl + L shortcut testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), -1, GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LWIN, VK_CONTROL, 0x4C }, Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting Null (-1) on second dropdown of second column of LWin + Ctrl + L shortcut testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), -1, GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_LWIN, VK_CONTROL, 0x4C } }, std::wstring()) }); // Case 3: Validate the element when selecting Null (-1) on second dropdown of second column of hybrid LWin + Ctrl + L shortcut testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), -1, GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_LWIN, VK_CONTROL, 0x4C } }, std::wstring()) }); // Case 4: Validate the element when selecting None (0) on second dropdown of first column of LWin + Ctrl + L shortcut testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), 0, GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LWIN, VK_CONTROL, 0x4C }, Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting None (0) on second dropdown of second column of LWin + Ctrl + L shortcut testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), 0, GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_LWIN, VK_CONTROL, 0x4C } }, std::wstring()) }); // Case 6: Validate the element when selecting None (0) on second dropdown of second column of hybrid LWin + Ctrl + L shortcut testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LWIN, keyList), 0, GetDropDownIndexFromDropDownList(0x4C, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_LWIN, VK_CONTROL, 0x4C } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::WinL); }); } // Test if the ValidateShortcutBufferElement method returns CtrlAltDel error on setting a drop down to Ctrl, Alt or Del on a column resulting in Ctrl+Alt+Del TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnCtrlAltDelError_OnSettingDropDownToCtrlAltOrDelOnColumnResultingInCtrlAltDel) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting Del (VK_DELETE) on third dropdown of first column of Ctrl+Alt+Empty shortcut testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_DELETE, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_MENU }, Shortcut() }, std::wstring()) }); // Case 2: Validate the element when selecting Del (VK_DELETE) on third dropdown of second column of Ctrl+Alt+Empty shortcut testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_DELETE, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_CONTROL, VK_MENU } }, std::wstring()) }); // Case 3: Validate the element when selecting Del (VK_DELETE) on third dropdown of second column of hybrid Ctrl+Alt+Empty shortcut testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_DELETE, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_CONTROL, VK_MENU } }, std::wstring()) }); // Case 4: Validate the element when selecting Alt (VK_MENU) on second dropdown of first column of Ctrl+Empty+Del shortcut testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_DELETE, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_DELETE }, Shortcut() }, std::wstring()) }); // Case 5: Validate the element when selecting Alt (VK_MENU) on second dropdown of second column of Ctrl+Empty+Del shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_DELETE, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_CONTROL, VK_DELETE } }, std::wstring()) }); // Case 6: Validate the element when selecting Alt (VK_MENU) on second dropdown of second column of hybrid Ctrl+Empty+Del shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_MENU, keyList), GetDropDownIndexFromDropDownList(VK_DELETE, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ Shortcut(), std::vector<DWORD>{ VK_CONTROL, VK_DELETE } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::CtrlAltDel); }); } // Test if the ValidateShortcutBufferElement method returns MapToSameKey error on setting hybrid second column to match first column in a remap keys table TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnMapToSameKeyError_OnSettingHybridSecondColumnToFirstColumnInKeyTable) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1: Validate the element when selecting A (0x41) on first dropdown of empty hybrid second column testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList), -1, -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ 0x41, NULL }, std::wstring()) }); // Case 2: Validate the element when selecting A (0x41) on second dropdown of empty hybrid second column testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(0x41, keyList), -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ 0x41, NULL }, std::wstring()) }); // Case 3: Validate the element when selecting A (0x41) on third dropdown of empty hybrid second column testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ -1, -1, GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ 0x41, NULL }, std::wstring()) }); // Case 4: Validate the element when selecting A (0x41) on first dropdown of hybrid second column with key testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ 0x41, 0x43 }, std::wstring()) }); // Case 5: Validate the element when selecting Null (-1) on first dropdown of hybrid second column with shortcut testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ 0x41, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 6: Validate the element when selecting None (0) on first dropdown of hybrid second column with shortcut testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(0x41, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ 0x41, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 7: Validate the element when selecting Null (-1) on second dropdown of hybrid second column with shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ VK_CONTROL, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 8: Validate the element when selecting None (0) on second dropdown of hybrid second column with shortcut testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ VK_CONTROL, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::MapToSameKey); }); } // Test if the ValidateShortcutBufferElement method returns MapToSameShortcut error on setting one column to match the other and both are valid 3 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnMapToSameShortcutError_OnSettingOneColumnToTheOtherAndBothAreValid3KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on third dropdown of first column with Ctrl+Shift+Empty testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 2 : Validate the element when selecting C (0x43) on third dropdown of second column with Ctrl+Shift+Empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT } }, std::wstring()) }); // Case 3 : Validate the element when selecting C (0x43) on third dropdown of second column with hybrid Ctrl+Shift+Empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT } }, std::wstring()) }); // Case 4 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column with Ctrl+Empty+C testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 5 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of second column with Ctrl+Empty+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 6 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of second column with hybrid Ctrl+Empty+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 7 : Validate the element when selecting Shift (VK_SHIFT) on first dropdown of first column with Empty+Ctrl+C testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 8 : Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column with Empty+Ctrl+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 9 : Validate the element when selecting Shift (VK_SHIFT) on first dropdown of second column with hybrid Empty+Ctrl+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::MapToSameShortcut); }); } // Test if the ValidateShortcutBufferElement method returns MapToSameShortcut error on setting one column to match the other and both are valid 2 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnMapToSameShortcutError_OnSettingOneColumnToTheOtherAndBothAreValid2KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on third dropdown of first column with Ctrl+Empty+Empty testCases.push_back({ 0, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 2 : Validate the element when selecting C (0x43) on third dropdown of second column with Ctrl+Empty+Empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL } }, std::wstring()) }); // Case 3 : Validate the element when selecting C (0x43) on third dropdown of second column with hybrid Ctrl+Empty+Empty testCases.push_back({ 0, 1, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL } }, std::wstring()) }); // Case 4 : Validate the element when selecting C (0x43) on second dropdown of first column with Ctrl+Empty+Empty testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 5 : Validate the element when selecting C (0x43) on second dropdown of second column with Ctrl+Empty+Empty testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL } }, std::wstring()) }); // Case 6 : Validate the element when selecting C (0x43) on second dropdown of second column with hybrid Ctrl+Empty+Empty testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL } }, std::wstring()) }); // Case 7 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column with Empty+Empty+C testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 8 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of second column with Empty+Empty+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ 0x43 } }, std::wstring()) }); // Case 9 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of second column with hybrid Empty+Empty+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ 0x43 } }, std::wstring()) }); // Case 10 : Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of first column with Empty+Empty+C testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 11 : Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of second column with Empty+Empty+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ 0x43 } }, std::wstring()) }); // Case 12 : Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of second column with hybrid Empty+Empty+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ 0x43 } }, std::wstring()) }); // Case 13 : Validate the element when selecting C (0x43) on second dropdown of first column with Ctrl+A testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x41 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 14 : Validate the element when selecting C (0x43) on second dropdown of second column with Ctrl+A testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 15 : Validate the element when selecting C (0x43) on second dropdown of second column with hybrid Ctrl+A testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x41 } }, std::wstring()) }); // Case 16 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column with Alt+C testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_MENU, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 17 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of second column with Alt+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_MENU, 0x43 } }, std::wstring()) }); // Case 18 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of second column with hybrid Alt+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_MENU, 0x43 } }, std::wstring()) }); // Case 19 : Validate the element when selecting Null (-1) on second dropdown of first column with Ctrl+Shift+C testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 20 : Validate the element when selecting Null (-1) on second dropdown of second column with Ctrl+Shift+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 21 : Validate the element when selecting Null (-1) on second dropdown of second column with hybrid Ctrl+Shift+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 22 : Validate the element when selecting None (0) on second dropdown of first column with Ctrl+Shift+C testCases.push_back({ 0, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 23 : Validate the element when selecting None (0) on second dropdown of second column with Ctrl+Shift+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 24 : Validate the element when selecting None (0) on second dropdown of second column with hybrid Ctrl+Shift+C testCases.push_back({ 0, 1, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 } }, std::wstring()) }); // Case 25 : Validate the element when selecting Null (-1) on first dropdown of first column with Shift+Ctrl+C testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 26 : Validate the element when selecting Null (-1) on first dropdown of second column with Shift+Ctrl+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 27 : Validate the element when selecting Null (-1) on first dropdown of second column with hybrid Shift+Ctrl+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 28 : Validate the element when selecting None (0) on first dropdown of first column with Shift+Ctrl+C testCases.push_back({ 0, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 29 : Validate the element when selecting None (0) on first dropdown of second column with Shift+Ctrl+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 } }, std::wstring()) }); // Case 30 : Validate the element when selecting None (0) on first dropdown of second column with hybrid Shift+Ctrl+C testCases.push_back({ 0, 1, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), true, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 } }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::MapToSameShortcut); }); } // Test if the ValidateShortcutBufferElement method returns SameShortcutPreviouslyMapped error on setting first column to match first column in another row with same target app and both are valid 3 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnSameShortcutPreviouslyMappedError_OnSettingFirstColumnToFirstColumnInAnotherRowWithSameTargetAppAndBothAreValid3KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on third dropdown of first column with Ctrl+Shift+Empty testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT }, Shortcut() }, std::wstring()) }); // Case 2 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column with Ctrl+Empty+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, std::wstring()) }); // Case 3 : Validate the element when selecting Shift (VK_SHIFT) on first dropdown of first column with Empty+Ctrl+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+Shift+C remapped remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, std::wstring())); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::SameShortcutPreviouslyMapped); }); } // Test if the ValidateShortcutBufferElement method returns no error on setting first column to match first column in another row with different target app and both are valid 3 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoError_OnSettingFirstColumnToFirstColumnInAnotherRowWithDifferentTargetAppAndBothAreValid3KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on third dropdown of first column with Ctrl+Shift+Empty for testApp2 testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT }, Shortcut() }, testApp2) }); // Case 2 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column with Ctrl+Empty+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, testApp2) }); // Case 3 : Validate the element when selecting Shift (VK_SHIFT) on first dropdown of first column with Empty+Ctrl+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, testApp2) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+Shift+C remapped for testApp1 remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, testApp1)); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); }); } // Test if the ValidateShortcutBufferElement method returns ConflictingModifierShortcut error on setting first column to conflict with first column in another row with same target app and both are valid 3 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnConflictingModifierShortcutError_OnSettingFirstColumnToConflictWithFirstColumnInAnotherRowWithSameTargetAppAndBothAreValid3KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on third dropdown of first column with LCtrl+Shift+Empty testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, VK_SHIFT }, Shortcut() }, std::wstring()) }); // Case 2 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column with LCtrl+Empty+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, 0x43 }, Shortcut() }, std::wstring()) }); // Case 3 : Validate the element when selecting LShift (VK_LSHIFT) on first dropdown of first column with Empty+Ctrl+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LSHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+Shift+C remapped remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, std::wstring())); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ConflictingModifierShortcut); }); } // Test if the ValidateShortcutBufferElement method returns no error on setting first column to conflict with first column in another row with different target app and both are valid 3 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoError_OnSettingFirstColumnToConflictWithFirstColumnInAnotherRowWithDifferentTargetAppAndBothAreValid3KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on third dropdown of first column with LCtrl+Shift+Empty for testApp2 testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, VK_SHIFT }, Shortcut() }, testApp2) }); // Case 2 : Validate the element when selecting Shift (VK_SHIFT) on second dropdown of first column with LCtrl+Empty+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, 0x43 }, Shortcut() }, testApp2) }); // Case 3 : Validate the element when selecting LShift (VK_LSHIFT) on first dropdown of first column with Empty+Ctrl+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LSHIFT, keyList), GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, testApp2) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+Shift+C remapped for testApp1 remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, testApp1)); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); }); } // Test if the ValidateShortcutBufferElement method returns SameShortcutPreviouslyMapped error on setting first column to match first column in another row with same target app and both are valid 2 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnSameShortcutPreviouslyMappedError_OnSettingFirstColumnToFirstColumnInAnotherRowWithSameTargetAppAndBothAreValid2KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on second dropdown of first column with Ctrl+Empty testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, Shortcut() }, std::wstring()) }); // Case 2 : Validate the element when selecting C (0x43) on third dropdown of first column with Ctrl+Empty+Empty testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, Shortcut() }, std::wstring()) }); // Case 3 : Validate the element when selecting C (0x43) on second dropdown of first column with Ctrl+Empty+Empty testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, Shortcut() }, std::wstring()) }); // Case 4 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column with Empty+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, std::wstring()) }); // Case 5 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column with Empty+Empty+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, std::wstring()) }); // Case 6 : Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of first column with Empty+Empty+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, std::wstring()) }); // Case 7 : Validate the element when selecting Null (-1) on second dropdown of first column with Ctrl+Shift+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, std::wstring()) }); // Case 8 : Validate the element when selecting Null (-1) on first dropdown of first column with Shift+Ctrl+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 }, Shortcut() }, std::wstring()) }); // Case 9 : Validate the element when selecting None (0) on second dropdown of first column with Ctrl+Shift+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, std::wstring()) }); // Case 10 : Validate the element when selecting None (0) on first dropdown of first column with Shift+Ctrl+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 }, Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+C remapped remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, std::wstring())); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::SameShortcutPreviouslyMapped); }); } // Test if the ValidateShortcutBufferElement method returns no error on setting first column to match first column in another row with different target app and both are valid 2 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoError_OnSettingFirstColumnToFirstColumnInAnotherRowWithDifferentTargetAppAndBothAreValid2KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on second dropdown of first column with Ctrl+Empty for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, Shortcut() }, testApp2) }); // Case 2 : Validate the element when selecting C (0x43) on third dropdown of first column with Ctrl+Empty+Empty for testApp2 testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, Shortcut() }, testApp2) }); // Case 3 : Validate the element when selecting C (0x43) on second dropdown of first column with Ctrl+Empty+Empty for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL }, Shortcut() }, testApp2) }); // Case 4 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column with Empty+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, testApp2) }); // Case 5 : Validate the element when selecting Ctrl (VK_CONTROL) on first dropdown of first column with Empty+Empty+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, testApp2) }); // Case 6 : Validate the element when selecting Ctrl (VK_CONTROL) on second dropdown of first column with Empty+Empty+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, testApp2) }); // Case 7 : Validate the element when selecting Null (-1) on second dropdown of first column with Ctrl+Shift+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, testApp2) }); // Case 8 : Validate the element when selecting Null (-1) on first dropdown of first column with Shift+Ctrl+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 }, Shortcut() }, testApp2) }); // Case 9 : Validate the element when selecting None (0) on second dropdown of first column with Ctrl+Shift+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, VK_SHIFT, 0x43 }, Shortcut() }, testApp2) }); // Case 10 : Validate the element when selecting None (0) on first dropdown of first column with Shift+Ctrl+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_CONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_CONTROL, 0x43 }, Shortcut() }, testApp2) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+C remapped for testApp1 remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, testApp1)); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); }); } // Test if the ValidateShortcutBufferElement method returns ConflictingModifierShortcut error on setting first column to conflict with first column in another row with same target app and both are valid 2 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnConflictingModifierShortcutError_OnSettingFirstColumnToConflictWithFirstColumnInAnotherRowWithSameTargetAppAndBothAreValid2KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on second dropdown of first column with LCtrl+Empty testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL }, Shortcut() }, std::wstring()) }); // Case 2 : Validate the element when selecting C (0x43) on third dropdown of first column with LCtrl+Empty+Empty testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL }, Shortcut() }, std::wstring()) }); // Case 3 : Validate the element when selecting C (0x43) on second dropdown of first column with LCtrl+Empty+Empty testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL }, Shortcut() }, std::wstring()) }); // Case 4 : Validate the element when selecting LCtrl (VK_LCONTROL) on first dropdown of first column with Empty+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, std::wstring()) }); // Case 5 : Validate the element when selecting LCtrl (VK_LCONTROL) on first dropdown of first column with Empty+Empty+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, std::wstring()) }); // Case 6 : Validate the element when selecting LCtrl (VK_LCONTROL) on second dropdown of first column with Empty+Empty+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, std::wstring()) }); // Case 7 : Validate the element when selecting Null (-1) on second dropdown of first column with LCtrl+Shift+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, VK_SHIFT, 0x43 }, Shortcut() }, std::wstring()) }); // Case 8 : Validate the element when selecting Null (-1) on first dropdown of first column with Shift+LCtrl+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_LCONTROL, 0x43 }, Shortcut() }, std::wstring()) }); // Case 9 : Validate the element when selecting None (0) on second dropdown of first column with LCtrl+Shift+C testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, VK_SHIFT, 0x43 }, Shortcut() }, std::wstring()) }); // Case 10 : Validate the element when selecting None (0) on first dropdown of first column with Shift+LCtrl+C testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, std::wstring(), false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_LCONTROL, 0x43 }, Shortcut() }, std::wstring()) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+C remapped remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, std::wstring())); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is invalid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ConflictingModifierShortcut); }); } // Test if the ValidateShortcutBufferElement method returns no error on setting first column to conflict with first column in another row with different target app and both are valid 2 key shortcuts TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnNoError_OnSettingFirstColumnToConflictWithFirstColumnInAnotherRowWithDifferentTargetAppAndBothAreValid2KeyShortcuts) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); std::vector<ValidateShortcutBufferElementArgs> testCases; // Case 1 : Validate the element when selecting C (0x43) on second dropdown of first column with LCtrl+Empty for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL }, Shortcut() }, testApp2) }); // Case 2 : Validate the element when selecting C (0x43) on third dropdown of first column with LCtrl+Empty+Empty for testApp2 testCases.push_back({ 1, 0, 2, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL }, Shortcut() }, testApp2) }); // Case 3 : Validate the element when selecting C (0x43) on second dropdown of first column with LCtrl+Empty+Empty for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList), -1 }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL }, Shortcut() }, testApp2) }); // Case 4 : Validate the element when selecting LCtrl (VK_LCONTROL) on first dropdown of first column with Empty+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, testApp2) }); // Case 5 : Validate the element when selecting LCtrl (VK_LCONTROL) on first dropdown of first column with Empty+Empty+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, testApp2) }); // Case 6 : Validate the element when selecting LCtrl (VK_LCONTROL) on second dropdown of first column with Empty+Empty+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ 0x43 }, Shortcut() }, testApp2) }); // Case 7 : Validate the element when selecting Null (-1) on second dropdown of first column with LCtrl+Shift+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), -1, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, VK_SHIFT, 0x43 }, Shortcut() }, testApp2) }); // Case 8 : Validate the element when selecting Null (-1) on first dropdown of first column with Shift+LCtrl+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ -1, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_LCONTROL, 0x43 }, Shortcut() }, testApp2) }); // Case 9 : Validate the element when selecting None (0) on second dropdown of first column with LCtrl+Shift+C for testApp2 testCases.push_back({ 1, 0, 1, std::vector<int32_t>{ GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), 0, GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_LCONTROL, VK_SHIFT, 0x43 }, Shortcut() }, testApp2) }); // Case 10 : Validate the element when selecting None (0) on first dropdown of first column with Shift+LCtrl+C for testApp2 testCases.push_back({ 1, 0, 0, std::vector<int32_t>{ 0, GetDropDownIndexFromDropDownList(VK_LCONTROL, keyList), GetDropDownIndexFromDropDownList(0x43, keyList) }, testApp2, false, std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, VK_LCONTROL, 0x43 }, Shortcut() }, testApp2) }); RunTestCases(testCases, [this, &keyList](const ValidateShortcutBufferElementArgs& testCase) { // Arrange RemapBuffer remapBuffer; // Ctrl+C remapped for testApp1 remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_CONTROL, 0x43 }, Shortcut() }, testApp1)); remapBuffer.push_back(testCase.bufferRow); // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(testCase.elementRowIndex, testCase.elementColIndex, testCase.indexOfDropDownLastModified, testCase.selectedIndicesOnDropDowns, testCase.targetAppNameInTextBox, testCase.isHybridColumn, keyList, remapBuffer, true); // Assert that the element is valid Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::NoError); }); } // Return error on Disable as second modifier key or action key TEST_METHOD (ValidateShortcutBufferElement_ShouldReturnDisableAsActionKeyError_OnSettingSecondDropdownAsDisable) { std::vector<DWORD> keyList = keyboardLayout.GetKeyCodeList(true); keyList.insert(keyList.begin(), CommonSharedConstants::VK_DISABLED); // Arrange RemapBuffer remapBuffer; remapBuffer.push_back(std::make_pair(RemapBufferItem{ std::vector<DWORD>{ VK_SHIFT, CommonSharedConstants::VK_DISABLED }, Shortcut() }, testApp1)); std::vector<int32_t> selectedIndices = { GetDropDownIndexFromDropDownList(VK_SHIFT, keyList), GetDropDownIndexFromDropDownList(CommonSharedConstants::VK_DISABLED, keyList) }; // Act std::pair<KeyboardManagerHelper::ErrorType, BufferValidationHelpers::DropDownAction> result = BufferValidationHelpers::ValidateShortcutBufferElement(0, 1, 1, selectedIndices, testApp1, true, keyList, remapBuffer, true); // Assert Assert::AreEqual(true, result.first == KeyboardManagerHelper::ErrorType::ShortcutDisableAsActionKey); Assert::AreEqual(true, result.second == BufferValidationHelpers::DropDownAction::NoAction); } }; }
119.320355
403
0.720199
[ "vector" ]
161ea26063b136509713f003e19a67eb0662e507
13,582
cpp
C++
xercesc/xerces-c1_7_0-win32/samples/PParse/PParse.cpp
anjingbin/starccm
70db48004aa20bbb82cc24de80802b40c7024eff
[ "BSD-3-Clause" ]
2
2020-01-06T07:43:30.000Z
2020-07-11T20:53:53.000Z
xercesc/xerces-c1_7_0-win32/samples/PParse/PParse.cpp
anjingbin/starccm
70db48004aa20bbb82cc24de80802b40c7024eff
[ "BSD-3-Clause" ]
null
null
null
xercesc/xerces-c1_7_0-win32/samples/PParse/PParse.cpp
anjingbin/starccm
70db48004aa20bbb82cc24de80802b40c7024eff
[ "BSD-3-Clause" ]
null
null
null
/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log: PParse.cpp,v $ * Revision 1.1 2003/11/12 01:58:43 AnJingBin * *** empty log message *** * * Revision 1.1 2003/10/23 20:58:29 AnJingBin * *** empty log message *** * * Revision 1.13 2002/02/01 22:37:38 peiyongz * sane_include * * Revision 1.12 2001/10/25 15:18:33 tng * delete the parser before XMLPlatformUtils::Terminate. * * Revision 1.11 2001/10/19 18:52:04 tng * Since PParse can take any XML file as input file, it shouldn't hardcode to expect 16 elements. * Change it to work similar to SAXCount which just prints the number of elements, characters, attributes ... etc. * And other modification for consistent help display and return code across samples. * * Revision 1.10 2001/08/01 19:11:01 tng * Add full schema constraint checking flag to the samples and the parser. * * Revision 1.9 2001/05/11 13:24:55 tng * Copyright update. * * Revision 1.8 2001/05/03 15:59:48 tng * Schema: samples update with schema * * Revision 1.7 2000/06/20 02:23:08 rahulj * Help message added by Joe Polastre. * * Revision 1.6 2000/03/03 01:29:31 roddey * Added a scanReset()/parseReset() method to the scanner and * parsers, to allow for reset after early exit from a progressive parse. * Added calls to new Terminate() call to all of the samples. Improved * documentation in SAX and DOM parsers. * * Revision 1.5 2000/03/02 19:53:44 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.4 2000/02/11 02:37:48 abagchi * Removed StrX::transcode * * Revision 1.3 2000/02/06 07:47:20 rahulj * Year 2K copyright swat. * * Revision 1.2 2000/01/12 00:27:00 roddey * Updates to work with the new URL and input source scheme. * * Revision 1.1.1.1 1999/11/09 01:09:45 twl * Initial checkin * * Revision 1.5 1999/11/08 20:43:38 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // This sample program demonstrates the progressive parse capabilities of // the parser system. It allows you to do a scanFirst() call followed by // a loop which calls scanNext(). You can drop out when you've found what // ever it is you want. In our little test, our event handler looks for // 16 new elements then sets a flag to indicate its found what it wants. // At that point, our progressive parse loop below exits. // // The parameters are: // // [-?] - Show usage and exit // [-v=xxx] - Validation scheme [always | never | auto*] // [-n] - Enable namespace processing // [-s] - Enable schema processing // [-f] - Enable full schema constraint checking // filename - The path to the XML file to parse // // * = Default if not provided explicitly // These are non-case sensitive // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/framework/XMLPScanToken.hpp> #include <xercesc/parsers/SAXParser.hpp> #include "PParse.hpp" // --------------------------------------------------------------------------- // Local data // // xmlFile // The path to the file to parser. Set via command line. // // doNamespaces // Indicates whether namespace processing should be done. // // doSchema // Indicates whether schema processing should be done. // // schemaFullChecking // Indicates whether full schema constraint checking should be done. // // valScheme // Indicates what validation scheme to use. It defaults to 'auto', but // can be set via the -v= command. // --------------------------------------------------------------------------- static char* xmlFile = 0; static bool doNamespaces = false; static bool doSchema = false; static bool schemaFullChecking = false; static SAXParser::ValSchemes valScheme = SAXParser::Val_Auto; // --------------------------------------------------------------------------- // Local helper methods // --------------------------------------------------------------------------- static void usage() { cout << "\nUsage:\n" " PParse [options] <XML file>\n\n" "This program demonstrates the progressive parse capabilities of\n" "the parser system. It allows you to do a scanFirst() call followed by\n" "a loop which calls scanNext(). You can drop out when you've found what\n" "ever it is you want. In our little test, our event handler looks for\n" "16 new elements then sets a flag to indicate its found what it wants.\n" "At that point, our progressive parse loop exits.\n\n" "Options:\n" " -v=xxx - Validation scheme [always | never | auto*].\n" " -n - Enable namespace processing [default is off].\n" " -s - Enable schema processing [default is off].\n" " -f - Enable full schema constraint checking [default is off].\n" " -? - Show this help.\n\n" " * = Default if not provided explicitly.\n" << endl; } // --------------------------------------------------------------------------- // Program entry point // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { // Initialize the XML4C system try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { cerr << "Error during initialization! :\n" << StrX(toCatch.getMessage()) << endl; return 1; } // Check command line and extract arguments. if (argC < 2) { usage(); XMLPlatformUtils::Terminate(); return 1; } // See if non validating dom parser configuration is requested. int parmInd; for (parmInd = 1; parmInd < argC; parmInd++) { // Break out on first parm not starting with a dash if (argV[parmInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[parmInd], "-?")) { usage(); XMLPlatformUtils::Terminate(); return 2; } else if (!strncmp(argV[parmInd], "-v=", 3) || !strncmp(argV[parmInd], "-V=", 3)) { const char* const parm = &argV[parmInd][3]; if (!strcmp(parm, "never")) valScheme = SAXParser::Val_Never; else if (!strcmp(parm, "auto")) valScheme = SAXParser::Val_Auto; else if (!strcmp(parm, "always")) valScheme = SAXParser::Val_Always; else { cerr << "Unknown -v= value: " << parm << endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strcmp(argV[parmInd], "-n") || !strcmp(argV[parmInd], "-N")) { doNamespaces = true; } else if (!strcmp(argV[parmInd], "-s") || !strcmp(argV[parmInd], "-S")) { doSchema = true; } else if (!strcmp(argV[parmInd], "-f") || !strcmp(argV[parmInd], "-F")) { schemaFullChecking = true; } else { cerr << "Unknown option '" << argV[parmInd] << "', ignoring it\n" << endl; } } // // And now we have to have only one parameter left and it must be // the file name. // if (parmInd + 1 != argC) { usage(); XMLPlatformUtils::Terminate(); return 1; } xmlFile = argV[parmInd]; int errorCount = 0; // // Create a SAX parser object to use and create our SAX event handlers // and plug them in. // SAXParser* parser = new SAXParser; PParseHandlers handler; parser->setDocumentHandler(&handler); parser->setErrorHandler(&handler); parser->setValidationScheme(valScheme); parser->setDoNamespaces(doNamespaces); parser->setDoSchema(doSchema); parser->setValidationSchemaFullChecking(schemaFullChecking); // // Ok, lets do the progressive parse loop. On each time around the // loop, we look and see if the handler has found what its looking // for. When it does, we fall out then. // unsigned long duration; try { // Create a progressive scan token XMLPScanToken token; const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis(); if (!parser->parseFirst(xmlFile, token)) { cerr << "scanFirst() failed\n" << endl; XMLPlatformUtils::Terminate(); return 1; } // // We started ok, so lets call scanNext() until we find what we want // or hit the end. // bool gotMore = true; while (gotMore && !parser->getErrorCount()) gotMore = parser->parseNext(token); const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis(); duration = endMillis - startMillis; errorCount = parser->getErrorCount(); // // Reset the parser-> In this simple progrma, since we just exit // now, its not technically required. But, in programs which // would remain open, you should reset after a progressive parse // in case you broke out before the end of the file. This insures // that all opened files, sockets, etc... are closed. // parser->parseReset(token); } catch (const XMLException& toCatch) { cerr << "\nAn error occured: '" << xmlFile << "'\n" << "Exception message is: \n" << StrX(toCatch.getMessage()) << "\n" << endl; XMLPlatformUtils::Terminate(); return 4; } if (!errorCount) { cout << xmlFile << ": " << duration << " ms (" << handler.getElementCount() << " elems, " << handler.getAttrCount() << " attrs, " << handler.getSpaceCount() << " spaces, " << handler.getCharacterCount() << " chars)" << endl; } // // Delete the parser itself. Must be done prior to calling Terminate, below. // delete parser; // And call the termination method XMLPlatformUtils::Terminate(); if (errorCount > 0) return 4; else return 0; }
35.648294
114
0.578413
[ "object" ]
162035bd2a466902af54e918b8a82e07d70f06ff
2,962
cpp
C++
examples/input_output/systemSpeakExample/src/ofApp.cpp
murven/openFrameworks
f9cb24b3f58d7f8b6aca54dcf4ec57e672202a0d
[ "MIT" ]
6,436
2015-01-01T19:51:56.000Z
2022-03-31T05:45:34.000Z
examples/input_output/systemSpeakExample/src/ofApp.cpp
Pandinosaurus/openFrameworks
38c8715c022c6b34c9ce9c379aeb55315aa0f2a0
[ "MIT" ]
3,195
2015-01-01T00:18:46.000Z
2022-03-31T04:41:47.000Z
examples/input_output/systemSpeakExample/src/ofApp.cpp
Pandinosaurus/openFrameworks
38c8715c022c6b34c9ce9c379aeb55315aa0f2a0
[ "MIT" ]
2,180
2015-01-01T02:42:29.000Z
2022-03-30T06:36:48.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { font.load("verdana.ttf", 34); // load the lyrics from a text file and split them // up in to a vector of strings string lyrics = ofBufferFromFile("lyrics.txt").getText(); step = 0; words = ofSplitString(lyrics, " "); // we are running the systems commands // in a sperate thread so that it does // not block the drawing startThread(); } //-------------------------------------------------------------- void ofApp::threadedFunction() { while (isThreadRunning()) { // call the system command say #ifdef TARGET_OSX string cmd = "say " + words[step] + " "; // create the command #endif #ifdef TARGET_WIN32 string cmd = "data\\SayStatic.exe " + words[step]; // create the command #endif #ifdef TARGET_LINUX string cmd = "echo " + words[step] + "|espeak"; // create the command #endif // print command and execute it cout << cmd << endl; ofSystem(cmd.c_str()); // step to the next word step ++; step %= words.size(); // slowdown boy ofSleepMillis(10); } } //-------------------------------------------------------------- void ofApp::update() { // get a random voice } //-------------------------------------------------------------- void ofApp::draw() { // center the word on the screen float x = (ofGetWidth() - font.stringWidth(words[step])) / 2; float y = ofGetHeight() / 2; // draw the word ofSetColor(0); font.drawString(words[step], x, y); } //-------------------------------------------------------------- void ofApp::exit() { // stop the thread on exit waitForThread(true); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
23.322835
82
0.408508
[ "vector" ]
1620603c57c2f86c5d4a721b429926d07d79c3aa
39,362
cpp
C++
src/validate/block_storage.cpp
eveybcd/BitcoinDiamond
ad08a18a13fb29cbf6d7b5a17c1632c5528a5f58
[ "MIT" ]
126
2017-12-21T07:17:47.000Z
2021-06-05T03:46:52.000Z
src/validate/block_storage.cpp
Matthelonianxl/BitcoinDiamond
ad08a18a13fb29cbf6d7b5a17c1632c5528a5f58
[ "MIT" ]
63
2017-12-21T14:43:04.000Z
2021-11-18T03:43:35.000Z
src/validate/block_storage.cpp
Matthelonianxl/BitcoinDiamond
ad08a18a13fb29cbf6d7b5a17c1632c5528a5f58
[ "MIT" ]
87
2017-12-21T07:17:50.000Z
2021-06-18T23:39:16.000Z
// Copyright (c) 2019 The BCD Core developers #include <validate/block_storage.h> #include <validate/cchain_state.h> #include <validate/chain_cache.h> std::atomic_bool fReindex(false); std::unique_ptr<CBlockTreeDB> pblocktree; size_t nCoinCacheUsage = 5000 * 300; uint64_t nPruneTarget = 0; FILE* BlockStorage::OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { if (pos.IsNull()) return nullptr; fs::path path = GetBlockPosFilename(pos, prefix); fs::create_directories(path.parent_path()); FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+"); if (!file && !fReadOnly) file = fsbridge::fopen(path, "wb+"); if (!file) { LogPrintf("Unable to open file %s\n", path.string()); return nullptr; } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string()); fclose(file); return nullptr; } } return file; } /** Open an undo file (rev?????.dat) */ FILE* BlockStorage::OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) { return OpenDiskFile(pos, "rev", fReadOnly); } bool BlockStorage::UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex) { CDiskBlockPos pos = pindex->GetUndoPos(); if (pos.IsNull()) { return error("%s: no undo data available", __func__); } // Open history file to read CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s: OpenUndoFile failed", __func__); // Read block uint256 hashChecksum; CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data try { verifier << pindex->pprev->GetBlockHash(); verifier >> blockundo; filein >> hashChecksum; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } // Verify checksum if (hashChecksum != verifier.GetHash()) return error("%s: Checksum mismatch", __func__); return true; } FILE* BlockStorage::OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) { return OpenDiskFile(pos, "blk", fReadOnly); } bool BlockStorage::WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart) { // Open history file to append CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("WriteBlockToDisk: OpenBlockFile failed"); // Write index header unsigned int nSize = GetSerializeSize(fileout, block); fileout << messageStart << nSize; // Write block long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("WriteBlockToDisk: ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << block; return true; } bool BlockStorage::ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams) { block.SetNull(); bool isBCDBlock = false; CBlockIndex* pindexPrev = nullptr; // Open history file to read CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString()); // Read block try { filein >> block; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } if (!block.hashPrevBlock.IsNull()){ BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi == mapBlockIndex.end()) return error("%s: block %s prev block not found", __func__, pos.ToString()); pindexPrev = (*mi).second; if ((block.nVersion & VERSIONBITS_FORK_BCD) && pindexPrev->nHeight + 1 >= consensusParams.BCDHeight) isBCDBlock = true; } // Check the header if (!CheckProofOfWork(block.GetPoWHash(isBCDBlock), block.nBits, consensusParams)) return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString()); return true; } bool BlockStorage::ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& message_start) { CDiskBlockPos hpos = pos; hpos.nPos -= 8; // Seek back 8 bytes for meta header CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString()); } try { CMessageHeader::MessageStartChars blk_start; unsigned int blk_size; filein >> blk_start >> blk_size; if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) { return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(), HexStr(blk_start, blk_start + CMessageHeader::MESSAGE_START_SIZE), HexStr(message_start, message_start + CMessageHeader::MESSAGE_START_SIZE)); } if (blk_size > MAX_SIZE) { return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(), blk_size, MAX_SIZE); } block.resize(blk_size); // Zeroing of memory is intentional here filein.read((char*)block.data(), blk_size); } catch(const std::exception& e) { return error("%s: Read from block file failed: %s for %s", __func__, e.what(), pos.ToString()); } return true; } bool BlockStorage::UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart) { // Open history file to append CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: OpenUndoFile failed", __func__); // Write index header unsigned int nSize = GetSerializeSize(fileout, blockundo); fileout << messageStart << nSize; // Write undo data long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("%s: ftell failed", __func__); pos.nPos = (unsigned int)fileOutPos; fileout << blockundo; // calculate & write checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << blockundo; fileout << hasher.GetHash(); return true; } void BlockStorage::UnlinkPrunedFiles(const std::set<int>& setFilesToPrune) { for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) { CDiskBlockPos pos(*it, 0); fs::remove(GetBlockPosFilename(pos, "blk")); fs::remove(GetBlockPosFilename(pos, "rev")); LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it); } } /* This function is called from the RPC code for pruneblockchain */ void BlockStorage::PruneBlockFilesManual(int nManualPruneHeight) { CValidationState state; const CChainParams& chainparams = Params(); if (!FlushStateToDisk(chainparams, state, FlushStateMode::NONE, nManualPruneHeight)) { LogPrintf("%s: failed to flush state (%s)\n", __func__, FormatStateMessage(state)); } } /** * Update the on-disk chain state. * The caches and indexes are flushed depending on the mode we're called with * if they're too large, if it's been a while since the last write, * or always and in all cases if we're in prune mode and are deleting files. * * If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything * besides checking if we need to prune. */ bool BlockStorage::FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) { int64_t nMempoolUsage = mempool.DynamicMemoryUsage(); LOCK(cs_main); static int64_t nLastWrite = 0; static int64_t nLastFlush = 0; std::set<int> setFilesToPrune; bool full_flush_completed = false; try { { bool fFlushForPrune = false; bool fDoFullFlush = false; LOCK(cs_LastBlockFile); if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) { if (nManualPruneHeight > 0) { FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight); } else { FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight()); fCheckForPruning = false; } if (!setFilesToPrune.empty()) { fFlushForPrune = true; if (!fHavePruned) { pblocktree->WriteFlag("prunedblockfiles", true); fHavePruned = true; } } } int64_t nNow = GetTimeMicros(); // Avoid writing/flushing immediately after startup. if (nLastWrite == 0) { nLastWrite = nNow; } if (nLastFlush == 0) { nLastFlush = nNow; } int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; int64_t cacheSize = pcoinsTip->DynamicMemoryUsage(); int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0); // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing). bool fCacheLarge = mode == FlushStateMode::PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024); // The cache is over the limit, we have to write now. bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cacheSize > nTotalSpace; // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; // Combine all conditions that result in a full cache flush. fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; // Write blocks and block index to disk. if (fDoFullFlush || fPeriodicWrite) { // Depend on nMinDiskSpace to ensure we can write block index if (!CheckDiskSpace(0, true)) return state.Error("out of disk space"); // First make sure all block and undo data is flushed to disk. FlushBlockFile(); // Then update all block file information (which may refer to block and undo files). { std::vector<std::pair<int, const CBlockFileInfo*> > vFiles; vFiles.reserve(dirtyFileInfo.size()); for (std::set<int>::iterator it = dirtyFileInfo.begin(); it != dirtyFileInfo.end(); ) { vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it])); dirtyFileInfo.erase(it++); } std::vector<const CBlockIndex*> vBlocks; vBlocks.reserve(dirtyBlockIndex.size()); for (std::set<CBlockIndex*>::iterator it = dirtyBlockIndex.begin(); it != dirtyBlockIndex.end(); ) { vBlocks.push_back(*it); dirtyBlockIndex.erase(it++); } if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { return AbortNode(state, "Failed to write to block index database"); } } // Finally remove any pruned files if (fFlushForPrune) UnlinkPrunedFiles(setFilesToPrune); nLastWrite = nNow; } // Flush best chain related state. This can only be done if the blocks / block index write was also done. if (fDoFullFlush && !pcoinsTip->GetBestBlock().IsNull()) { // Typical Coin structures on disk are around 48 bytes in size. // Pushing a new one to the database can cause it to be written // twice (once in the log, and once in the tables). This is already // an overestimation, as most will delete an existing entry or // overwrite one. Still, use a conservative safety factor of 2. if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize())) return state.Error("out of disk space"); // Flush the chainstate (which may refer to block index entries). if (!pcoinsTip->Flush()) return AbortNode(state, "Failed to write to coin database"); nLastFlush = nNow; full_flush_completed = true; } } if (full_flush_completed) { // Update best block in wallet (so we can detect restored wallets). GetMainSignals().ChainStateFlushed(chainActive.GetLocator()); } } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error while flushing: ") + e.what()); } return true; } void BlockStorage::FlushBlockFile(bool fFinalize) { LOCK(cs_LastBlockFile); CDiskBlockPos posOld(nLastBlockFile, 0); bool status = true; FILE *fileOld = OpenBlockFile(posOld); if (fileOld) { if (fFinalize) status &= TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize); status &= FileCommit(fileOld); fclose(fileOld); } fileOld = OpenUndoFile(posOld); if (fileOld) { if (fFinalize) status &= TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize); status &= FileCommit(fileOld); fclose(fileOld); } if (!status) { AbortNode("Flushing block file to disk failed. This is likely the result of an I/O error."); } } // // CBlock and CBlockIndex // bool BlockStorage::ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams) { CDiskBlockPos blockPos; { LOCK(cs_main); blockPos = pindex->GetBlockPos(); } if (!ReadBlockFromDisk(block, blockPos, consensusParams)) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", pindex->ToString(), pindex->GetBlockPos().ToString()); return true; } bool BlockStorage::ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start) { CDiskBlockPos block_pos; { LOCK(cs_main); block_pos = pindex->GetBlockPos(); } return ReadRawBlockFromDisk(block, block_pos, message_start); } void BlockStorage::FlushStateToDisk() { CValidationState state; const CChainParams& chainparams = Params(); if (!FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS)) { LogPrintf("%s: failed to flush state (%s)\n", __func__, FormatStateMessage(state)); } } /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */ void BlockStorage::FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight) { assert(fPruneMode && nManualPruneHeight > 0); LOCK2(cs_main, cs_LastBlockFile); if (chainActive.Tip() == nullptr) return; // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip) unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP); int count=0; for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) continue; PruneOneBlockFile(fileNumber); setFilesToPrune.insert(fileNumber); count++; } LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count); } /** * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target. * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex * (which in this case means the blockchain must be re-downloaded.) * * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set. * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.) * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest). * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip. * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files. * A db flag records the fact that at least some block files have been pruned. * * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned */ void BlockStorage::FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight) { LOCK2(cs_main, cs_LastBlockFile); if (chainActive.Tip() == nullptr || nPruneTarget == 0) { return; } if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) { return; } unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files // So we should leave a buffer under our target to account for another allocation // before the next pruning. uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE; uint64_t nBytesToPrune; int count=0; if (nCurrentUsage + nBuffer >= nPruneTarget) { // On a prune event, the chainstate DB is flushed. // To avoid excessive prune events negating the benefit of high dbcache // values, we should not prune too rapidly. // So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon. if (IsInitialBlockDownload()) { // Since this is only relevant during IBD, we use a fixed 10% nBuffer += nPruneTarget / 10; } for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize; if (vinfoBlockFile[fileNumber].nSize == 0) continue; if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target? break; // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) continue; PruneOneBlockFile(fileNumber); // Queue up the files for removal setFilesToPrune.insert(fileNumber); nCurrentUsage -= nBytesToPrune; count++; } } LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n", nPruneTarget/1024/1024, nCurrentUsage/1024/1024, ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024, nLastBlockWeCanPrune, count); } /* Prune a block file (modify associated database entries)*/ void BlockStorage::PruneOneBlockFile(const int fileNumber) { LOCK(cs_LastBlockFile); for (const auto& entry : mapBlockIndex) { CBlockIndex* pindex = entry.second; if (pindex->nFile == fileNumber) { pindex->nStatus &= ~BLOCK_HAVE_DATA; pindex->nStatus &= ~BLOCK_HAVE_UNDO; pindex->nFile = 0; pindex->nDataPos = 0; pindex->nUndoPos = 0; setDirtyBlockIndex(pindex); // Prune from mapBlocksUnlinked -- any block we prune would have // to be downloaded again in order to consider its chain, at which // point it would be considered as a candidate for // mapBlocksUnlinked or setBlockIndexCandidates. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev); while (range.first != range.second) { std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first; range.first++; if (_it->second == pindex) { mapBlocksUnlinked.erase(_it); } } } } vinfoBlockFile[fileNumber].SetNull(); dirtyFileInfo.insert(fileNumber); } void BlockStorage::PruneAndFlush() { CValidationState state; fCheckForPruning = true; const CChainParams& chainparams = Params(); if (!FlushStateToDisk(chainparams, state, FlushStateMode::NONE)) { LogPrintf("%s: failed to flush state (%s)\n", __func__, FormatStateMessage(state)); } } fs::path BlockStorage::GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix) { return GetBlocksDir() / strprintf("%s%05u.dat", prefix, pos.nFile); } bool BlockStorage::LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp) { // Map of disk positions for blocks with unknown parent (only used for reindex) static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent; int64_t nStart = GetTimeMillis(); int nLoaded = 0; try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION); uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); blkdat.SetPos(nRewind); nRewind++; // start one byte further next time, in case of failure blkdat.SetLimit(); // remove former limit unsigned int nSize = 0; try { // locate a header unsigned char buf[CMessageHeader::MESSAGE_START_SIZE]; blkdat.FindByte(chainparams.MessageStart()[0]); nRewind = blkdat.GetPos()+1; blkdat >> buf; if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) continue; // read size blkdat >> nSize; if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE) continue; } catch (const std::exception&) { // no valid block header found; don't complain break; } try { // read block uint64_t nBlockPos = blkdat.GetPos(); if (dbp) dbp->nPos = nBlockPos; blkdat.SetLimit(nBlockPos + nSize); blkdat.SetPos(nBlockPos); std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); CBlock& block = *pblock; blkdat >> block; nRewind = blkdat.GetPos(); uint256 hash = block.GetHash(); { LOCK(cs_main); // detect out of order blocks, and store them for later if (hash != chainparams.GetConsensus().hashGenesisBlock && !LookupBlockIndex(block.hashPrevBlock)) { LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(), block.hashPrevBlock.ToString()); if (dbp) mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); continue; } // process in case the block isn't known yet CBlockIndex* pindex = LookupBlockIndex(hash); if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) { CValidationState state; if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr)) { nLoaded++; } if (state.IsError()) { break; } } else if (hash != chainparams.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) { LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight); } } // Activate the genesis block so normal node progress can continue if (hash == chainparams.GetConsensus().hashGenesisBlock) { CValidationState state; if (!ActivateBestChain(state, chainparams)) { break; } } NotifyHeaderTip(); // Recursively process earlier encountered successors of this block std::deque<uint256> queue; queue.push_back(hash); while (!queue.empty()) { uint256 head = queue.front(); queue.pop_front(); std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head); while (range.first != range.second) { std::multimap<uint256, CDiskBlockPos>::iterator it = range.first; std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>(); if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus())) { LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(), head.ToString()); LOCK(cs_main); CValidationState dummy; if (g_chainstate.AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr)) { nLoaded++; queue.push_back(pblockrecursive->GetHash()); } } range.first++; mapBlocksUnknownParent.erase(it); NotifyHeaderTip(); } } } catch (const std::exception& e) { LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what()); } } } catch (const std::runtime_error& e) { AbortNode(std::string("System error: ") + e.what()); } if (nLoaded > 0) LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart); return nLoaded > 0; } /** * BLOCK PRUNING CODE */ /* Calculate the amount of disk space the block & undo files currently use */ uint64_t BlockStorage::CalculateCurrentUsage() { LOCK(cs_LastBlockFile); uint64_t retval = 0; for (const CBlockFileInfo &file : vinfoBlockFile) { retval += file.nSize + file.nUndoSize; } return retval; } CBlockIndex* BlockStorage::LookupBlockIndex(const uint256& hash) { AssertLockHeld(cs_main); BlockMap::const_iterator it = mapBlockIndex.find(hash); return it == mapBlockIndex.end() ? nullptr : it->second; } bool BlockStorage::FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown) { LOCK(cs_LastBlockFile); unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } if (!fKnown) { while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { nFile++; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } } pos.nFile = nFile; pos.nPos = vinfoBlockFile[nFile].nSize; } if ((int)nFile != nLastBlockFile) { if (!fKnown) { LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString()); } FlushBlockFile(!fKnown); nLastBlockFile = nFile; } vinfoBlockFile[nFile].AddBlock(nHeight, nTime); if (fKnown) vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize); else vinfoBlockFile[nFile].nSize += nAddSize; if (!fKnown) { unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (fPruneMode) fCheckForPruning = true; if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos, true)) { FILE *file = OpenBlockFile(pos); if (file) { LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return error("out of disk space"); } } dirtyFileInfo.insert(nFile); return true; } /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */ CDiskBlockPos BlockStorage::SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const CDiskBlockPos* dbp) { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; if (dbp != nullptr) blockPos = *dbp; if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) { error("%s: FindBlockPos failed", __func__); return CDiskBlockPos(); } if (dbp == nullptr) { if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) { AbortNode("Failed to write block"); return CDiskBlockPos(); } } return blockPos; } unsigned int BlockStorage::GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) { AssertLockHeld(cs_main); unsigned int flags = SCRIPT_VERIFY_NONE; // BIP16 didn't become active until Apr 1 2012 (on mainnet, and // retroactively applied to testnet) // However, only one historical block violated the P2SH rules (on both // mainnet and testnet), so for simplicity, always leave P2SH // on except for the one violating block. if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity() *pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception { flags |= SCRIPT_VERIFY_P2SH; } // Enforce WITNESS rules whenever P2SH is in effect (and the segwit // deployment is defined). if (flags & SCRIPT_VERIFY_P2SH && IsScriptWitnessEnabled(consensusparams)) { flags |= SCRIPT_VERIFY_WITNESS; } // Start enforcing the DERSIG (BIP66) rule if (pindex->nHeight >= consensusparams.BIP66Height) { flags |= SCRIPT_VERIFY_DERSIG; } // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule if (pindex->nHeight >= consensusparams.BIP65Height) { flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; } // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic. if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) { flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY; } if (IsNullDummyEnabled(pindex->pprev, consensusparams)) { flags |= SCRIPT_VERIFY_NULLDUMMY; } return flags; } bool BlockStorage::CheckDiskSpace(uint64_t nAdditionalBytes, bool blocks_dir) { uint64_t nFreeBytesAvailable = fs::space(blocks_dir ? GetBlocksDir() : GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) return AbortNode("Disk space is low!", _("Error: Disk space is low!")); return true; } bool BlockStorage::IsNullDummyEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params) { LOCK(cs_main); return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == ThresholdState::ACTIVE); } // 0.13.0 was shipped with a segwit deployment defined for testnet, but not for // mainnet. We no longer need to support disabling the segwit deployment // except for testing purposes, due to limitations of the functional test // environment. See test/functional/p2p-segwit.py. bool BlockStorage::IsScriptWitnessEnabled(const Consensus::Params& params) { return params.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0; } bool BlockStorage::LoadBlockIndexDB(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { if (!g_chainstate.LoadBlockIndex(chainparams.GetConsensus(), *pblocktree)) return false; // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile); for (int nFile = 0; nFile <= nLastBlockFile; nFile++) { pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]); } LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString()); for (int nFile = nLastBlockFile + 1; true; nFile++) { CBlockFileInfo info; if (pblocktree->ReadBlockFileInfo(nFile, info)) { vinfoBlockFile.push_back(info); } else { break; } } // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); std::set<int> setBlkDataFiles; for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } } for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { CDiskBlockPos pos(*it, 0); if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) { return false; } } // Check whether we have ever pruned block & undo files pblocktree->ReadFlag("prunedblockfiles", fHavePruned); if (fHavePruned) LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n"); // Check whether we need to continue reindexing bool fReindexing = false; pblocktree->ReadReindexing(fReindexing); if(fReindexing) fReindex = true; return true; } bool BlockStorage::FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { pos.nFile = nFile; LOCK(gBlockStorage.cs_LastBlockFile); unsigned int nNewSize; pos.nPos = gBlockStorage.vinfoBlockFile[nFile].nUndoSize; nNewSize = gBlockStorage.vinfoBlockFile[nFile].nUndoSize += nAddSize; gBlockStorage.setDirtyFileInfo(nFile); unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (fPruneMode) gBlockStorage.setFCheckForPruning(true); if (gBlockStorage.CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos, true)) { FILE *file = gBlockStorage.OpenUndoFile(pos); if (file) { LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error("out of disk space"); } return true; } bool BlockStorage::WriteUndoDataForBlock(const CBlockUndo& blockundo, CValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams) { // Write undo information to disk if (pindex->GetUndoPos().IsNull()) { CDiskBlockPos _pos; if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40)) return error("ConnectBlock(): FindUndoPos failed"); if (!gBlockStorage.UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart())) return AbortNode(state, "Failed to write undo data"); // update nUndoPos in block index pindex->nUndoPos = _pos.nPos; pindex->nStatus |= BLOCK_HAVE_UNDO; gBlockStorage.setDirtyBlockIndex(pindex); } return true; } int32_t BlockStorage::ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) { LOCK(cs_main); int32_t nVersion = VERSIONBITS_TOP_BITS; if (pindexPrev && pindexPrev->nHeight + 1 >= params.BCDHeight) nVersion |= VERSIONBITS_FORK_BCD; for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) { ThresholdState state = VersionBitsState(pindexPrev, params, static_cast<Consensus::DeploymentPos>(i), versionbitscache); if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) { nVersion |= VersionBitsMask(params, static_cast<Consensus::DeploymentPos>(i)); } } return nVersion; }
41.608879
181
0.627636
[ "vector" ]
16278851a266e8f19db9ac13e21e09b04eecb7b8
10,865
cpp
C++
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/popup_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2020-10-04T18:50:01.000Z
2020-10-04T18:50:01.000Z
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/popup_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
null
null
null
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/popup_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2018-09-18T08:03:33.000Z
2018-09-18T08:03:33.000Z
#include "horus.h" #include "types.h" #include "ui_theme.h" #include "ui_font.h" #include "util.h" #include "ui_context.h" #include <limits.h> namespace hui { //TODO: place into public settings static f32 movePopupMaxDistanceTrigger = 5; void beginPopup( f32 width, PopupFlags flags, const Point& position, WidgetElementId widgetElementId) { auto& popup = ctx->popupStack[ctx->popupIndex]; popup.flags = flags; if (ctx->popupUseGlobalScale) width *= ctx->globalScale; //ctx->popupUseGlobalScale = true; if (!has(flags, PopupFlags::SameLayer)) incrementLayerIndex(); if (has(flags, PopupFlags::TopMost)) { popup.oldZOrder = ctx->renderer->getZOrder(); ctx->renderer->setZOrder(INT_MAX - 1); } ctx->popupIndex++; // not active, first show, do not render anything, next frame if (!popup.active) { skipThisFrame(); popup.active = true; popup.height = 0; popup.widgetElementId = widgetElementId; } if (has(flags, PopupFlags::BelowLastWidget)) { popup.position = ctx->widget.rect.bottomLeft(); } else if (has(flags, PopupFlags::RightSideLastWidget)) { popup.position = ctx->widget.rect.topRight(); } else { popup.position = position; } popup.width = width; f32 height = popup.height; auto bodyElemState = ctx->theme->getElement(widgetElementId).normalState(); Point pos = { ctx->containerRect.x, ctx->containerRect.y }; if (has(flags, PopupFlags::WindowCenter)) { pos = { (ctx->renderer->getWindowSize().x - width) / 2.0f, (ctx->renderer->getWindowSize().y - height) / 2.0f }; pos += popup.moveOffset; } else if (has(flags, PopupFlags::CustomPosition) || has(flags, PopupFlags::BelowLastWidget) || has(flags, PopupFlags::RightSideLastWidget)) { pos = { popup.position.x, popup.position.y }; } if (has(flags, PopupFlags::IsMenu) && !ctx->rightSideMenu) { pos.x -= ctx->activeMenuBarItemWidgetWidth + width; } // limit to right side if (pos.x + width > ctx->renderer->getWindowSize().x) { if (has(flags, PopupFlags::IsMenu)) { ctx->rightSideMenu = false; pos.x -= ctx->activeMenuBarItemWidgetWidth + width; } else { pos.x = ctx->renderer->getWindowSize().x - width; } } // limit to top if (pos.y + height > ctx->renderer->getWindowSize().y) { pos.y = ctx->renderer->getWindowSize().y - height; } // limit to left if (pos.x < 0) { pos.x = 0; } // limit to bottom if (pos.y < 0) { pos.y = 0; } pos.x = round(pos.x); pos.y = round(pos.y); popup.position = pos; Rect popupRect = { pos.x, pos.y, width, height }; ctx->layoutStack.push_back(LayoutState(LayoutType::Container)); ctx->layoutStack.back().position = { pos.x + bodyElemState.border * ctx->globalScale, pos.y + bodyElemState.border * ctx->globalScale }; ctx->layoutStack.back().width = width - bodyElemState.border * 2 * ctx->globalScale; ctx->layoutStack.back().savedPenPosition = ctx->penPosition; ctx->penPosition = ctx->layoutStack.back().position; ctx->sameLineStack.push_back(ctx->widget.sameLine); ctx->widget.sameLine = false; // reset the same line, we don't need that at the popup start popup.prevContainerRect = ctx->containerRect; ctx->containerRect = ctx->renderer->getWindowRect(); ctx->renderer->pushClipRect(ctx->renderer->getWindowRect(), false); if (has(flags, PopupFlags::FadeWindowContents)) { auto& behindElemState = ctx->theme->getElement(WidgetElementId::PopupBehind).normalState(); ctx->renderer->cmdSetColor(behindElemState.color); ctx->renderer->cmdDrawImageBordered( behindElemState.image, behindElemState.border, ctx->containerRect, ctx->globalScale); } ctx->renderer->cmdSetColor(bodyElemState.color); ctx->renderer->cmdDrawImageBordered( bodyElemState.image, bodyElemState.border, popupRect, ctx->globalScale); popup.widgetId = ctx->currentWidgetId; ctx->currentWidgetId++; } void endPopup() { auto& popup = ctx->popupStack[ctx->popupIndex - 1]; //TODO: make a better popup move if (ctx->isActiveLayer() && (ctx->widget.hoveredWidgetId == popup.widgetId || popup.startedToDrag || ctx->widget.hoveredWidgetType == WidgetType::Label)) { auto rect = Rect(popup.position.x, popup.position.y, popup.width, popup.height); if (ctx->event.type == InputEvent::Type::MouseDown && rect.contains(ctx->event.mouse.point) && !popup.startedToDrag) { popup.startedToDrag = true; popup.lastMouseDownPoint = ctx->event.mouse.point; popup.lastMousePoint = ctx->event.mouse.point; } // popup drag by mouse if (popup.startedToDrag || popup.draggingPopup) { auto mousePos = ctx->inputProvider->getMousePosition(); if (popup.startedToDrag && popup.lastMouseDownPoint.getDistance(mousePos) >= movePopupMaxDistanceTrigger && !popup.draggingPopup && ctx->widget.hoveredWidgetId == popup.widgetId) { popup.dragDelta = popup.position - mousePos; // clear the event so other widgets will not use it ctx->event = InputEvent(); popup.draggingPopup = true; popup.startedToDrag = false; } else if (popup.draggingPopup) { popup.position = mousePos + popup.dragDelta; popup.moveOffset += mousePos - popup.lastMousePoint; popup.lastMousePoint = mousePos; } } } if (ctx->event.type == InputEvent::Type::MouseUp) { if (popup.draggingPopup) { popup.moveOffset += ctx->event.mouse.point - popup.lastMousePoint; popup.lastMousePoint = ctx->event.mouse.point; // clear the event so other widgets will not use it ctx->event = InputEvent(); } popup.startedToDrag = false; popup.draggingPopup = false; forceRepaint(); } auto bodyElemState = ctx->theme->getElement(popup.widgetElementId).normalState(); popup.height = (ctx->penPosition.y - ctx->layoutStack.back().position.y) + bodyElemState.border * 2.0f * ctx->globalScale - ctx->spacing * ctx->globalScale; ctx->penPosition = ctx->layoutStack.back().savedPenPosition; ctx->containerRect = popup.prevContainerRect; ctx->renderer->popClipRect(); ctx->layoutStack.pop_back(); ctx->widget.sameLine = ctx->sameLineStack.back(); ctx->sameLineStack.pop_back(); if (!has(popup.flags, PopupFlags::SameLayer)) decrementLayerIndex(); if (has(popup.flags, PopupFlags::TopMost)) ctx->renderer->setZOrder(popup.oldZOrder); ctx->popupIndex--; } void closePopup() { auto& popup = ctx->popupStack[ctx->popupIndex - 1]; popup.active = false; if (!has(popup.flags, PopupFlags::SameLayer)) decrementWindowMaxLayerIndex(); ctx->event.type = InputEvent::Type::None; ctx->widget.focusedWidgetId = 0; skipThisFrame(); forceRepaint(); } bool clickedOutsidePopup() { if (ctx->event.type != InputEvent::Type::MouseDown) return false; if (ctx->layoutStack.back().type == LayoutType::Container && ctx->isActiveLayer()) { auto& popup = ctx->popupStack[ctx->popupIndex - 1]; Rect rc = { popup.position.x, popup.position.y, popup.width, popup.height }; if (!rc.contains(ctx->event.mouse.point)) { return true; } } return false; } bool mouseOutsidePopup() { if (ctx->layoutStack.back().type == LayoutType::Container && ctx->isActiveLayer()) { auto& popup = ctx->popupStack[ctx->popupIndex - 1]; Rect rc = { popup.position.x, popup.position.y, popup.width, popup.height }; if (!rc.contains(ctx->event.mouse.point)) { return true; } } return false; } bool pressedEscapeOnPopup() { auto& popup = ctx->popupStack[ctx->popupIndex - 1]; if (popup.alreadyClosedWithEscape) return false; if (ctx->layoutStack.back().type == LayoutType::Container && ctx->event.type == InputEvent::Type::Key && ctx->event.key.down && ctx->event.key.code == KeyCode::Esc && ctx->isActiveLayer()) { popup.alreadyClosedWithEscape = true; return true; } return false; } bool mustClosePopup() { return pressedEscapeOnPopup() || clickedOutsidePopup(); } MessageBoxButtons messageBox( const char* title, const char* message, MessageBoxButtons buttons, MessageBoxIcon icon, u32 width, Image customIcon) { UiThemeElement* iconElem = nullptr; switch (icon) { case hui::MessageBoxIcon::Error: iconElem = &ctx->theme->getElement(WidgetElementId::MessageBoxIconError); break; case hui::MessageBoxIcon::Info: iconElem = &ctx->theme->getElement(WidgetElementId::MessageBoxIconInfo); break; case hui::MessageBoxIcon::Question: iconElem = &ctx->theme->getElement(WidgetElementId::MessageBoxIconQuestion); break; case hui::MessageBoxIcon::Warning: iconElem = &ctx->theme->getElement(WidgetElementId::MessageBoxIconWarning); break; default: break; } hui::beginPopup(500, PopupFlags::FadeWindowContents | PopupFlags::WindowCenter); auto iterFnt = ctx->theme->fonts.find("title"); hui::pushTint(Color::cyan); if (iterFnt != ctx->theme->fonts.end()) { hui::labelCustomFont(title, (Image)iterFnt->second); } else { hui::label(title); } hui::popTint(); hui::line(); // body and icon f32 titleColWidths[2] = { 0.8, 0.2 }; beginColumns(2, titleColWidths); hui::multilineLabel(message, HAlignType::Left); nextColumn(); hui::image((Image)iconElem->normalState().image, 0, hui::HAlignType::Right); endColumns(); hui::gap(10); MessageBoxButtons returnBtns = MessageBoxButtons::None; u32 colCount = 0; f32 colWidths[6] = { -1,-1,-1,-1,-1,-1 }; if (!!(buttons & MessageBoxButtons::Ok)) colCount++; if (!!(buttons & MessageBoxButtons::Cancel)) colCount++; if (!!(buttons & MessageBoxButtons::Yes)) colCount++; if (!!(buttons & MessageBoxButtons::No)) colCount++; if (!!(buttons & MessageBoxButtons::Retry)) colCount++; if (!!(buttons & MessageBoxButtons::Abort)) colCount++; hui::beginColumns(colCount, colWidths); if (!!(buttons & MessageBoxButtons::Ok)) { if (hui::button("OK")) { returnBtns |= MessageBoxButtons::Ok; } hui::nextColumn(); } if (!!(buttons & MessageBoxButtons::Cancel)) { if (hui::button("Cancel")) { returnBtns |= MessageBoxButtons::Cancel; } hui::nextColumn(); } if (!!(buttons & MessageBoxButtons::Yes)) { if (hui::button("Yes")) { returnBtns |= buttons & MessageBoxButtons::Yes; } hui::nextColumn(); } if (!!(buttons & MessageBoxButtons::No)) { if (hui::button("No")) { returnBtns |= MessageBoxButtons::No; } hui::nextColumn(); } if (!!(buttons & MessageBoxButtons::Retry)) { if (hui::button("Retry")) { returnBtns |= MessageBoxButtons::Retry; } hui::nextColumn(); } if (!!(buttons & MessageBoxButtons::Abort)) { if (hui::button("Abort")) { returnBtns |= MessageBoxButtons::Abort; } hui::nextColumn(); } hui::endColumns(); if (mustClosePopup()) { returnBtns = MessageBoxButtons::Abort | MessageBoxButtons::Cancel | MessageBoxButtons::ClosedByEscape | MessageBoxButtons::No; closePopup(); } else if (!!returnBtns) { closePopup(); } hui::endPopup(); return returnBtns; } }
22.635417
157
0.684952
[ "render" ]
16278c2f91acef3eb317f8c4b200589cf988805b
2,435
cpp
C++
examples/maze_navigation.cpp
ChampiB/Homing-Pigeon
3bc238cb4d49a65c338156f4728bfeb46136739b
[ "MIT" ]
4
2021-01-03T20:12:02.000Z
2022-01-27T10:47:34.000Z
examples/maze_navigation.cpp
ChampiB/Homing-Pigeon
3bc238cb4d49a65c338156f4728bfeb46136739b
[ "MIT" ]
null
null
null
examples/maze_navigation.cpp
ChampiB/Homing-Pigeon
3bc238cb4d49a65c338156f4728bfeb46136739b
[ "MIT" ]
null
null
null
#include "distributions/Transition.h" #include "environments/MazeEnv.h" #include "nodes/VarNode.h" #include "math/Ops.h" #include "api/API.h" #include "graphs/FactorGraph.h" #include "algorithms/planning/tmp/MCTS.h" #include "algorithms/inference/VMP.h" #include <torch/torch.h> #include <iostream> using namespace hopi::environments; using namespace hopi::distributions; using namespace hopi::nodes; using namespace hopi::math; using namespace hopi::graphs; using namespace hopi::algorithms::inference; using namespace hopi::algorithms::planning; using namespace hopi::api; using namespace torch; int main() { /** ** Create the environment and matrix generator. **/ auto env = MazeEnv::create("../examples/mazes/1.maze"); /** ** Create the model's parameters. **/ Tensor U0 = Ops::uniform({env->actions()}); Tensor A = env->A(); Tensor B = env->B(); Tensor D0 = env->D(); /** ** Create the generative model. **/ VarNode *a0 = API::Categorical(U0); VarNode *s0 = API::Categorical(D0); VarNode *o0 = API::Transition(s0, A); o0->setType(VarNodeType::OBSERVED); o0->setName("o0"); VarNode *s1 = API::ActiveTransition(s0, a0, B); VarNode *o1 = API::Transition(s1, A); o1->setName("o1"); o1->setType(VarNodeType::OBSERVED); auto fg = FactorGraph::current(); fg->setTreeRoot(s1); fg->loadEvidence(env->observations(), "../examples/evidences/1.evi"); /** ** Create the model's prior preferences. **/ Tensor D_tilde = Ops::uniform({env->states()}); Tensor E_tilde = softmax(env->observations() - API::range(0, env->observations()), 0); /** ** Run the simulation. **/ env->print(); for (int i = 0; i < 20; ++i) { // Action perception cycle VMP::inference(fg->getNodes()); auto algoTree = MCTS::create(env->actions(), D_tilde, E_tilde); for (int j = 0; j < 100; ++j) { // Planning VarNode *n = algoTree->nodeSelection(fg); algoTree->expansion(n, A, B); VMP::inference(algoTree->lastExpandedNodes()); algoTree->evaluation(fg, A, B); algoTree->propagation(fg->treeRoot()); } int a = algoTree->actionSelection(fg->treeRoot()); int o = env->execute(a); fg->integrate(a, Ops::one_hot(env->observations(), o), A, B); env->print(); } return EXIT_SUCCESS; }
30.4375
90
0.61232
[ "model" ]
162abe9ba4a2cfc2e311e50c632d35447609b64d
1,754
cpp
C++
solutions/hitting-the-targets.cpp
techchrism/kattis-problems
4d5b761fefdee04e4396fc09f0ee3578fc44a76f
[ "MIT" ]
null
null
null
solutions/hitting-the-targets.cpp
techchrism/kattis-problems
4d5b761fefdee04e4396fc09f0ee3578fc44a76f
[ "MIT" ]
null
null
null
solutions/hitting-the-targets.cpp
techchrism/kattis-problems
4d5b761fefdee04e4396fc09f0ee3578fc44a76f
[ "MIT" ]
null
null
null
// Problem https://open.kattis.com/problems/hittingtargets #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <limits> #include <ctime> #include <cmath> #include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> using namespace std; #define MP make_pair #define PB push_back #define INF (int)1e9 #define EPS 1e-9 #define PI 3.1415926535897932384626433832795 #define MOD 1000000007 typedef pair<int, int> PII; typedef vector<int> VI; typedef vector<string> VS; typedef vector<PII> VII; typedef vector<VI> VVI; typedef map<int, int> MPII; typedef set<int> SETI; typedef multiset<int> MSETI; typedef long int int32; typedef unsigned long int ul; typedef long long int ll; typedef unsigned long long int ull; struct Target { int x1,y1,x2,y2; int x,y,r; bool rect; }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin>>n; vector<Target> tg; for(int i=0;i<n;i++){ string s; cin>>s; Target t; t.rect=(s=="rectangle"); if(t.rect) cin>>t.x1>>t.y1>>t.x2>>t.y2; else cin>>t.x>>t.y>>t.r; tg.PB(t); } cin>>n; for(int i=0;i<n;i++){ int x,y; cin>>x>>y; int h=0; for(auto t:tg){ if(t.rect){ if(x>=t.x1&&x<=t.x2&&y>=t.y1&&y<=t.y2) h++; }else{ if(pow(x-t.x,2)+pow(y-t.y,2)<=pow(t.r,2)) h++; } } cout<<h<<"\n"; } return 0; }
19.931818
62
0.596351
[ "vector" ]
162d91077c2b5b9db21edc3f8b34bbaa2e12a14c
275,273
cpp
C++
src/mongoose/mongoose.cpp
frc-862/vision_server
2d26896eecfe0a2a24bb64ce72ed583a97b3b4de
[ "MIT" ]
null
null
null
src/mongoose/mongoose.cpp
frc-862/vision_server
2d26896eecfe0a2a24bb64ce72ed583a97b3b4de
[ "MIT" ]
null
null
null
src/mongoose/mongoose.cpp
frc-862/vision_server
2d26896eecfe0a2a24bb64ce72ed583a97b3b4de
[ "MIT" ]
null
null
null
#include "mongoose.h" #ifdef NS_MODULE_LINES #line 1 "src/internal.h" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef MG_INTERNAL_HEADER_INCLUDED #define MG_INTERNAL_HEADER_INCLUDED #ifndef MG_MALLOC #define MG_MALLOC malloc #endif #ifndef MG_CALLOC #define MG_CALLOC calloc #endif #ifndef MG_REALLOC #define MG_REALLOC realloc #endif #ifndef MG_FREE #define MG_FREE free #endif #ifndef MBUF_REALLOC #define MBUF_REALLOC MG_REALLOC #endif #ifndef MBUF_FREE #define MBUF_FREE MG_FREE #endif #define MG_SET_PTRPTR(_ptr, _v) \ do { \ if (_ptr) *(_ptr) = _v; \ } while (0) #ifndef MG_INTERNAL #define MG_INTERNAL static #endif #if !defined(MG_MGR_EV_MGR) /* * Switches between different methods of handling sockets. Supported values: * 0 - select() * 1 - epoll() (Linux only) */ #define MG_MGR_EV_MGR 0 /* select() */ #endif #ifdef PICOTCP #define NO_LIBC #define MG_DISABLE_FILESYSTEM #define MG_DISABLE_POPEN #define MG_DISABLE_CGI #define MG_DISABLE_DIRECTORY_LISTING #define MG_DISABLE_SOCKETPAIR #define MG_DISABLE_PFS #endif /* Amalgamated: #include "../mongoose.h" */ /* internals that need to be accessible in unit tests */ MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa); MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len); MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, int ev, void *ev_data); MG_INTERNAL void mg_forward(struct mg_connection *, struct mg_connection *); MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c); MG_INTERNAL void mg_remove_conn(struct mg_connection *c); #ifndef MG_DISABLE_FILESYSTEM MG_INTERNAL int find_index_file(char *, size_t, const char *, cs_stat_t *); #endif #ifdef _WIN32 void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len); #endif /* * Reassemble the content of the buffer (buf, blen) which should be * in the HTTP chunked encoding, by collapsing data chunks to the * beginning of the buffer. * * If chunks get reassembled, modify hm->body to point to the reassembled * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK * in nc->flags, delete reassembled body from the mbuf. * * Return reassembled body size. */ MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen); #ifndef MG_DISABLE_FILESYSTEM MG_INTERNAL time_t mg_parse_date_string(const char *datetime); MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st); #endif /* Forward declarations for testing. */ extern void *(*test_malloc)(size_t); extern void *(*test_calloc)(size_t, size_t); #endif /* MG_INTERNAL_HEADER_INCLUDED */ #ifdef NS_MODULE_LINES #line 1 "src/../../common/base64.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "base64.h" */ #include <string.h> /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */ #define NUM_UPPERCASES ('Z' - 'A' + 1) #define NUM_LETTERS (NUM_UPPERCASES * 2) #define NUM_DIGITS ('9' - '0' + 1) /* * Emit a base64 code char. * * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps */ static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) { if (v < NUM_UPPERCASES) { ctx->b64_putc(v + 'A', ctx->user_data); } else if (v < (NUM_LETTERS)) { ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data); } else if (v < (NUM_LETTERS + NUM_DIGITS)) { ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data); } else { ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/', ctx->user_data); } } static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) { int a, b, c; a = ctx->chunk[0]; b = ctx->chunk[1]; c = ctx->chunk[2]; cs_base64_emit_code(ctx, a >> 2); cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4)); if (ctx->chunk_size > 1) { cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6)); } if (ctx->chunk_size > 2) { cs_base64_emit_code(ctx, c & 63); } } void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, void *user_data) { ctx->chunk_size = 0; ctx->b64_putc = b64_putc; ctx->user_data = user_data; } void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) { const unsigned char *src = (const unsigned char *) str; size_t i; for (i = 0; i < len; i++) { ctx->chunk[ctx->chunk_size++] = src[i]; if (ctx->chunk_size == 3) { cs_base64_emit_chunk(ctx); ctx->chunk_size = 0; } } } void cs_base64_finish(struct cs_base64_ctx *ctx) { if (ctx->chunk_size > 0) { int i; memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size); cs_base64_emit_chunk(ctx); for (i = 0; i < (3 - ctx->chunk_size); i++) { ctx->b64_putc('=', ctx->user_data); } } } #define BASE64_ENCODE_BODY \ static const char *b64 = \ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \ int i, j, a, b, c; \ \ for (i = j = 0; i < src_len; i += 3) { \ a = src[i]; \ b = i + 1 >= src_len ? 0 : src[i + 1]; \ c = i + 2 >= src_len ? 0 : src[i + 2]; \ \ BASE64_OUT(b64[a >> 2]); \ BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \ if (i + 1 < src_len) { \ BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \ } \ if (i + 2 < src_len) { \ BASE64_OUT(b64[c & 63]); \ } \ } \ \ while (j % 4 != 0) { \ BASE64_OUT('='); \ } \ BASE64_FLUSH() #define BASE64_OUT(ch) \ do { \ dst[j++] = (ch); \ } while (0) #define BASE64_FLUSH() \ do { \ dst[j++] = '\0'; \ } while (0) void cs_base64_encode(const unsigned char *src, int src_len, char *dst) { BASE64_ENCODE_BODY; } #undef BASE64_OUT #undef BASE64_FLUSH #define BASE64_OUT(ch) \ do { \ fprintf(f, "%c", (ch)); \ j++; \ } while (0) #define BASE64_FLUSH() void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) { BASE64_ENCODE_BODY; } #undef BASE64_OUT #undef BASE64_FLUSH /* Convert one byte of encoded base64 input stream to 6-bit chunk */ static unsigned char from_b64(unsigned char ch) { /* Inverse lookup map */ static const unsigned char tab[128] = { 255, 255, 255, 255, 255, 255, 255, 255, /* 0 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 8 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 16 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 24 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 32 */ 255, 255, 255, 62, 255, 255, 255, 63, /* 40 */ 52, 53, 54, 55, 56, 57, 58, 59, /* 48 */ 60, 61, 255, 255, 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */ 255, 0, 1, 2, 3, 4, 5, 6, /* 64 */ 7, 8, 9, 10, 11, 12, 13, 14, /* 72 */ 15, 16, 17, 18, 19, 20, 21, 22, /* 80 */ 23, 24, 25, 255, 255, 255, 255, 255, /* 88 */ 255, 26, 27, 28, 29, 30, 31, 32, /* 96 */ 33, 34, 35, 36, 37, 38, 39, 40, /* 104 */ 41, 42, 43, 44, 45, 46, 47, 48, /* 112 */ 49, 50, 51, 255, 255, 255, 255, 255, /* 120 */ }; return tab[ch & 127]; } int cs_base64_decode(const unsigned char *s, int len, char *dst) { unsigned char a, b, c, d; int orig_len = len; while (len >= 4 && (a = from_b64(s[0])) != 255 && (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 && (d = from_b64(s[3])) != 255) { s += 4; len -= 4; if (a == 200 || b == 200) break; /* '=' can't be there */ *dst++ = a << 2 | b >> 4; if (c == 200) break; *dst++ = b << 4 | c >> 2; if (d == 200) break; *dst++ = c << 6 | d; } *dst = 0; return orig_len - len; } #endif /* EXCLUDE_COMMON */ #ifdef NS_MODULE_LINES #line 1 "src/../../common/cs_dbg.c" /**/ #endif /* Amalgamated: #include "cs_dbg.h" */ #include <stdarg.h> #include <stdio.h> enum cs_log_level s_cs_log_level = #ifdef CS_ENABLE_DEBUG LL_DEBUG; #else LL_ERROR; #endif void cs_log_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" vfprintf(stderr, fmt, ap); #pragma GCC diagnostic pop va_end(ap); fputc('\n', stderr); fflush(stderr); } void cs_log_set_level(enum cs_log_level level) { s_cs_log_level = level; } #ifdef NS_MODULE_LINES #line 1 "src/../../common/dirent.c" /**/ #endif /* * Copyright (c) 2015 Cesanta Software Limited * All rights reserved */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "osdep.h" */ /* * This file contains POSIX opendir/closedir/readdir API implementation * for systems which do not natively support it (e.g. Windows). */ #ifndef MG_FREE #define MG_FREE free #endif #ifndef MG_MALLOC #define MG_MALLOC malloc #endif #ifdef _WIN32 DIR *opendir(const char *name) { DIR *dir = NULL; wchar_t wpath[MAX_PATH]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { to_wchar(name, wpath, ARRAY_SIZE(wpath)); attrs = GetFileAttributesW(wpath); if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { (void) wcscat(wpath, L"\\*"); dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { MG_FREE(dir); dir = NULL; } } return dir; } int closedir(DIR *dir) { int result = 0; if (dir != NULL) { if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; MG_FREE(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); } return result; } struct dirent *readdir(DIR *dir) { struct dirent *result = 0; if (dir) { if (dir->handle != INVALID_HANDLE_VALUE) { result = &dir->result; (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, result->d_name, sizeof(result->d_name), NULL, NULL); if (!FindNextFileW(dir->handle, &dir->info)) { (void) FindClose(dir->handle); dir->handle = INVALID_HANDLE_VALUE; } } else { SetLastError(ERROR_FILE_NOT_FOUND); } } else { SetLastError(ERROR_BAD_ARGUMENTS); } return result; } #endif #endif /* EXCLUDE_COMMON */ #ifdef NS_MODULE_LINES #line 1 "src/../deps/frozen/frozen.c" /**/ #endif /* * Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com> * Copyright (c) 2013 Cesanta Software Limited * All rights reserved * * This library is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http: *www.gnu.org/licenses/>. * * You are free to use this library under the terms of the GNU General * Public License, 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. * * Alternatively, you can license this library under a commercial * license, as set out in <https://www.cesanta.com/license>. */ #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> /* Amalgamated: #include "frozen.h" */ #ifdef _WIN32 #define snprintf _snprintf #endif #ifndef FROZEN_REALLOC #define FROZEN_REALLOC realloc #endif #ifndef FROZEN_FREE #define FROZEN_FREE free #endif struct frozen { const char *end; const char *cur; struct json_token *tokens; int max_tokens; int num_tokens; int do_realloc; }; static int parse_object(struct frozen *f); static int parse_value(struct frozen *f); #define EXPECT(cond, err_code) do { if (!(cond)) return (err_code); } while (0) #define TRY(expr) do { int _n = expr; if (_n < 0) return _n; } while (0) #define END_OF_STRING (-1) static int left(const struct frozen *f) { return f->end - f->cur; } static int is_space(int ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } static void skip_whitespaces(struct frozen *f) { while (f->cur < f->end && is_space(*f->cur)) f->cur++; } static int cur(struct frozen *f) { skip_whitespaces(f); return f->cur >= f->end ? END_OF_STRING : * (unsigned char *) f->cur; } static int test_and_skip(struct frozen *f, int expected) { int ch = cur(f); if (ch == expected) { f->cur++; return 0; } return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID; } static int is_alpha(int ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } static int is_digit(int ch) { return ch >= '0' && ch <= '9'; } static int is_hex_digit(int ch) { return is_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); } static int get_escape_len(const char *s, int len) { switch (*s) { case 'u': return len < 6 ? JSON_STRING_INCOMPLETE : is_hex_digit(s[1]) && is_hex_digit(s[2]) && is_hex_digit(s[3]) && is_hex_digit(s[4]) ? 5 : JSON_STRING_INVALID; case '"': case '\\': case '/': case 'b': case 'f': case 'n': case 'r': case 't': return len < 2 ? JSON_STRING_INCOMPLETE : 1; default: return JSON_STRING_INVALID; } } static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) { if (f->do_realloc && f->num_tokens >= f->max_tokens) { int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2; void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0])); if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL; f->max_tokens = new_size; f->tokens = (struct json_token *) p; } if (f->tokens == NULL || f->max_tokens == 0) return 0; if (f->num_tokens >= f->max_tokens) return JSON_TOKEN_ARRAY_TOO_SMALL; f->tokens[f->num_tokens].ptr = ptr; f->tokens[f->num_tokens].type = type; f->num_tokens++; return 0; } static int capture_len(struct frozen *f, int token_index, const char *ptr) { if (f->tokens == 0 || f->max_tokens == 0) return 0; EXPECT(token_index >= 0 && token_index < f->max_tokens, JSON_STRING_INVALID); f->tokens[token_index].len = ptr - f->tokens[token_index].ptr; f->tokens[token_index].num_desc = (f->num_tokens - 1) - token_index; return 0; } /* identifier = letter { letter | digit | '_' } */ static int parse_identifier(struct frozen *f) { EXPECT(is_alpha(cur(f)), JSON_STRING_INVALID); TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING)); while (f->cur < f->end && (*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) { f->cur++; } capture_len(f, f->num_tokens - 1, f->cur); return 0; } static int get_utf8_char_len(unsigned char ch) { if ((ch & 0x80) == 0) return 1; switch (ch & 0xf0) { case 0xf0: return 4; case 0xe0: return 3; default: return 2; } } /* string = '"' { quoted_printable_chars } '"' */ static int parse_string(struct frozen *f) { int n, ch = 0, len = 0; TRY(test_and_skip(f, '"')); TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING)); for (; f->cur < f->end; f->cur += len) { ch = * (unsigned char *) f->cur; len = get_utf8_char_len((unsigned char) ch); EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID); /* No control chars */ EXPECT(len < left(f), JSON_STRING_INCOMPLETE); if (ch == '\\') { EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n); len += n; } else if (ch == '"') { capture_len(f, f->num_tokens - 1, f->cur); f->cur++; break; }; } return ch == '"' ? 0 : JSON_STRING_INCOMPLETE; } /* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */ static int parse_number(struct frozen *f) { int ch = cur(f); TRY(capture_ptr(f, f->cur, JSON_TYPE_NUMBER)); if (ch == '-') f->cur++; EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID); while (f->cur < f->end && is_digit(f->cur[0])) f->cur++; if (f->cur < f->end && f->cur[0] == '.') { f->cur++; EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID); while (f->cur < f->end && is_digit(f->cur[0])) f->cur++; } if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) { f->cur++; EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++; EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID); while (f->cur < f->end && is_digit(f->cur[0])) f->cur++; } capture_len(f, f->num_tokens - 1, f->cur); return 0; } /* array = '[' [ value { ',' value } ] ']' */ static int parse_array(struct frozen *f) { int ind; TRY(test_and_skip(f, '[')); TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY)); ind = f->num_tokens - 1; while (cur(f) != ']') { TRY(parse_value(f)); if (cur(f) == ',') f->cur++; } TRY(test_and_skip(f, ']')); capture_len(f, ind, f->cur); return 0; } static int compare(const char *s, const char *str, int len) { int i = 0; while (i < len && s[i] == str[i]) i++; return i == len ? 1 : 0; } static int expect(struct frozen *f, const char *s, int len, enum json_type t) { int i, n = left(f); TRY(capture_ptr(f, f->cur, t)); for (i = 0; i < len; i++) { if (i >= n) return JSON_STRING_INCOMPLETE; if (f->cur[i] != s[i]) return JSON_STRING_INVALID; } f->cur += len; TRY(capture_len(f, f->num_tokens - 1, f->cur)); return 0; } /* value = 'null' | 'true' | 'false' | number | string | array | object */ static int parse_value(struct frozen *f) { int ch = cur(f); switch (ch) { case '"': TRY(parse_string(f)); break; case '{': TRY(parse_object(f)); break; case '[': TRY(parse_array(f)); break; case 'n': TRY(expect(f, "null", 4, JSON_TYPE_NULL)); break; case 't': TRY(expect(f, "true", 4, JSON_TYPE_TRUE)); break; case 'f': TRY(expect(f, "false", 5, JSON_TYPE_FALSE)); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': TRY(parse_number(f)); break; default: return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID; } return 0; } /* key = identifier | string */ static int parse_key(struct frozen *f) { int ch = cur(f); #if 0 printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur); #endif if (is_alpha(ch)) { TRY(parse_identifier(f)); } else if (ch == '"') { TRY(parse_string(f)); } else { return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID; } return 0; } /* pair = key ':' value */ static int parse_pair(struct frozen *f) { TRY(parse_key(f)); TRY(test_and_skip(f, ':')); TRY(parse_value(f)); return 0; } /* object = '{' pair { ',' pair } '}' */ static int parse_object(struct frozen *f) { int ind; TRY(test_and_skip(f, '{')); TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT)); ind = f->num_tokens - 1; while (cur(f) != '}') { TRY(parse_pair(f)); if (cur(f) == ',') f->cur++; } TRY(test_and_skip(f, '}')); capture_len(f, ind, f->cur); return 0; } static int doit(struct frozen *f) { if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID; if (f->end == f->cur) return JSON_STRING_INCOMPLETE; TRY(parse_object(f)); TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF)); capture_len(f, f->num_tokens, f->cur); return 0; } /* json = object */ int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len) { struct frozen frozen; memset(&frozen, 0, sizeof(frozen)); frozen.end = s + s_len; frozen.cur = s; frozen.tokens = arr; frozen.max_tokens = arr_len; TRY(doit(&frozen)); return frozen.cur - s; } struct json_token *parse_json2(const char *s, int s_len) { struct frozen frozen; memset(&frozen, 0, sizeof(frozen)); frozen.end = s + s_len; frozen.cur = s; frozen.do_realloc = 1; if (doit(&frozen) < 0) { FROZEN_FREE((void *) frozen.tokens); frozen.tokens = NULL; } return frozen.tokens; } static int path_part_len(const char *p) { int i = 0; while (p[i] != '\0' && p[i] != '[' && p[i] != '.') i++; return i; } struct json_token *find_json_token(struct json_token *toks, const char *path) { while (path != 0 && path[0] != '\0') { int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path); if (path[0] == '[') { if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0; for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) { if (!is_digit(path[n])) return 0; ind *= 10; ind += path[n] - '0'; } if (path[n++] != ']') return 0; skip = 1; /* In objects, we skip 2 elems while iterating, in arrays 1. */ } else if (toks->type != JSON_TYPE_OBJECT) return 0; toks++; for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) { /* ind == -1 indicated that we're iterating an array, not object */ if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0; if (ind2 == ind || (ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) { i += skip - 1; break; }; if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY || toks[i - 1 + skip].type == JSON_TYPE_OBJECT) { i += toks[i - 1 + skip].num_desc; } } if (i == toks[-1].num_desc) return 0; path += n; if (path[0] == '.') path++; if (path[0] == '\0') return &toks[i]; toks += i; } return 0; } int json_emit_long(char *buf, int buf_len, long int value) { char tmp[20]; int n = snprintf(tmp, sizeof(tmp), "%ld", value); strncpy(buf, tmp, buf_len > 0 ? buf_len : 0); return n; } int json_emit_double(char *buf, int buf_len, double value) { char tmp[20]; int n = snprintf(tmp, sizeof(tmp), "%g", value); strncpy(buf, tmp, buf_len > 0 ? buf_len : 0); return n; } int json_emit_quoted_str(char *s, int s_len, const char *str, int len) { const char *begin = s, *end = s + s_len, *str_end = str + len; char ch; #define EMIT(x) do { if (s < end) *s = x; s++; } while (0) EMIT('"'); while (str < str_end) { ch = *str++; switch (ch) { case '"': EMIT('\\'); EMIT('"'); break; case '\\': EMIT('\\'); EMIT('\\'); break; case '\b': EMIT('\\'); EMIT('b'); break; case '\f': EMIT('\\'); EMIT('f'); break; case '\n': EMIT('\\'); EMIT('n'); break; case '\r': EMIT('\\'); EMIT('r'); break; case '\t': EMIT('\\'); EMIT('t'); break; default: EMIT(ch); } } EMIT('"'); if (s < end) { *s = '\0'; } return s - begin; } int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) { if (buf_len > 0 && len > 0) { int n = len < buf_len ? len : buf_len; memcpy(buf, str, n); if (n < buf_len) { buf[n] = '\0'; } } return len; } int json_emit_va(char *s, int s_len, const char *fmt, va_list ap) { const char *end = s + s_len, *str, *orig = s; size_t len; while (*fmt != '\0') { switch (*fmt) { case '[': case ']': case '{': case '}': case ',': case ':': case ' ': case '\r': case '\n': case '\t': if (s < end) { *s = *fmt; } s++; break; case 'i': s += json_emit_long(s, end - s, va_arg(ap, long)); break; case 'f': s += json_emit_double(s, end - s, va_arg(ap, double)); break; case 'v': str = va_arg(ap, char *); len = va_arg(ap, size_t); s += json_emit_quoted_str(s, end - s, str, len); break; case 'V': str = va_arg(ap, char *); len = va_arg(ap, size_t); s += json_emit_unquoted_str(s, end - s, str, len); break; case 's': str = va_arg(ap, char *); s += json_emit_quoted_str(s, end - s, str, strlen(str)); break; case 'S': str = va_arg(ap, char *); s += json_emit_unquoted_str(s, end - s, str, strlen(str)); break; case 'T': s += json_emit_unquoted_str(s, end - s, "true", 4); break; case 'F': s += json_emit_unquoted_str(s, end - s, "false", 5); break; case 'N': s += json_emit_unquoted_str(s, end - s, "null", 4); break; default: return 0; } fmt++; } /* Best-effort to 0-terminate generated string */ if (s < end) { *s = '\0'; } return s - orig; } int json_emit(char *buf, int buf_len, const char *fmt, ...) { int len; va_list ap; va_start(ap, fmt); len = json_emit_va(buf, buf_len, fmt, ap); va_end(ap); return len; } #ifdef NS_MODULE_LINES #line 1 "src/../../common/md5.c" /**/ #endif /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ #if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON) /* Amalgamated: #include "md5.h" */ #ifndef CS_ENABLE_NATIVE_MD5 static void byteReverse(unsigned char *buf, unsigned longs) { /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ #if BYTE_ORDER == BIG_ENDIAN do { uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | ((unsigned) buf[1] << 8 | buf[0]); *(uint32_t *) buf = t; buf += 4; } while (--longs); #else (void) buf; (void) longs; #endif } #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f, w, x, y, z, data, s) \ (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5_Init(MD5_CTX *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) { uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) { uint32_t t; t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; ctx->bits[1] += (uint32_t) len >> 29; t = (t >> 3) & 0x3f; if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); buf += t; len -= t; } while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); buf += 64; len -= 64; } memcpy(ctx->in, buf, len); } void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { unsigned count; unsigned char *p; uint32_t *a; count = (ctx->bits[0] >> 3) & 0x3F; p = ctx->in + count; *p++ = 0x80; count = 64 - 1 - count; if (count < 8) { memset(p, 0, count); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); memset(ctx->in, 0, 56); } else { memset(p, 0, count - 8); } byteReverse(ctx->in, 14); a = (uint32_t *) ctx->in; a[14] = ctx->bits[0]; a[15] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset((char *) ctx, 0, sizeof(*ctx)); } #endif /* CS_ENABLE_NATIVE_MD5 */ /* * Stringify binary data. Output buffer size must be 2 * size_of_input + 1 * because each byte of input takes 2 bytes in string representation * plus 1 byte for the terminating \0 character. */ void cs_to_hex(char *to, const unsigned char *p, size_t len) { static const char *hex = "0123456789abcdef"; for (; len--; p++) { *to++ = hex[p[0] >> 4]; *to++ = hex[p[0] & 0x0f]; } *to = '\0'; } char *cs_md5(char buf[33], ...) { unsigned char hash[16]; const unsigned char *p; va_list ap; MD5_CTX ctx; MD5_Init(&ctx); va_start(ap, buf); while ((p = va_arg(ap, const unsigned char *) ) != NULL) { size_t len = va_arg(ap, size_t); MD5_Update(&ctx, p, len); } va_end(ap); MD5_Final(hash, &ctx); cs_to_hex(buf, hash, sizeof(hash)); return buf; } #endif /* EXCLUDE_COMMON */ #ifdef NS_MODULE_LINES #line 1 "src/../../common/mbuf.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef EXCLUDE_COMMON #include <assert.h> #include <string.h> /* Amalgamated: #include "mbuf.h" */ #ifndef MBUF_REALLOC #define MBUF_REALLOC realloc #endif #ifndef MBUF_FREE #define MBUF_FREE free #endif void mbuf_init(struct mbuf *mbuf, size_t initial_size) { mbuf->len = mbuf->size = 0; mbuf->buf = NULL; mbuf_resize(mbuf, initial_size); } void mbuf_free(struct mbuf *mbuf) { if (mbuf->buf != NULL) { MBUF_FREE(mbuf->buf); mbuf_init(mbuf, 0); } } void mbuf_resize(struct mbuf *a, size_t new_size) { if (new_size > a->size || (new_size < a->size && new_size >= a->len)) { char *buf = (char *) MBUF_REALLOC(a->buf, new_size); /* * In case realloc fails, there's not much we can do, except keep things as * they are. Note that NULL is a valid return value from realloc when * size == 0, but that is covered too. */ if (buf == NULL && new_size != 0) return; a->buf = buf; a->size = new_size; } } void mbuf_trim(struct mbuf *mbuf) { mbuf_resize(mbuf, mbuf->len); } size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) { char *p = NULL; assert(a != NULL); assert(a->len <= a->size); assert(off <= a->len); /* check overflow */ if (~(size_t) 0 - (size_t) a->buf < len) return 0; if (a->len + len <= a->size) { memmove(a->buf + off + len, a->buf + off, a->len - off); if (buf != NULL) { memcpy(a->buf + off, buf, len); } a->len += len; } else if ((p = (char *) MBUF_REALLOC( a->buf, (a->len + len) * MBUF_SIZE_MULTIPLIER)) != NULL) { a->buf = p; memmove(a->buf + off + len, a->buf + off, a->len - off); if (buf != NULL) { memcpy(a->buf + off, buf, len); } a->len += len; a->size = a->len * MBUF_SIZE_MULTIPLIER; } else { len = 0; } return len; } size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) { return mbuf_insert(a, a->len, buf, len); } void mbuf_remove(struct mbuf *mb, size_t n) { if (n > 0 && n <= mb->len) { memmove(mb->buf, mb->buf + n, mb->len - n); mb->len -= n; } } #endif /* EXCLUDE_COMMON */ #ifdef NS_MODULE_LINES #line 1 "src/../../common/sha1.c" /**/ #endif /* Copyright(c) By Steve Reid <steve@edmweb.com> */ /* 100% Public Domain */ #if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON) /* Amalgamated: #include "sha1.h" */ #define SHA1HANDSOFF #if defined(__sun) /* Amalgamated: #include "solarisfixes.h" */ #endif union char64long16 { unsigned char c[64]; uint32_t l[16]; }; #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) static uint32_t blk0(union char64long16 *block, int i) { /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ #if BYTE_ORDER == LITTLE_ENDIAN block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); #endif return block->l[i]; } /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ #undef blk #undef R0 #undef R1 #undef R2 #undef R3 #undef R4 #define blk(i) \ (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ block->l[(i + 2) & 15] ^ block->l[i & 15], \ 1)) #define R0(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R1(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R2(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ w = rol(w, 30); #define R3(v, w, x, y, z, i) \ z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ w = rol(w, 30); #define R4(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ w = rol(w, 30); void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { uint32_t a, b, c, d, e; union char64long16 block[1]; memcpy(block, buffer, 64); a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3); R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7); R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11); R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15); R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23); R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27); R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31); R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35); R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39); R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43); R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47); R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51); R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55); R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59); R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63); R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67); R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71); R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75); R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79); state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Erase working structures. The order of operations is important, * used to ensure that compiler doesn't optimize those out. */ memset(block, 0, sizeof(block)); a = b = c = d = e = 0; (void) a; (void) b; (void) c; (void) d; (void) e; } void cs_sha1_init(cs_sha1_ctx *context) { context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, uint32_t len) { uint32_t i, j; j = context->count[0]; if ((context->count[0] += len << 3) < j) context->count[1]++; context->count[1] += (len >> 29); j = (j >> 3) & 63; if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64 - j)); cs_sha1_transform(context->state, context->buffer); for (; i + 63 < len; i += 64) { cs_sha1_transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) { unsigned i; unsigned char finalcount[8], c; for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); } c = 0200; cs_sha1_update(context, &c, 1); while ((context->count[0] & 504) != 448) { c = 0000; cs_sha1_update(context, &c, 1); } cs_sha1_update(context, finalcount, 8); for (i = 0; i < 20; i++) { digest[i] = (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); } memset(context, '\0', sizeof(*context)); memset(&finalcount, '\0', sizeof(finalcount)); } void cs_hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char out[20]) { cs_sha1_ctx ctx; unsigned char buf1[64], buf2[64], tmp_key[20], i; if (keylen > sizeof(buf1)) { cs_sha1_init(&ctx); cs_sha1_update(&ctx, key, keylen); cs_sha1_final(tmp_key, &ctx); key = tmp_key; keylen = sizeof(tmp_key); } memset(buf1, 0, sizeof(buf1)); memset(buf2, 0, sizeof(buf2)); memcpy(buf1, key, keylen); memcpy(buf2, key, keylen); for (i = 0; i < sizeof(buf1); i++) { buf1[i] ^= 0x36; buf2[i] ^= 0x5c; } cs_sha1_init(&ctx); cs_sha1_update(&ctx, buf1, sizeof(buf1)); cs_sha1_update(&ctx, data, datalen); cs_sha1_final(out, &ctx); cs_sha1_init(&ctx); cs_sha1_update(&ctx, buf2, sizeof(buf2)); cs_sha1_update(&ctx, out, 20); cs_sha1_final(out, &ctx); } #endif /* EXCLUDE_COMMON */ #ifdef NS_MODULE_LINES #line 1 "src/../../common/str_util.c" /**/ #endif /* * Copyright (c) 2015 Cesanta Software Limited * All rights reserved */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "osdep.h" */ /* Amalgamated: #include "str_util.h" */ #ifdef _MG_PROVIDE_STRNLEN size_t strnlen(const char *s, size_t maxlen) { size_t l = 0; for (; l < maxlen && s[l] != '\0'; l++) { } return l; } #endif #define C_SNPRINTF_APPEND_CHAR(ch) \ do { \ if (i < (int) buf_size) buf[i] = ch; \ i++; \ } while (0) #define C_SNPRINTF_FLAG_ZERO 1 #ifdef C_DISABLE_BUILTIN_SNPRINTF int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { return vsnprintf(buf, buf_size, fmt, ap); } #else static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, int field_width) { char tmp[40]; int i = 0, k = 0, neg = 0; if (num < 0) { neg++; num = -num; } /* Print into temporary buffer - in reverse order */ do { int rem = num % base; if (rem < 10) { tmp[k++] = '0' + rem; } else { tmp[k++] = 'a' + (rem - 10); } num /= base; } while (num > 0); /* Zero padding */ if (flags && C_SNPRINTF_FLAG_ZERO) { while (k < field_width && k < (int) sizeof(tmp) - 1) { tmp[k++] = '0'; } } /* And sign */ if (neg) { tmp[k++] = '-'; } /* Now output */ while (--k >= 0) { C_SNPRINTF_APPEND_CHAR(tmp[k]); } return i; } int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { int ch, i = 0, len_mod, flags, precision, field_width; while ((ch = *fmt++) != '\0') { if (ch != '%') { C_SNPRINTF_APPEND_CHAR(ch); } else { /* * Conversion specification: * zero or more flags (one of: # 0 - <space> + ') * an optional minimum field width (digits) * an optional precision (. followed by digits, or *) * an optional length modifier (one of: hh h l ll L q j z t) * conversion specifier (one of: d i o u x X e E f F g G a A c s p n) */ flags = field_width = precision = len_mod = 0; /* Flags. only zero-pad flag is supported. */ if (*fmt == '0') { flags |= C_SNPRINTF_FLAG_ZERO; } /* Field width */ while (*fmt >= '0' && *fmt <= '9') { field_width *= 10; field_width += *fmt++ - '0'; } /* Dynamic field width */ if (*fmt == '*') { field_width = va_arg(ap, int); fmt++; } /* Precision */ if (*fmt == '.') { fmt++; if (*fmt == '*') { precision = va_arg(ap, int); fmt++; } else { while (*fmt >= '0' && *fmt <= '9') { precision *= 10; precision += *fmt++ - '0'; } } } /* Length modifier */ switch (*fmt) { case 'h': case 'l': case 'L': case 'I': case 'q': case 'j': case 'z': case 't': len_mod = *fmt++; if (*fmt == 'h') { len_mod = 'H'; fmt++; } if (*fmt == 'l') { len_mod = 'q'; fmt++; } break; } ch = *fmt++; if (ch == 's') { const char *s = va_arg(ap, const char *); /* Always fetch parameter */ int j; int pad = field_width - (precision >= 0 ? strnlen(s, precision) : 0); for (j = 0; j < pad; j++) { C_SNPRINTF_APPEND_CHAR(' '); } /* Ignore negative and 0 precisions */ for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) { C_SNPRINTF_APPEND_CHAR(s[j]); } } else if (ch == 'c') { ch = va_arg(ap, int); /* Always fetch parameter */ C_SNPRINTF_APPEND_CHAR(ch); } else if (ch == 'd' && len_mod == 0) { i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags, field_width); } else if (ch == 'd' && len_mod == 'l') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 0) { i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned), ch == 'x' ? 16 : 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long), ch == 'x' ? 16 : 10, flags, field_width); } else if (ch == 'p') { unsigned long num = (unsigned long) va_arg(ap, void *); C_SNPRINTF_APPEND_CHAR('0'); C_SNPRINTF_APPEND_CHAR('x'); i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0); } else { #ifndef NO_LIBC /* * TODO(lsm): abort is not nice in a library, remove it * Also, ESP8266 SDK doesn't have it */ abort(); #endif } } } /* Zero-terminate the result */ if (buf_size > 0) { buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0'; } return i; } #endif int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) { int result; va_list ap; va_start(ap, fmt); result = c_vsnprintf(buf, buf_size, fmt, ap); va_end(ap); return result; } #ifdef _WIN32 void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; strncpy(buf, path, sizeof(buf)); buf[sizeof(buf) - 1] = '\0'; /* Trim trailing slashes. Leave backslash for paths like "X:\" */ p = buf + strlen(buf) - 1; while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; /* * Convert to Unicode and back. If doubly-converted string does not * match the original, something is fishy, reject. */ memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), NULL, NULL); if (strcmp(buf, buf2) != 0) { wbuf[0] = L'\0'; } } #endif /* _WIN32 */ #endif /* EXCLUDE_COMMON */ #ifdef NS_MODULE_LINES #line 1 "src/net.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved * * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, 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. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ /* Amalgamated: #include "internal.h" */ #if MG_MGR_EV_MGR == 1 /* epoll() */ #include <sys/epoll.h> #endif #define MG_CTL_MSG_MESSAGE_SIZE 8192 #define MG_VPRINTF_BUFFER_SIZE 100 #define MG_MAX_HOST_LEN 200 #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \ memcpy(dst, src, sizeof(*dst)); /* Which flags can be pre-set by the user at connection creation time. */ #define _MG_ALLOWED_CONNECT_FLAGS_MASK \ (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG) /* Which flags should be modifiable by user's callbacks. */ #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \ (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \ MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK) #ifndef intptr_t #define intptr_t long #endif struct ctl_msg { mg_event_handler_t callback; char message[MG_CTL_MSG_MESSAGE_SIZE]; }; int mg_is_error(int n); void mg_set_non_blocking_mode(sock_t sock); extern void mg_ev_mgr_init(struct mg_mgr *mgr); extern void mg_ev_mgr_free(struct mg_mgr *mgr); extern void mg_ev_mgr_add_conn(struct mg_connection *nc); extern void mg_ev_mgr_remove_conn(struct mg_connection *nc); MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) { DBG(("%p %p", mgr, c)); c->mgr = mgr; c->next = mgr->active_connections; mgr->active_connections = c; c->prev = NULL; if (c->next != NULL) c->next->prev = c; mg_ev_mgr_add_conn(c); } MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) { if (conn->prev == NULL) conn->mgr->active_connections = conn->next; if (conn->prev) conn->prev->next = conn->next; if (conn->next) conn->next->prev = conn->prev; mg_ev_mgr_remove_conn(conn); } MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, int ev, void *ev_data) { unsigned long flags_before; if (ev_handler == NULL) { /* * If protocol handler is specified, call it. Otherwise, call user-specified * event handler. */ ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler; } DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc, ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); #if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP) /* LCOV_EXCL_START */ if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_SEND /* handled separately */) { if (ev == MG_EV_RECV) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, nc->recv_mbuf.buf, *(int *) ev_data, ev); } else { mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev); } } /* LCOV_EXCL_STOP */ #endif if (ev_handler != NULL) { flags_before = nc->flags; ev_handler(nc, ev, ev_data); /* Prevent user handler from fiddling with system flags. */ if (ev_handler == nc->handler && nc->flags != flags_before) { nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) | (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK); } } DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc, ev_handler == nc->handler ? "user" : "proto", nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } void mg_if_poll(struct mg_connection *nc, time_t now) { mg_call(nc, NULL, MG_EV_POLL, &now); } static void mg_destroy_conn(struct mg_connection *conn) { mg_if_destroy_conn(conn); mbuf_free(&conn->recv_mbuf); mbuf_free(&conn->send_mbuf); MG_FREE(conn); } void mg_close_conn(struct mg_connection *conn) { DBG(("%p %lu", conn, conn->flags)); mg_call(conn, NULL, MG_EV_CLOSE, NULL); mg_remove_conn(conn); mg_destroy_conn(conn); } void mg_mgr_init(struct mg_mgr *m, void *user_data) { memset(m, 0, sizeof(*m)); m->ctl[0] = m->ctl[1] = INVALID_SOCKET; m->user_data = user_data; #ifdef _WIN32 { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } #elif !defined(AVR_LIBC) && !defined(MG_ESP8266) /* Ignore SIGPIPE signal, so if client cancels the request, it * won't kill the whole process. */ signal(SIGPIPE, SIG_IGN); #endif #ifdef MG_ENABLE_SSL { static int init_done; if (!init_done) { SSL_library_init(); init_done++; } } #endif mg_ev_mgr_init(m); DBG(("==================================")); DBG(("init mgr=%p", m)); } #ifdef MG_ENABLE_JAVASCRIPT static v7_val_t mg_send_js(struct v7 *v7) { v7_val_t arg0 = v7_arg(v7, 0); v7_val_t arg1 = v7_arg(v7, 1); struct mg_connection *c = (struct mg_connection *) v7_to_foreign(arg0); size_t len = 0; if (v7_is_string(arg1)) { const char *data = v7_to_string(v7, &arg1, &len); mg_send(c, data, len); } return v7_create_number(len); } enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7, const char *init_file_name) { v7_val_t v; m->v7 = v7; v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js); return v7_exec_file(v7, init_file_name, &v); } #endif void mg_mgr_free(struct mg_mgr *m) { struct mg_connection *conn, *tmp_conn; DBG(("%p", m)); if (m == NULL) return; /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */ mg_mgr_poll(m, 0); #ifndef MG_DISABLE_SOCKETPAIR if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]); if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]); #endif m->ctl[0] = m->ctl[1] = INVALID_SOCKET; for (conn = m->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; mg_close_conn(conn); } mg_ev_mgr_free(m); } int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int len; if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_send(nc, buf, len); } if (buf != mem && buf != NULL) { MG_FREE(buf); /* LCOV_EXCL_LINE */ } /* LCOV_EXCL_LINE */ return len; } int mg_printf(struct mg_connection *conn, const char *fmt, ...) { int len; va_list ap; va_start(ap, fmt); len = mg_vprintf(conn, fmt, ap); va_end(ap); return len; } #ifndef MG_DISABLE_SYNC_RESOLVER /* TODO(lsm): use non-blocking resolver */ static int mg_resolve2(const char *host, struct in_addr *ina) { #ifdef MG_ENABLE_GETADDRINFO int rv = 0; struct addrinfo hints, *servinfo, *p; struct sockaddr_in *h = NULL; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) { DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno))); return 0; } for (p = servinfo; p != NULL; p = p->ai_next) { memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *)); memcpy(ina, &h->sin_addr, sizeof(ina)); } freeaddrinfo(servinfo); return 1; #else struct hostent *he; if ((he = gethostbyname(host)) == NULL) { DBG(("gethostbyname(%s) failed: %s", host, strerror(errno))); } else { memcpy(ina, he->h_addr_list[0], sizeof(*ina)); return 1; } return 0; #endif /* MG_ENABLE_GETADDRINFO */ } int mg_resolve(const char *host, char *buf, size_t n) { struct in_addr ad; return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0; } #endif /* MG_DISABLE_SYNC_RESOLVER */ MG_INTERNAL struct mg_connection *mg_create_connection( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts) { struct mg_connection *conn; if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) { conn->sock = INVALID_SOCKET; conn->handler = callback; conn->mgr = mgr; conn->last_io_time = time(NULL); conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; conn->user_data = opts.user_data; /* * SIZE_MAX is defined as a long long constant in * system headers on some platforms and so it * doesn't compile with pedantic ansi flags. */ conn->recv_mbuf_limit = ~0; } else { MG_SET_PTRPTR(opts.error_string, "failed create connection"); } return conn; } /* * Address format: [PROTO://][HOST]:PORT * * HOST could be IPv4/IPv6 address or a host name. * `host` is a destination buffer to hold parsed HOST part. Shoud be at least * MG_MAX_HOST_LEN bytes long. * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM * * Return: * -1 on parse error * 0 if HOST needs DNS lookup * >0 length of the address string */ MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len) { unsigned int a, b, c, d, port = 0; int ch, len = 0; #ifdef MG_ENABLE_IPV6 char buf[100]; #endif /* * MacOS needs that. If we do not zero it, subsequent bind() will fail. * Also, all-zeroes in the socket address means binding to all addresses * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */ memset(sa, 0, sizeof(*sa)); sa->sin.sin_family = AF_INET; *proto = SOCK_STREAM; if (strncmp(str, "udp://", 6) == 0) { str += 6; *proto = SOCK_DGRAM; } else if (strncmp(str, "tcp://", 6) == 0) { str += 6; } if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */ sa->sin.sin_addr.s_addr = htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d); sa->sin.sin_port = htons((uint16_t) port); #ifdef MG_ENABLE_IPV6 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 && inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) { /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */ sa->sin6.sin6_family = AF_INET6; sa->sin.sin_port = htons((uint16_t) port); #endif #ifndef MG_DISABLE_RESOLVER } else if (strlen(str) < host_len && sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) { sa->sin.sin_port = htons((uint16_t) port); if (mg_resolve_from_hosts_file(host, sa) != 0) { return 0; } #endif } else if (sscanf(str, ":%u%n", &port, &len) == 1 || sscanf(str, "%u%n", &port, &len) == 1) { /* If only port is specified, bind to IPv4, INADDR_ANY */ sa->sin.sin_port = htons((uint16_t) port); } else { return -1; } ch = str[len]; /* Character that follows the address */ return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1; } #ifdef MG_ENABLE_SSL /* * Certificate generation script is at * https://github.com/cesanta/mongoose/blob/master/scripts/generate_ssl_certificates.sh */ #ifndef MG_DISABLE_PFS /* * Cipher suite options used for TLS negotiation. * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations */ static const char mg_s_cipher_list[] = #if defined(MG_SSL_CRYPTO_MODERN) "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:" "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK" #elif defined(MG_SSL_CRYPTO_OLD) "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:" "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:" "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" #else /* Default - intermediate. */ "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:" "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" #endif ; /* * Default DH params for PFS cipher negotiation. This is a 2048-bit group. * Will be used if none are provided by the user in the certificate file. */ static const char mg_s_default_dh_params[] = "\ -----BEGIN DH PARAMETERS-----\n\ MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\ Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\ +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\ ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\ wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\ 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\ -----END DH PARAMETERS-----\n"; #endif static int mg_use_ca_cert(SSL_CTX *ctx, const char *cert) { if (ctx == NULL) { return -1; } else if (cert == NULL || cert[0] == '\0') { return 0; } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2; } static int mg_use_cert(SSL_CTX *ctx, const char *pem_file) { if (ctx == NULL) { return -1; } else if (pem_file == NULL || pem_file[0] == '\0') { return 0; } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 || SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) { return -2; } else { #ifndef MG_DISABLE_PFS BIO *bio = NULL; DH *dh = NULL; /* Try to read DH parameters from the cert/key file. */ bio = BIO_new_file(pem_file, "r"); if (bio != NULL) { dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); } /* * If there are no DH params in the file, fall back to hard-coded ones. * Not ideal, but better than nothing. */ if (dh == NULL) { bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1); dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); } if (dh != NULL) { SSL_CTX_set_tmp_dh(ctx, dh); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); DH_free(dh); } #endif SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); SSL_CTX_use_certificate_chain_file(ctx, pem_file); return 0; } } /* * Turn the connection into SSL mode. * `cert` is the certificate file in PEM format. For listening connections, * certificate file must contain private key and server certificate, * concatenated. It may also contain DH params - these will be used for more * secure key exchange. `ca_cert` is a certificate authority (CA) PEM file, and * it is optional (can be set to NULL). If `ca_cert` is non-NULL, then * the connection is so-called two-way-SSL: other peer's certificate is * checked against the `ca_cert`. * * Handy OpenSSL command to generate test self-signed certificate: * * openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 999 * * Return NULL on success, or error message on failure. */ const char *mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert) { const char *result = NULL; if ((nc->flags & MG_F_LISTENING) && (nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { result = "SSL_CTX_new() failed"; } else if (!(nc->flags & MG_F_LISTENING) && (nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) { result = "SSL_CTX_new() failed"; } else if (mg_use_cert(nc->ssl_ctx, cert) != 0) { result = "Invalid ssl cert"; } else if (mg_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) { result = "Invalid CA cert"; } else if (!(nc->flags & MG_F_LISTENING) && (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) { result = "SSL_new() failed"; } else if (!(nc->flags & MG_F_LISTENING) && nc->sock != INVALID_SOCKET) { /* * Socket is open here only if we are connecting to IP address * and does not open if we are connecting using async DNS resolver */ SSL_set_fd(nc->ssl, nc->sock); } /* TODO(rojer): remove when krypton exposes this function, even a dummy one */ #ifdef OPENSSL_VERSION_NUMBER SSL_CTX_set_cipher_list(nc->ssl_ctx, mg_s_cipher_list); #endif return result; } static int mg_ssl_err(struct mg_connection *conn, int res) { int ssl_err = SSL_get_error(conn->ssl, res); if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= MG_F_WANT_READ; if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= MG_F_WANT_WRITE; return ssl_err; } #endif /* MG_ENABLE_SSL */ struct mg_connection *mg_if_accept_tcp_cb(struct mg_connection *lc, union socket_address *sa, size_t sa_len) { struct mg_add_sock_opts opts; struct mg_connection *nc; (void) sa_len; memset(&opts, 0, sizeof(opts)); nc = mg_create_connection(lc->mgr, lc->handler, opts); if (nc == NULL) return NULL; nc->listener = lc; nc->proto_data = lc->proto_data; nc->proto_handler = lc->proto_handler; nc->user_data = lc->user_data; nc->recv_mbuf_limit = lc->recv_mbuf_limit; nc->sa = *sa; mg_add_conn(nc->mgr, nc); if (nc->ssl == NULL) { /* For non-SSL connections deliver MG_EV_ACCEPT right away. */ mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa); } DBG(("%p %p %d %d, %p %p", lc, nc, nc->sock, (int) nc->flags, lc->ssl_ctx, nc->ssl)); return nc; } static size_t recv_avail_size(struct mg_connection *conn, size_t max) { size_t avail; if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0; avail = conn->recv_mbuf_limit - conn->recv_mbuf.len; return avail > max ? max : avail; } #ifdef MG_ENABLE_SSL static void mg_ssl_begin(struct mg_connection *nc) { int server_side = nc->listener != NULL; int res = server_side ? SSL_accept(nc->ssl) : SSL_connect(nc->ssl); DBG(("%p %d res %d %d %d", nc, server_side, res, errno, mg_ssl_err(nc, res))); if (res == 1) { nc->flags |= MG_F_SSL_HANDSHAKE_DONE; nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); if (server_side) { union socket_address sa; socklen_t sa_len = sizeof(sa); /* In case port was set to 0, get the real port number */ (void) getsockname(nc->sock, &sa.sa, &sa_len); mg_call(nc, NULL, MG_EV_ACCEPT, &sa); } else { int err = 0; mg_call(nc, NULL, MG_EV_CONNECT, &err); } } else { int ssl_err = mg_ssl_err(nc, res); if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; if (!server_side) { int err = 0; mg_call(nc, NULL, MG_EV_CONNECT, &err); } } } } #endif /* MG_ENABLE_SSL */ void mg_send(struct mg_connection *nc, const void *buf, int len) { nc->last_io_time = time(NULL); if (nc->flags & MG_F_UDP) { mg_if_udp_send(nc, buf, len); } else { mg_if_tcp_send(nc, buf, len); } #if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP) if (nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_SEND); } #endif } void mg_if_sent_cb(struct mg_connection *nc, int num_sent) { if (num_sent < 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } mg_call(nc, NULL, MG_EV_SEND, &num_sent); } static void mg_recv_common(struct mg_connection *nc, void *buf, int len) { DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len)); if (nc->flags & MG_F_CLOSE_IMMEDIATELY) { DBG(("%p discarded %d bytes", nc, len)); /* * This connection will not survive next poll. Do not deliver events, * send data to /dev/null without acking. */ MG_FREE(buf); return; } nc->last_io_time = time(NULL); if (nc->recv_mbuf.len == 0) { /* Adopt buf as recv_mbuf's backing store. */ mbuf_free(&nc->recv_mbuf); nc->recv_mbuf.buf = (char *) buf; nc->recv_mbuf.size = nc->recv_mbuf.len = len; } else { size_t avail = recv_avail_size(nc, len); len = avail; mbuf_append(&nc->recv_mbuf, buf, len); MG_FREE(buf); } mg_call(nc, NULL, MG_EV_RECV, &len); } void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len) { mg_recv_common(nc, buf, len); mg_if_recved(nc, len); } void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, union socket_address *sa, size_t sa_len) { assert(nc->flags & MG_F_UDP); DBG(("%p %u", nc, (unsigned int) len)); if (nc->flags & MG_F_LISTENING) { struct mg_connection *lc = nc; /* * Do we have an existing connection for this source? * This is very inefficient for long connection lists. */ for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) { if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0) break; } if (nc == NULL) { struct mg_add_sock_opts opts; memset(&opts, 0, sizeof(opts)); nc = mg_create_connection(lc->mgr, lc->handler, opts); } if (nc != NULL) { nc->sock = lc->sock; nc->listener = lc; nc->sa = *sa; nc->proto_data = lc->proto_data; nc->proto_handler = lc->proto_handler; nc->user_data = lc->user_data; nc->recv_mbuf_limit = lc->recv_mbuf_limit; nc->flags = MG_F_UDP; mg_add_conn(lc->mgr, nc); mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa); } else { DBG(("OOM")); } } if (nc != NULL) { mg_recv_common(nc, buf, len); } else { /* Drop on the floor. */ MG_FREE(buf); } mg_if_recved(nc, len); } /* * Schedules an async connect for a resolved address and proto. * Called from two places: `mg_connect_opt()` and from async resolver. * When called from the async resolver, it must trigger `MG_EV_CONNECT` event * with a failure flag to indicate connection failure. */ MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa) { DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp", inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); nc->flags |= MG_F_CONNECTING; if (proto == SOCK_DGRAM) { mg_if_connect_udp(nc); } else { mg_if_connect_tcp(nc, sa); } mg_add_conn(nc->mgr, nc); return nc; } void mg_if_connect_cb(struct mg_connection *nc, int err) { DBG(("%p connect, err=%d", nc, err)); nc->flags &= ~MG_F_CONNECTING; if (err == 0) { #ifdef MG_ENABLE_SSL if (nc->ssl != NULL) { SSL_set_fd(nc->ssl, nc->sock); mg_ssl_begin(nc); return; } #endif } else { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } mg_call(nc, NULL, MG_EV_CONNECT, &err); } #ifndef MG_DISABLE_RESOLVER /* * Callback for the async resolver on mg_connect_opt() call. * Main task of this function is to trigger MG_EV_CONNECT event with * either failure (and dealloc the connection) * or success (and proceed with connect() */ static void resolve_cb(struct mg_dns_message *msg, void *data) { struct mg_connection *nc = (struct mg_connection *) data; int i; int failure = -1; if (msg != NULL) { /* * Take the first DNS A answer and run... */ for (i = 0; i < msg->num_answers; i++) { if (msg->answers[i].rtype == MG_DNS_A_RECORD) { /* * Async resolver guarantees that there is at least one answer. * TODO(lsm): handle IPv6 answers too */ mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr, 4); mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM, &nc->sa); return; } } } /* * If we get there was no MG_DNS_A_RECORD in the answer */ mg_call(nc, NULL, MG_EV_CONNECT, &failure); mg_call(nc, NULL, MG_EV_CLOSE, NULL); mg_destroy_conn(nc); } #endif struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, mg_event_handler_t callback) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_opt(mgr, address, callback, opts); } struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, mg_event_handler_t callback, struct mg_connect_opts opts) { struct mg_connection *nc = NULL; int proto, rc; struct mg_add_sock_opts add_sock_opts; char host[MG_MAX_HOST_LEN]; MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) { return NULL; } else if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) < 0) { /* Address is malformed */ MG_SET_PTRPTR(opts.error_string, "cannot parse address"); mg_destroy_conn(nc); return NULL; } nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0; nc->user_data = opts.user_data; if (rc == 0) { #ifndef MG_DISABLE_RESOLVER /* * DNS resolution is required for host. * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb() */ if (mg_resolve_async(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc) != 0) { MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup"); mg_destroy_conn(nc); return NULL; } return nc; #else MG_SET_PTRPTR(opts.error_string, "Resolver is disabled"); mg_destroy_conn(nc); return NULL; #endif } else { /* Address is parsed and resolved to IP. proceed with connect() */ return mg_do_connect(nc, proto, &nc->sa); } } struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address, mg_event_handler_t event_handler) { struct mg_bind_opts opts; memset(&opts, 0, sizeof(opts)); return mg_bind_opt(srv, address, event_handler, opts); } struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, mg_event_handler_t callback, struct mg_bind_opts opts) { union socket_address sa; struct mg_connection *nc = NULL; int proto, rc; struct mg_add_sock_opts add_sock_opts; char host[MG_MAX_HOST_LEN]; MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) { MG_SET_PTRPTR(opts.error_string, "cannot parse address"); return NULL; } nc = mg_create_connection(mgr, callback, add_sock_opts); if (nc == NULL) { return NULL; } nc->sa = sa; nc->flags |= MG_F_LISTENING; if (proto == SOCK_DGRAM) { nc->flags |= MG_F_UDP; rc = mg_if_listen_udp(nc, &nc->sa); } else { rc = mg_if_listen_tcp(nc, &nc->sa); } if (rc != 0) { DBG(("Failed to open listener: %d", rc)); MG_SET_PTRPTR(opts.error_string, "failed to open listener"); mg_destroy_conn(nc); return NULL; } mg_add_conn(nc->mgr, nc); return nc; } struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) { return conn == NULL ? s->active_connections : conn->next; } #ifndef MG_DISABLE_SOCKETPAIR void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, size_t len) { struct ctl_msg ctl_msg; /* * Mongoose manager has a socketpair, `struct mg_mgr::ctl`, * where `mg_broadcast()` pushes the message. * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls * specified callback for each connection. Thus the callback function executes * in event manager thread. */ if (mgr->ctl[0] != INVALID_SOCKET && data != NULL && len < sizeof(ctl_msg.message)) { size_t dummy; ctl_msg.callback = cb; memcpy(ctl_msg.message, data, len); dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg, offsetof(struct ctl_msg, message) + len, 0); dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0); (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ } } #endif /* MG_DISABLE_SOCKETPAIR */ static int isbyte(int n) { return n >= 0 && n <= 255; } static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { int n, a, b, c, d, slash = 32, len = 0; if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 && slash < 33) { len = n; *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d; *mask = slash ? 0xffffffffU << (32 - slash) : 0; } return len; } int mg_check_ip_acl(const char *acl, uint32_t remote_ip) { int allowed, flag; uint32_t net, mask; struct mg_str vec; /* If any ACL is set, deny by default */ allowed = (acl == NULL || *acl == '\0') ? '+' : '-'; while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) { flag = vec.p[0]; if ((flag != '+' && flag != '-') || parse_net(&vec.p[1], &net, &mask) == 0) { return -1; } if (net == (remote_ip & mask)) { allowed = flag; } } return allowed == '+'; } /* Move data from one connection to another */ void mg_forward(struct mg_connection *from, struct mg_connection *to) { mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len); mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len); } #ifdef NS_MODULE_LINES #line 1 "src/net_if_socket.c" /**/ #endif #ifndef MG_DISABLE_SOCKET_IF /* Amalgamated: #include "internal.h" */ #define MG_TCP_RECV_BUFFER_SIZE 1024 #define MG_UDP_RECV_BUFFER_SIZE 1500 static sock_t mg_open_listening_socket(union socket_address *sa, int proto); static void mg_sock_set(struct mg_connection *nc, sock_t sock); void mg_set_non_blocking_mode(sock_t sock) { #ifdef _WIN32 unsigned long on = 1; ioctlsocket(sock, FIONBIO, &on); #elif defined(MG_CC3200) cc3200_set_non_blocking_mode(sock); #else int flags = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, flags | O_NONBLOCK); #endif } int mg_is_error(int n) { #ifdef MG_CC3200 DBG(("n = %d, errno = %d", n, errno)); if (n < 0) errno = n; #endif return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS && errno != EAGAIN && errno != EWOULDBLOCK #ifdef MG_CC3200 && errno != SL_EALREADY #endif #ifdef _WIN32 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK #endif ); } void mg_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { int rc; nc->sock = socket(AF_INET, SOCK_STREAM, 0); if (nc->sock < 0) { nc->sock = INVALID_SOCKET; nc->err = errno ? errno : 1; return; } #if !defined(MG_CC3200) && !defined(MG_ESP8266) mg_set_non_blocking_mode(nc->sock); #endif rc = connect(nc->sock, &sa->sa, sizeof(sa->sin)); nc->err = mg_is_error(rc) ? errno : 0; DBG(("%p sock %d err %d", nc, nc->sock, nc->err)); } void mg_if_connect_udp(struct mg_connection *nc) { nc->sock = socket(AF_INET, SOCK_DGRAM, 0); if (nc->sock < 0) { nc->sock = INVALID_SOCKET; nc->err = errno ? errno : 1; return; } nc->err = 0; } int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM); if (sock < 0) return (errno ? errno : 1); mg_sock_set(nc, sock); return 0; } int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM); if (sock < 0) return (errno ? errno : 1); mg_sock_set(nc, sock); return 0; } void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { mbuf_append(&nc->send_mbuf, buf, len); } void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { DBG(("%p %d %d", nc, (int) len, (int) nc->send_mbuf.len)); mbuf_append(&nc->send_mbuf, buf, len); } void mg_if_recved(struct mg_connection *nc, size_t len) { (void) nc; (void) len; } void mg_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; #ifdef MG_ENABLE_SSL if (nc->ssl != NULL) SSL_free(nc->ssl); if (nc->ssl_ctx != NULL) SSL_CTX_free(nc->ssl_ctx); #endif if (!(nc->flags & MG_F_UDP)) { closesocket(nc->sock); } else { /* Only close outgoing UDP sockets or listeners. */ if (nc->listener == NULL) closesocket(nc->sock); } /* * avoid users accidentally double close a socket * because it can lead to difficult to debug situations. * It would happen only if reusing a destroyed mg_connection * but it's not always possible to run the code through an * address sanitizer. */ nc->sock = INVALID_SOCKET; } static void mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; union socket_address sa; socklen_t sa_len = sizeof(sa); /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */ sock_t sock = accept(lc->sock, &sa.sa, &sa_len); if (sock < 0) { DBG(("%p: failed to accept: %d", lc, errno)); return; } nc = mg_if_accept_tcp_cb(lc, &sa, sa_len); if (nc == NULL) { closesocket(sock); return; } mg_sock_set(nc, sock); #ifdef MG_ENABLE_SSL if (lc->ssl_ctx != NULL) { nc->ssl = SSL_new(lc->ssl_ctx); if (nc->ssl == NULL || SSL_set_fd(nc->ssl, sock) != 1) { DBG(("SSL error")); mg_close_conn(nc); } } #endif } /* 'sa' must be an initialized address to bind to */ static sock_t mg_open_listening_socket(union socket_address *sa, int proto) { socklen_t sa_len = (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); sock_t sock = INVALID_SOCKET; #if !defined(MG_CC3200) && !defined(MG_LWIP) int on = 1; #endif if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET && #if !defined(MG_CC3200) && \ !defined(MG_LWIP) /* CC3200 and LWIP don't support either */ #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */ !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on, sizeof(on)) && #endif #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE) /* * SO_RESUSEADDR is not enabled on Windows because the semantics of * SO_REUSEADDR on UNIX and Windows is different. On Windows, * SO_REUSEADDR allows to bind a socket to a port without error even if * the port is already open by another program. This is not the behavior * SO_REUSEADDR was designed for, and leads to hard-to-track failure * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless * SO_EXCLUSIVEADDRUSE is supported and set on a socket. */ !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) && #endif #endif /* !MG_CC3200 && !MG_LWIP */ !bind(sock, &sa->sa, sa_len) && (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) { #if !defined(MG_CC3200) && !defined(MG_LWIP) /* TODO(rojer): Fix this. */ mg_set_non_blocking_mode(sock); /* In case port was set to 0, get the real port number */ (void) getsockname(sock, &sa->sa, &sa_len); #endif } else if (sock != INVALID_SOCKET) { closesocket(sock); sock = INVALID_SOCKET; } return sock; } static void mg_write_to_socket(struct mg_connection *nc) { struct mbuf *io = &nc->send_mbuf; int n = 0; #ifdef MG_LWIP /* With LWIP we don't know if the socket is ready */ if (io->len == 0) return; #endif assert(io->len > 0); if (nc->flags & MG_F_UDP) { int n = sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); if (n > 0) { mbuf_remove(io, n); } mg_if_sent_cb(nc, n); return; } #ifdef MG_ENABLE_SSL if (nc->ssl != NULL) { if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { n = SSL_write(nc->ssl, io->buf, io->len); if (n <= 0) { int ssl_err = mg_ssl_err(nc, n); if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) { return; /* Call us again */ } else { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { /* Successful SSL operation, clear off SSL wait flags */ nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); } } else { mg_ssl_begin(nc); return; } } else #endif { n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0); } DBG(("%p %d bytes -> %d", nc, n, nc->sock)); if (n > 0) { mbuf_remove(io, n); } mg_if_sent_cb(nc, n); } static void mg_read_from_socket(struct mg_connection *conn) { int n = 0; char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE); if (buf == NULL) { DBG(("OOM")); return; } #ifdef MG_ENABLE_SSL if (conn->ssl != NULL) { if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) { /* SSL library may have more bytes ready to read then we ask to read. * Therefore, read in a loop until we read everything. Without the loop, * we skip to the next select() cycle which can just timeout. */ while ((n = SSL_read(conn->ssl, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) { DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock)); mg_if_recv_tcp_cb(conn, buf, n); buf = NULL; if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break; /* buf has been freed, we need a new one. */ buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE); if (buf == NULL) break; } MG_FREE(buf); mg_ssl_err(conn, n); } else { MG_FREE(buf); mg_ssl_begin(conn); return; } } else #endif { n = (int) MG_RECV_FUNC(conn->sock, buf, recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0); if (n > 0) { DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock)); mg_if_recv_tcp_cb(conn, buf, n); } else { MG_FREE(buf); } if (mg_is_error(n)) { conn->flags |= MG_F_CLOSE_IMMEDIATELY; } } } static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa, socklen_t *sa_len, char **buf) { int n; *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE); if (*buf == NULL) { DBG(("Out of memory")); return -ENOMEM; } n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len); if (n <= 0) { DBG(("%p recvfrom: %s", nc, strerror(errno))); MG_FREE(*buf); } return n; } static void mg_handle_udp_read(struct mg_connection *nc) { char *buf = NULL; union socket_address sa; socklen_t sa_len = sizeof(sa); int n = mg_recvfrom(nc, &sa, &sa_len, &buf); DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len); } #define _MG_F_FD_CAN_READ 1 #define _MG_F_FD_CAN_WRITE 1 << 1 #define _MG_F_FD_ERROR 1 << 2 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, time_t now) { DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); if (nc->flags & MG_F_CONNECTING) { if (fd_flags != 0) { int err = 0; #if !defined(MG_CC3200) && !defined(MG_ESP8266) if (!(nc->flags & MG_F_UDP)) { socklen_t len = sizeof(err); int ret = getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len); if (ret != 0) err = 1; } #else /* On CC3200 and ESP8266 we use blocking connect. If we got as far as * this, it means connect() was successful. * TODO(rojer): Figure out why it fails where blocking succeeds. */ #endif mg_if_connect_cb(nc, err); } else if (nc->err != 0) { mg_if_connect_cb(nc, nc->err); } } if (fd_flags & _MG_F_FD_CAN_READ) { if (nc->flags & MG_F_UDP) { mg_handle_udp_read(nc); } else { if (nc->flags & MG_F_LISTENING) { /* * We're not looping here, and accepting just one connection at * a time. The reason is that eCos does not respect non-blocking * flag on a listening socket and hangs in a loop. */ if (fd_flags & _MG_F_FD_CAN_READ) mg_accept_conn(nc); return; } else { mg_read_from_socket(nc); } } if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return; } if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) { mg_write_to_socket(nc); } if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) { mg_if_poll(nc, now); } DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } #ifndef MG_DISABLE_SOCKETPAIR static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) { struct ctl_msg ctl_msg; int len = (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0); size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0); (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) { struct mg_connection *nc; for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message); } } } #endif struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock, mg_event_handler_t callback) { struct mg_add_sock_opts opts; memset(&opts, 0, sizeof(opts)); return mg_add_sock_opt(s, sock, callback, opts); } struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock, mg_event_handler_t callback, struct mg_add_sock_opts opts) { struct mg_connection *nc = mg_create_connection(s, callback, opts); if (nc != NULL) { mg_sock_set(nc, sock); mg_add_conn(nc->mgr, nc); } return nc; } /* Associate a socket to a connection. */ static void mg_sock_set(struct mg_connection *nc, sock_t sock) { mg_set_non_blocking_mode(sock); mg_set_close_on_exec(sock); nc->sock = sock; DBG(("%p %d", nc, sock)); } #if MG_MGR_EV_MGR == 1 /* epoll() */ #ifndef MG_EPOLL_MAX_EVENTS #define MG_EPOLL_MAX_EVENTS 100 #endif #define _MG_EPF_EV_EPOLLIN (1 << 0) #define _MG_EPF_EV_EPOLLOUT (1 << 1) #define _MG_EPF_NO_POLL (1 << 2) uint32_t mg_epf_to_evflags(unsigned int epf) { uint32_t result = 0; if (epf & _MG_EPF_EV_EPOLLIN) result |= EPOLLIN; if (epf & _MG_EPF_EV_EPOLLOUT) result |= EPOLLOUT; return result; } void mg_ev_mgr_epoll_set_flags(const struct mg_connection *nc, struct epoll_event *ev) { /* NOTE: EPOLLERR and EPOLLHUP are always enabled. */ ev->events = 0; if ((nc->flags & MG_F_LISTENING) || nc->recv_mbuf.len < nc->recv_mbuf_limit) { ev->events |= EPOLLIN; } if ((nc->flags & MG_F_CONNECTING) || (nc->send_mbuf.len > 0)) { ev->events |= EPOLLOUT; } } void mg_ev_mgr_epoll_ctl(struct mg_connection *nc, int op) { int epoll_fd = (intptr_t) nc->mgr->mgr_data; struct epoll_event ev; assert(op == EPOLL_CTL_ADD || op == EPOLL_CTL_MOD || EPOLL_CTL_DEL); DBG(("%p %d %d", nc, nc->sock, op)); if (nc->sock == INVALID_SOCKET) return; if (op != EPOLL_CTL_DEL) { mg_ev_mgr_epoll_set_flags(nc, &ev); if (op == EPOLL_CTL_MOD) { uint32_t old_ev_flags = mg_epf_to_evflags((intptr_t) nc->mgr_data); if (ev.events == old_ev_flags) return; } ev.data.ptr = nc; } if (epoll_ctl(epoll_fd, op, nc->sock, &ev) != 0) { perror("epoll_ctl"); abort(); } } void mg_ev_mgr_init(struct mg_mgr *mgr) { int epoll_fd; DBG(("%p using epoll()", mgr)); #ifndef MG_DISABLE_SOCKETPAIR do { mg_socketpair(mgr->ctl, SOCK_DGRAM); } while (mgr->ctl[0] == INVALID_SOCKET); #endif epoll_fd = epoll_create(MG_EPOLL_MAX_EVENTS /* unused but required */); if (epoll_fd < 0) { perror("epoll_ctl"); abort(); } mgr->mgr_data = (void *) ((intptr_t) epoll_fd); if (mgr->ctl[1] != INVALID_SOCKET) { struct epoll_event ev; ev.events = EPOLLIN; ev.data.ptr = NULL; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, mgr->ctl[1], &ev) != 0) { perror("epoll_ctl"); abort(); } } } void mg_ev_mgr_free(struct mg_mgr *mgr) { int epoll_fd = (intptr_t) mgr->mgr_data; close(epoll_fd); } void mg_ev_mgr_add_conn(struct mg_connection *nc) { if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_ADD); } } void mg_ev_mgr_remove_conn(struct mg_connection *nc) { if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_DEL); } } time_t mg_mgr_poll(struct mg_mgr *mgr, int timeout_ms) { int epoll_fd = (intptr_t) mgr->mgr_data; struct epoll_event events[MG_EPOLL_MAX_EVENTS]; struct mg_connection *nc, *next; int num_ev, fd_flags; time_t now; num_ev = epoll_wait(epoll_fd, events, MG_EPOLL_MAX_EVENTS, timeout_ms); now = time(NULL); DBG(("epoll_wait @ %ld num_ev=%d", (long) now, num_ev)); while (num_ev-- > 0) { intptr_t epf; struct epoll_event *ev = events + num_ev; nc = (struct mg_connection *) ev->data.ptr; if (nc == NULL) { mg_mgr_handle_ctl_sock(mgr); continue; } fd_flags = ((ev->events & (EPOLLIN | EPOLLHUP)) ? _MG_F_FD_CAN_READ : 0) | ((ev->events & (EPOLLOUT)) ? _MG_F_FD_CAN_WRITE : 0) | ((ev->events & (EPOLLERR)) ? _MG_F_FD_ERROR : 0); mg_mgr_handle_conn(nc, fd_flags, now); epf = (intptr_t) nc->mgr_data; epf ^= _MG_EPF_NO_POLL; nc->mgr_data = (void *) epf; } for (nc = mgr->active_connections; nc != NULL; nc = next) { next = nc->next; if (!(((intptr_t) nc->mgr_data) & _MG_EPF_NO_POLL)) { mg_mgr_handle_conn(nc, 0, now); } else { intptr_t epf = (intptr_t) nc->mgr_data; epf ^= _MG_EPF_NO_POLL; nc->mgr_data = (void *) epf; } if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { mg_close_conn(nc); } else { if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_MOD); } else { /* This is a kludge, but... */ if (nc->send_mbuf.len > 0) { mg_mgr_handle_conn(nc, _MG_F_FD_CAN_WRITE, now); } } } } return now; } #else /* select() */ void mg_ev_mgr_init(struct mg_mgr *mgr) { (void) mgr; DBG(("%p using select()", mgr)); #ifndef MG_DISABLE_SOCKETPAIR do { mg_socketpair(mgr->ctl, SOCK_DGRAM); } while (mgr->ctl[0] == INVALID_SOCKET); #endif } void mg_ev_mgr_free(struct mg_mgr *mgr) { (void) mgr; } void mg_ev_mgr_add_conn(struct mg_connection *nc) { (void) nc; } void mg_ev_mgr_remove_conn(struct mg_connection *nc) { (void) nc; } void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) { if (sock != INVALID_SOCKET) { FD_SET(sock, set); if (*max_fd == INVALID_SOCKET || sock > *max_fd) { *max_fd = sock; } } } time_t mg_mgr_poll(struct mg_mgr *mgr, int milli) { time_t now = time(NULL); struct mg_connection *nc, *tmp; struct timeval tv; fd_set read_set, write_set, err_set; sock_t max_fd = INVALID_SOCKET; int num_fds, num_selected; FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&err_set); mg_add_to_set(mgr->ctl[1], &read_set, &max_fd); for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->sock == INVALID_SOCKET) { mg_mgr_handle_conn(nc, 0, now); continue; } num_fds++; if (!(nc->flags & MG_F_WANT_WRITE) && nc->recv_mbuf.len < nc->recv_mbuf_limit && (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { mg_add_to_set(nc->sock, &read_set, &max_fd); } if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { mg_add_to_set(nc->sock, &write_set, &max_fd); mg_add_to_set(nc->sock, &err_set, &max_fd); } } tv.tv_sec = milli / 1000; tv.tv_usec = (milli % 1000) * 1000; num_selected = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); now = time(NULL); DBG(("select @ %ld num_ev=%d of %d", (long) now, num_selected, num_fds)); #ifndef MG_DISABLE_SOCKETPAIR if (num_selected > 0 && mgr->ctl[1] != INVALID_SOCKET && FD_ISSET(mgr->ctl[1], &read_set)) { mg_mgr_handle_ctl_sock(mgr); } #endif for (nc = mgr->active_connections; nc != NULL; nc = tmp) { int fd_flags = 0; if (num_selected > 0) { fd_flags = (FD_ISSET(nc->sock, &read_set) ? _MG_F_FD_CAN_READ : 0) | (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); } #ifdef MG_CC3200 // CC3200 does not report UDP sockets as writeable. if (nc->flags & MG_F_UDP && (nc->send_mbuf.len > 0 || nc->flags & MG_F_CONNECTING)) { fd_flags |= _MG_F_FD_CAN_WRITE; } #endif #ifdef MG_LWIP /* With LWIP socket emulation layer, we don't get write events */ fd_flags |= _MG_F_FD_CAN_WRITE; #endif tmp = nc->next; mg_mgr_handle_conn(nc, fd_flags, now); } for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { mg_close_conn(nc); } } return now; } #endif #ifndef MG_DISABLE_SOCKETPAIR int mg_socketpair(sock_t sp[2], int sock_type) { union socket_address sa; sock_t sock; socklen_t len = sizeof(sa.sin); int ret = 0; sock = sp[0] = sp[1] = INVALID_SOCKET; (void) memset(&sa, 0, sizeof(sa)); sa.sin.sin_family = AF_INET; sa.sin.sin_port = htons(0); sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */ if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { } else if (bind(sock, &sa.sa, len) != 0) { } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) { } else if (getsockname(sock, &sa.sa, &len) != 0) { } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { } else if (connect(sp[0], &sa.sa, len) != 0) { } else if (sock_type == SOCK_DGRAM && (getsockname(sp[0], &sa.sa, &len) != 0 || connect(sock, &sa.sa, len) != 0)) { } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : accept(sock, &sa.sa, &len))) == INVALID_SOCKET) { } else { mg_set_close_on_exec(sp[0]); mg_set_close_on_exec(sp[1]); if (sock_type == SOCK_STREAM) closesocket(sock); ret = 1; } if (!ret) { if (sp[0] != INVALID_SOCKET) closesocket(sp[0]); if (sp[1] != INVALID_SOCKET) closesocket(sp[1]); if (sock != INVALID_SOCKET) closesocket(sock); sock = sp[0] = sp[1] = INVALID_SOCKET; } return ret; } #endif /* MG_DISABLE_SOCKETPAIR */ static void mg_sock_get_addr(sock_t sock, int remote, union socket_address *sa) { #ifndef MG_CC3200 socklen_t slen = sizeof(sa); memset(sa, 0, sizeof(*sa)); if (remote) { getpeername(sock, &sa->sa, &slen); } else { getsockname(sock, &sa->sa, &slen); } #else memset(sa, 0, sizeof(*sa)); #endif } void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) { union socket_address sa; mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); mg_sock_addr_to_str(&sa, buf, len, flags); } void mg_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { mg_sock_get_addr(nc->sock, remote, sa); } #endif /* !MG_DISABLE_SOCKET_IF */ #ifdef NS_MODULE_LINES #line 1 "src/multithreading.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "internal.h" */ #ifdef MG_ENABLE_THREADS static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p); /* * This thread function executes user event handler. * It runs an event manager that has only one connection, until that * connection is alive. */ static void *per_connection_thread_function(void *param) { struct mg_connection *c = (struct mg_connection *) param; struct mg_mgr m; mg_mgr_init(&m, NULL); mg_add_conn(&m, c); while (m.active_connections != NULL) { mg_mgr_poll(&m, 1000); } mg_mgr_free(&m); return param; } static void link_conns(struct mg_connection *c1, struct mg_connection *c2) { c1->priv_2 = c2; c2->priv_2 = c1; } static void unlink_conns(struct mg_connection *c) { struct mg_connection *peer = (struct mg_connection *) c->priv_2; if (peer != NULL) { peer->flags |= MG_F_SEND_AND_CLOSE; peer->priv_2 = NULL; } c->priv_2 = NULL; } static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) { (void) p; if (ev == MG_EV_RECV && c->priv_2) { mg_forward(c, (struct mg_connection *) c->priv_2); } else if (ev == MG_EV_CLOSE) { unlink_conns(c); } } static void spawn_handling_thread(struct mg_connection *nc) { struct mg_mgr dummy; sock_t sp[2]; struct mg_connection *c[2]; /* * Create a socket pair, and wrap each socket into the connection with * dummy event manager. * c[0] stays in this thread, c[1] goes to another thread. */ mg_socketpair(sp, SOCK_STREAM); memset(&dummy, 0, sizeof(dummy)); c[0] = mg_add_sock(&dummy, sp[0], forwarder_ev_handler); c[1] = mg_add_sock(&dummy, sp[1], (mg_event_handler_t) nc->listener->priv_1); /* Interlink client connection with c[0] */ link_conns(c[0], nc); /* * Switch c[0] manager from the dummy one to the real one. c[1] manager * will be set in another thread, allocated on stack of that thread. */ mg_add_conn(nc->mgr, c[0]); /* * Dress c[1] as nc. * TODO(lsm): code in accept_conn() looks similar. Refactor. */ c[1]->listener = nc->listener; c[1]->proto_handler = nc->proto_handler; c[1]->proto_data = nc->proto_data; c[1]->user_data = nc->user_data; mg_start_thread(per_connection_thread_function, c[1]); } static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) { (void) p; if (ev == MG_EV_ACCEPT) { spawn_handling_thread(c); c->handler = forwarder_ev_handler; } } void mg_enable_multithreading(struct mg_connection *nc) { /* Wrap user event handler into our multithreaded_ev_handler */ nc->priv_1 = (void *) nc->handler; nc->handler = multithreaded_ev_handler; } #endif #ifdef NS_MODULE_LINES #line 1 "src/http.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef MG_DISABLE_HTTP /* Amalgamated: #include "internal.h" */ enum http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT, DATA_CGI }; struct proto_data_http { FILE *fp; /* Opened file. */ int64_t cl; /* Content-Length. How many bytes to send. */ int64_t sent; /* How many bytes have been already sent. */ int64_t body_len; /* How many bytes of chunked body was reassembled. */ struct mg_connection *cgi_nc; enum http_proto_data_type type; }; /* * This structure helps to create an environment for the spawned CGI program. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, * last element must be NULL. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0 * strings must reside in a contiguous buffer. The end of the buffer is * marked by two '\0' characters. * We satisfy both worlds: we create an envp array (which is vars), all * entries are actually pointers inside buf. */ struct cgi_env_block { struct mg_connection *nc; char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */ const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */ int len; /* Space taken */ int nvars; /* Number of variables in envp[] */ }; #define MIME_ENTRY(_ext, _type) \ { _ext, sizeof(_ext) - 1, _type } static const struct { const char *extension; size_t ext_len; const char *mime_type; } static_builtin_mime_types[] = { MIME_ENTRY("html", "text/html"), MIME_ENTRY("html", "text/html"), MIME_ENTRY("htm", "text/html"), MIME_ENTRY("shtm", "text/html"), MIME_ENTRY("shtml", "text/html"), MIME_ENTRY("css", "text/css"), MIME_ENTRY("js", "application/x-javascript"), MIME_ENTRY("ico", "image/x-icon"), MIME_ENTRY("gif", "image/gif"), MIME_ENTRY("jpg", "image/jpeg"), MIME_ENTRY("jpeg", "image/jpeg"), MIME_ENTRY("png", "image/png"), MIME_ENTRY("svg", "image/svg+xml"), MIME_ENTRY("txt", "text/plain"), MIME_ENTRY("torrent", "application/x-bittorrent"), MIME_ENTRY("wav", "audio/x-wav"), MIME_ENTRY("mp3", "audio/x-mp3"), MIME_ENTRY("mid", "audio/mid"), MIME_ENTRY("m3u", "audio/x-mpegurl"), MIME_ENTRY("ogg", "application/ogg"), MIME_ENTRY("ram", "audio/x-pn-realaudio"), MIME_ENTRY("xml", "text/xml"), MIME_ENTRY("ttf", "application/x-font-ttf"), MIME_ENTRY("json", "application/json"), MIME_ENTRY("xslt", "application/xml"), MIME_ENTRY("xsl", "application/xml"), MIME_ENTRY("ra", "audio/x-pn-realaudio"), MIME_ENTRY("doc", "application/msword"), MIME_ENTRY("exe", "application/octet-stream"), MIME_ENTRY("zip", "application/x-zip-compressed"), MIME_ENTRY("xls", "application/excel"), MIME_ENTRY("tgz", "application/x-tar-gz"), MIME_ENTRY("tar", "application/x-tar"), MIME_ENTRY("gz", "application/x-gunzip"), MIME_ENTRY("arj", "application/x-arj-compressed"), MIME_ENTRY("rar", "application/x-rar-compressed"), MIME_ENTRY("rtf", "application/rtf"), MIME_ENTRY("pdf", "application/pdf"), MIME_ENTRY("swf", "application/x-shockwave-flash"), MIME_ENTRY("mpg", "video/mpeg"), MIME_ENTRY("webm", "video/webm"), MIME_ENTRY("mpeg", "video/mpeg"), MIME_ENTRY("mov", "video/quicktime"), MIME_ENTRY("mp4", "video/mp4"), MIME_ENTRY("m4v", "video/x-m4v"), MIME_ENTRY("asf", "video/x-ms-asf"), MIME_ENTRY("avi", "video/x-msvideo"), MIME_ENTRY("bmp", "image/bmp"), {NULL, 0, NULL} }; #ifndef MG_DISABLE_FILESYSTEM #ifndef MG_DISABLE_DAV static int mg_mkdir(const char *path, uint32_t mode) { #ifndef _WIN32 return mkdir(path, mode); #else (void) mode; return _mkdir(path); #endif } #endif static struct mg_str get_mime_type(const char *path, const char *dflt, const struct mg_serve_http_opts *opts) { const char *ext, *overrides; size_t i, path_len; struct mg_str r, k, v; path_len = strlen(path); overrides = opts->custom_mime_types; while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) { ext = path + (path_len - k.len); if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) { return v; } } for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) { ext = path + (path_len - static_builtin_mime_types[i].ext_len); if (path_len > static_builtin_mime_types[i].ext_len && ext[-1] == '.' && mg_casecmp(ext, static_builtin_mime_types[i].extension) == 0) { r.p = static_builtin_mime_types[i].mime_type; r.len = strlen(r.p); return r; } } r.p = dflt; r.len = strlen(r.p); return r; } #endif /* * Check whether full request is buffered. Return: * -1 if request is malformed * 0 if request is not yet fully buffered * >0 actual request length, including last \r\n\r\n */ static int get_request_len(const char *s, int buf_len) { const unsigned char *buf = (unsigned char *) s; int i; for (i = 0; i < buf_len; i++) { if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { return -1; } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { return i + 2; } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && buf[i + 2] == '\n') { return i + 3; } } return 0; } static const char *parse_http_headers(const char *s, const char *end, int len, struct http_message *req) { int i; for (i = 0; i < (int) ARRAY_SIZE(req->header_names) - 1; i++) { struct mg_str *k = &req->header_names[i], *v = &req->header_values[i]; s = mg_skip(s, end, ": ", k); s = mg_skip(s, end, "\r\n", v); while (v->len > 0 && v->p[v->len - 1] == ' ') { v->len--; /* Trim trailing spaces in header value */ } if (k->len == 0 || v->len == 0) { k->p = v->p = NULL; k->len = v->len = 0; break; } if (!mg_ncasecmp(k->p, "Content-Length", 14)) { req->body.len = to64(v->p); req->message.len = len + req->body.len; } } return s; } int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) { const char *end, *qs; int len = get_request_len(s, n); if (len <= 0) return len; memset(hm, 0, sizeof(*hm)); hm->message.p = s; hm->body.p = s + len; hm->message.len = hm->body.len = (size_t) ~0; end = s + len; /* Request is fully buffered. Skip leading whitespaces. */ while (s < end && isspace(*(unsigned char *) s)) s++; if (is_req) { /* Parse request line: method, URI, proto */ s = mg_skip(s, end, " ", &hm->method); s = mg_skip(s, end, " ", &hm->uri); s = mg_skip(s, end, "\r\n", &hm->proto); if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1; /* If URI contains '?' character, initialize query_string */ if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) { hm->query_string.p = qs + 1; hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1); hm->uri.len = qs - hm->uri.p; } } else { s = mg_skip(s, end, " ", &hm->proto); if (end - s < 4 || s[3] != ' ') return -1; hm->resp_code = atoi(s); if (hm->resp_code < 100 || hm->resp_code >= 600) return -1; s += 4; s = mg_skip(s, end, "\r\n", &hm->resp_status_msg); } s = parse_http_headers(s, end, len, hm); /* * mg_parse_http() is used to parse both HTTP requests and HTTP * responses. If HTTP response does not have Content-Length set, then * body is read until socket is closed, i.e. body.len is infinite (~0). * * For HTTP requests though, according to * http://tools.ietf.org/html/rfc7231#section-8.1.3, * only POST and PUT methods have defined body semantics. * Therefore, if Content-Length is not specified and methods are * not one of PUT or POST, set body length to 0. * * So, * if it is HTTP request, and Content-Length is not set, * and method is not (PUT or POST) then reset body length to zero. */ if (hm->body.len == (size_t) ~0 && is_req && mg_vcasecmp(&hm->method, "PUT") != 0 && mg_vcasecmp(&hm->method, "POST") != 0) { hm->body.len = 0; hm->message.len = len; } return len; } struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) { size_t i, len = strlen(name); for (i = 0; hm->header_names[i].len > 0; i++) { struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i]; if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len)) return v; } return NULL; } #ifndef MG_DISABLE_HTTP_WEBSOCKET static int is_ws_fragment(unsigned char flags) { return (flags & 0x80) == 0 || (flags & 0x0f) == 0; } static int is_ws_first_fragment(unsigned char flags) { return (flags & 0x80) == 0 && (flags & 0x0f) != 0; } static void handle_incoming_websocket_frame(struct mg_connection *nc, struct websocket_message *wsm) { if (wsm->flags & 0x8) { mg_call(nc, nc->handler, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm); } else { mg_call(nc, nc->handler, MG_EV_WEBSOCKET_FRAME, wsm); } } static int deliver_websocket_data(struct mg_connection *nc) { /* Using unsigned char *, cause of integer arithmetic below */ uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len, mask_len = 0, header_len = 0; unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p, *e = p + buf_len; unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */ int ok, reass = buf_len > 0 && is_ws_fragment(p[0]) && !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG); /* If that's a continuation frame that must be reassembled, handle it */ if (reass && !is_ws_first_fragment(p[0]) && buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) { buf += 1 + sizeof(*sizep) + *sizep; buf_len -= 1 + sizeof(*sizep) + *sizep; } if (buf_len >= 2) { len = buf[1] & 127; mask_len = buf[1] & 128 ? 4 : 0; if (len < 126 && buf_len >= mask_len) { data_len = len; header_len = 2 + mask_len; } else if (len == 126 && buf_len >= 4 + mask_len) { header_len = 4 + mask_len; data_len = ntohs(*(uint16_t *) &buf[2]); } else if (buf_len >= 10 + mask_len) { header_len = 10 + mask_len; data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) + ntohl(*(uint32_t *) &buf[6]); } } frame_len = header_len + data_len; ok = frame_len > 0 && frame_len <= buf_len; if (ok) { struct websocket_message wsm; wsm.size = (size_t) data_len; wsm.data = buf + header_len; wsm.flags = buf[0]; /* Apply mask if necessary */ if (mask_len > 0) { for (i = 0; i < data_len; i++) { buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4]; } } if (reass) { /* On first fragmented frame, nullify size */ if (is_ws_first_fragment(wsm.flags)) { mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep)); p[0] &= ~0x0f; /* Next frames will be treated as continuation */ buf = p + 1 + sizeof(*sizep); *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */ } /* Append this frame to the reassembled buffer */ memmove(buf, wsm.data, e - wsm.data); (*sizep) += wsm.size; nc->recv_mbuf.len -= wsm.data - buf; /* On last fragmented frame - call user handler and remove data */ if (wsm.flags & 0x80) { wsm.data = p + 1 + sizeof(*sizep); wsm.size = *sizep; handle_incoming_websocket_frame(nc, &wsm); mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep); } } else { /* TODO(lsm): properly handle OOB control frames during defragmentation */ handle_incoming_websocket_frame(nc, &wsm); mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */ } /* If client closes, close too */ if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } return ok; } struct ws_mask_ctx { size_t pos; /* zero means unmasked */ uint32_t mask; }; static uint32_t ws_random_mask(void) { /* * The spec requires WS client to generate hard to * guess mask keys. From RFC6455, Section 5.3: * * The unpredictability of the masking key is essential to prevent * authors of malicious applications from selecting the bytes that appear on * the wire. * * Hence this feature is essential when the actual end user of this API * is untrusted code that wouldn't have access to a lower level net API * anyway (e.g. web browsers). Hence this feature is low prio for most * mongoose use cases and thus can be disabled, e.g. when porting to a platform * that lacks random(). */ #ifdef MG_DISABLE_WS_RANDOM_MASK return 0xefbeadde; /* generated with a random number generator, I swear */ #else if (sizeof(long) >= 4) { return (uint32_t) random(); } else if (sizeof(long) == 2) { return (uint32_t) random() << 16 | (uint32_t) random(); } #endif } static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, struct ws_mask_ctx *ctx) { int header_len; unsigned char header[10]; header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f); if (len < 126) { header[1] = len; header_len = 2; } else if (len < 65535) { uint16_t tmp = htons((uint16_t) len); header[1] = 126; memcpy(&header[2], &tmp, sizeof(tmp)); header_len = 4; } else { uint32_t tmp; header[1] = 127; tmp = htonl((uint32_t)((uint64_t) len >> 32)); memcpy(&header[2], &tmp, sizeof(tmp)); tmp = htonl((uint32_t)(len & 0xffffffff)); memcpy(&header[6], &tmp, sizeof(tmp)); header_len = 10; } /* client connections enable masking */ if (nc->listener == NULL) { header[1] |= 1 << 7; /* set masking flag */ mg_send(nc, header, header_len); ctx->mask = ws_random_mask(); mg_send(nc, &ctx->mask, sizeof(ctx->mask)); ctx->pos = nc->send_mbuf.len; } else { mg_send(nc, header, header_len); ctx->pos = 0; } } static void ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) { size_t i; if (ctx->pos == 0) return; for (i = 0; i < (mbuf->len - ctx->pos); i++) { mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4]; } } void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, size_t len) { struct ws_mask_ctx ctx; mg_send_ws_header(nc, op, len, &ctx); mg_send(nc, data, len); ws_mask_frame(&nc->send_mbuf, &ctx); if (op == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } void mg_send_websocket_framev(struct mg_connection *nc, int op, const struct mg_str *strv, int strvcnt) { struct ws_mask_ctx ctx; int i; int len = 0; for (i = 0; i < strvcnt; i++) { len += strv[i].len; } mg_send_ws_header(nc, op, len, &ctx); for (i = 0; i < strvcnt; i++) { mg_send(nc, strv[i].p, strv[i].len); } ws_mask_frame(&nc->send_mbuf, &ctx); if (op == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } void mg_printf_websocket_frame(struct mg_connection *nc, int op, const char *fmt, ...) { char mem[BUFSIZ], *buf = mem; va_list ap; int len; va_start(ap, fmt); if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_send_websocket_frame(nc, op, buf, len); } va_end(ap); if (buf != mem && buf != NULL) { MG_FREE(buf); } } static void websocket_handler(struct mg_connection *nc, int ev, void *ev_data) { mg_call(nc, nc->handler, ev, ev_data); switch (ev) { case MG_EV_RECV: do { } while (deliver_websocket_data(nc)); break; case MG_EV_POLL: /* Ping idle websocket connections */ { time_t now = *(time_t *) ev_data; if (nc->flags & MG_F_IS_WEBSOCKET && now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) { mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0); } } break; default: break; } } static void ws_handshake(struct mg_connection *nc, const struct mg_str *key) { static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char buf[500], sha[20], b64_sha[sizeof(sha) * 2]; cs_sha1_ctx sha_ctx; snprintf(buf, sizeof(buf), "%.*s%s", (int) key->len, key->p, magic); cs_sha1_init(&sha_ctx); cs_sha1_update(&sha_ctx, (unsigned char *) buf, strlen(buf)); cs_sha1_final((unsigned char *) sha, &sha_ctx); mg_base64_encode((unsigned char *) sha, sizeof(sha), b64_sha); mg_printf(nc, "%s%s%s", "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n"); } #endif /* MG_DISABLE_HTTP_WEBSOCKET */ static void free_http_proto_data(struct mg_connection *nc) { struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data; if (dp != NULL) { if (dp->fp != NULL) { fclose(dp->fp); } if (dp->cgi_nc != NULL) { dp->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; } MG_FREE(dp); nc->proto_data = NULL; } } static void transfer_file_data(struct mg_connection *nc) { struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data; char buf[MG_MAX_HTTP_SEND_IOBUF]; int64_t left = dp->cl - dp->sent; size_t n = 0, to_read = 0; if (dp->type == DATA_FILE) { struct mbuf *io = &nc->send_mbuf; if (io->len < sizeof(buf)) { to_read = sizeof(buf) - io->len; } if (left > 0 && to_read > (size_t) left) { to_read = left; } if (to_read == 0) { /* Rate limiting. send_mbuf is too full, wait until it's drained. */ } else if (dp->sent < dp->cl && (n = fread(buf, 1, to_read, dp->fp)) > 0) { mg_send(nc, buf, n); dp->sent += n; } else { free_http_proto_data(nc); #ifdef MG_DISABLE_HTTP_KEEP_ALIVE nc->flags |= MG_F_SEND_AND_CLOSE; #endif } } else if (dp->type == DATA_PUT) { struct mbuf *io = &nc->recv_mbuf; size_t to_write = left <= 0 ? 0 : left < (int64_t) io->len ? (size_t) left : io->len; size_t n = fwrite(io->buf, 1, to_write, dp->fp); if (n > 0) { mbuf_remove(io, n); dp->sent += n; } if (n == 0 || dp->sent >= dp->cl) { free_http_proto_data(nc); #ifdef MG_DISABLE_HTTP_KEEP_ALIVE nc->flags |= MG_F_SEND_AND_CLOSE; #endif } } else if (dp->type == DATA_CGI) { /* This is POST data that needs to be forwarded to the CGI process */ if (dp->cgi_nc != NULL) { mg_forward(nc, dp->cgi_nc); } else { nc->flags |= MG_F_SEND_AND_CLOSE; } } } /* * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or * if it's incomplete. If the chunk is fully buffered, return total number of * bytes in a chunk, and store data in `data`, `data_len`. */ static size_t parse_chunk(char *buf, size_t len, char **chunk_data, size_t *chunk_len) { unsigned char *s = (unsigned char *) buf; size_t n = 0; /* scanned chunk length */ size_t i = 0; /* index in s */ /* Scan chunk length. That should be a hexadecimal number. */ while (i < len && isxdigit(s[i])) { n *= 16; n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10; i++; } /* Skip new line */ if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { return 0; } i += 2; /* Record where the data is */ *chunk_data = (char *) s + i; *chunk_len = n; /* Skip data */ i += n; /* Skip new line */ if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { return 0; } return i + 2; } MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen) { struct proto_data_http *dp; char *data; size_t i, n, data_len, body_len, zero_chunk_received = 0; /* If not allocated, allocate proto_data to hold reassembled offset */ if (nc->proto_data == NULL && (nc->proto_data = MG_CALLOC(1, sizeof(*dp))) == NULL) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return 0; } /* Find out piece of received data that is not yet reassembled */ dp = (struct proto_data_http *) nc->proto_data; body_len = dp->body_len; assert(blen >= body_len); /* Traverse all fully buffered chunks */ for (i = body_len; (n = parse_chunk(buf + i, blen - i, &data, &data_len)) > 0; i += n) { /* Collapse chunk data to the rest of HTTP body */ memmove(buf + body_len, data, data_len); body_len += data_len; hm->body.len = body_len; if (data_len == 0) { zero_chunk_received = 1; i += n; break; } } if (i > body_len) { /* Shift unparsed content to the parsed body */ assert(i <= blen); memmove(buf + body_len, buf + i, blen - i); memset(buf + body_len + blen - i, 0, i - body_len); nc->recv_mbuf.len -= i - body_len; dp->body_len = body_len; /* Send MG_EV_HTTP_CHUNK event */ nc->flags &= ~MG_F_DELETE_CHUNK; mg_call(nc, nc->handler, MG_EV_HTTP_CHUNK, hm); /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ if (nc->flags & MG_F_DELETE_CHUNK) { memset(buf, 0, body_len); memmove(buf, buf + body_len, blen - i); nc->recv_mbuf.len -= body_len; hm->body.len = dp->body_len = 0; } if (zero_chunk_received) { hm->message.len = dp->body_len + blen - i; } } return body_len; } /* * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here) * If a big structure is declared in a big function, lx106 gcc will make it * even bigger (round up to 4k, from 700 bytes of actual size). */ #ifdef MG_ESP8266 static void http_handler2(struct mg_connection *nc, int ev, void *ev_data, struct http_message *hm) __attribute__((noinline)); void http_handler(struct mg_connection *nc, int ev, void *ev_data) { struct http_message hm; http_handler2(nc, ev, ev_data, &hm); } static void http_handler2(struct mg_connection *nc, int ev, void *ev_data, struct http_message *hm) { #else void http_handler(struct mg_connection *nc, int ev, void *ev_data) { struct http_message shm; struct http_message *hm = &shm; #endif struct mbuf *io = &nc->recv_mbuf; int req_len; const int is_req = (nc->listener != NULL); #ifndef MG_DISABLE_HTTP_WEBSOCKET struct mg_str *vec; #endif if (ev == MG_EV_CLOSE) { /* * For HTTP messages without Content-Length, always send HTTP message * before MG_EV_CLOSE message. */ if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) { int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; hm->message.len = io->len; hm->body.len = io->buf + io->len - hm->body.p; mg_call(nc, nc->handler, ev2, hm); } free_http_proto_data(nc); } if (nc->proto_data != NULL) { transfer_file_data(nc); } mg_call(nc, nc->handler, ev, ev_data); if (ev == MG_EV_RECV) { struct mg_str *s; req_len = mg_parse_http(io->buf, io->len, hm, is_req); if (req_len > 0 && (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL && mg_vcasecmp(s, "chunked") == 0) { mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len); } if (req_len < 0 || (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE)) { DBG(("invalid request")); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (req_len == 0) { /* Do nothing, request is not yet fully buffered */ } #ifndef MG_DISABLE_HTTP_WEBSOCKET else if (nc->listener == NULL && mg_get_http_header(hm, "Sec-WebSocket-Accept")) { /* We're websocket client, got handshake response from server. */ /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */ mbuf_remove(io, req_len); nc->proto_handler = websocket_handler; nc->flags |= MG_F_IS_WEBSOCKET; mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL); websocket_handler(nc, MG_EV_RECV, ev_data); } else if (nc->listener != NULL && (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) { /* This is a websocket request. Switch protocol handlers. */ mbuf_remove(io, req_len); nc->proto_handler = websocket_handler; nc->flags |= MG_F_IS_WEBSOCKET; /* Send handshake */ mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm); if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { if (nc->send_mbuf.len == 0) { ws_handshake(nc, vec); } mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL); websocket_handler(nc, MG_EV_RECV, ev_data); } } #endif /* MG_DISABLE_HTTP_WEBSOCKET */ else if (hm->message.len <= io->len) { int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; /* Whole HTTP message is fully buffered, call event handler */ #ifdef MG_ENABLE_JAVASCRIPT v7_val_t v1, v2, headers, req, args, res; struct v7 *v7 = nc->mgr->v7; const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv"; int i, js_callback_handled_request = 0; if (v7 != NULL) { /* Lookup JS callback */ v1 = v7_get(v7, v7_get_global(v7), "Http", ~0); v2 = v7_get(v7, v1, ev_name, ~0); /* Create callback params. TODO(lsm): own/disown those */ args = v7_create_array(v7); req = v7_create_object(v7); headers = v7_create_object(v7); /* Populate request object */ v7_set(v7, req, "method", ~0, 0, v7_create_string(v7, hm->method.p, hm->method.len, 1)); v7_set(v7, req, "uri", ~0, 0, v7_create_string(v7, hm->uri.p, hm->uri.len, 1)); v7_set(v7, req, "body", ~0, 0, v7_create_string(v7, hm->body.p, hm->body.len, 1)); v7_set(v7, req, "headers", ~0, 0, headers); for (i = 0; hm->header_names[i].len > 0; i++) { const struct mg_str *name = &hm->header_names[i]; const struct mg_str *value = &hm->header_values[i]; v7_set(v7, headers, name->p, name->len, 0, v7_create_string(v7, value->p, value->len, 1)); } /* Invoke callback. TODO(lsm): report errors */ v7_array_push(v7, args, v7_create_foreign(nc)); v7_array_push(v7, args, req); if (v7_apply(v7, &res, v2, v7_create_undefined(), args) == V7_OK && v7_is_true(v7, res)) { js_callback_handled_request++; } } /* If JS callback returns true, stop request processing */ if (js_callback_handled_request) { nc->flags |= MG_F_SEND_AND_CLOSE; } else { mg_call(nc, nc->handler, trigger_ev, hm); } #else mg_call(nc, nc->handler, trigger_ev, hm); #endif mbuf_remove(io, hm->message.len); } } } void mg_set_protocol_http_websocket(struct mg_connection *nc) { nc->proto_handler = http_handler; } #ifndef MG_DISABLE_HTTP_WEBSOCKET void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri, const char *extra_headers) { unsigned long random = (unsigned long) uri; char key[sizeof(random) * 3]; mg_base64_encode((unsigned char *) &random, sizeof(random), key); mg_printf(nc, "GET %s HTTP/1.1\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Version: 13\r\n" "Sec-WebSocket-Key: %s\r\n" "%s\r\n", uri, key, extra_headers == NULL ? "" : extra_headers); } #endif /* MG_DISABLE_HTTP_WEBSOCKET */ #ifndef MG_DISABLE_FILESYSTEM void mg_send_response_line(struct mg_connection *nc, int status_code, const char *extra_headers) { const char *status_message = "OK"; switch (status_code) { case 206: status_message = "Partial Content"; break; case 301: status_message = "Moved"; break; case 302: status_message = "Found"; break; case 416: status_message = "Requested range not satisfiable"; break; case 418: status_message = "I'm a teapot"; break; } mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code, status_message); if (extra_headers != NULL) { mg_printf(nc, "%s\r\n", extra_headers); } } void mg_send_head(struct mg_connection *c, int status_code, int64_t content_length, const char *extra_headers) { mg_send_response_line(c, status_code, extra_headers); if (content_length < 0) { mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n"); } else { mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length); } mg_send(c, "\r\n", 2); } static void send_http_error(struct mg_connection *nc, int code, const char *reason) { if (reason == NULL) { reason = ""; } mg_printf(nc, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\n\r\n", code, reason); } #ifndef MG_DISABLE_SSI static void send_ssi_file(struct mg_connection *, const char *, FILE *, int, const struct mg_serve_http_opts *); static void send_file_data(struct mg_connection *nc, FILE *fp) { char buf[BUFSIZ]; size_t n; while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { mg_send(nc, buf, n); } } static void do_ssi_include(struct mg_connection *nc, const char *ssi, char *tag, int include_level, const struct mg_serve_http_opts *opts) { char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p; FILE *fp; /* * sscanf() is safe here, since send_ssi_file() also uses buffer * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. */ if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { /* File name is relative to the webserver root */ snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name); } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { /* * File name is relative to the webserver working directory * or it is absolute system path */ snprintf(path, sizeof(path), "%s", file_name); } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || sscanf(tag, " \"%[^\"]\"", file_name) == 1) { /* File name is relative to the currect document */ snprintf(path, sizeof(path), "%s", ssi); if ((p = strrchr(path, '/')) != NULL) { p[1] = '\0'; } snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); } else { mg_printf(nc, "Bad SSI #include: [%s]", tag); return; } if ((fp = fopen(path, "rb")) == NULL) { mg_printf(nc, "SSI include error: fopen(%s): %s", path, strerror(errno)); } else { mg_set_close_on_exec(fileno(fp)); if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { send_ssi_file(nc, path, fp, include_level + 1, opts); } else { send_file_data(nc, fp); } fclose(fp); } } #ifndef MG_DISABLE_POPEN static void do_ssi_exec(struct mg_connection *nc, char *tag) { char cmd[BUFSIZ]; FILE *fp; if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { mg_printf(nc, "Bad SSI #exec: [%s]", tag); } else if ((fp = popen(cmd, "r")) == NULL) { mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno)); } else { send_file_data(nc, fp); pclose(fp); } } #endif /* !MG_DISABLE_POPEN */ static void do_ssi_call(struct mg_connection *nc, char *tag) { mg_call(nc, NULL, MG_EV_SSI_CALL, tag); } /* * SSI directive has the following format: * <!--#directive parameter=value parameter=value --> */ static void send_ssi_file(struct mg_connection *nc, const char *path, FILE *fp, int include_level, const struct mg_serve_http_opts *opts) { static const struct mg_str btag = MG_STR("<!--#"); static const struct mg_str d_include = MG_STR("include"); static const struct mg_str d_call = MG_STR("call"); #ifndef MG_DISABLE_POPEN static const struct mg_str d_exec = MG_STR("exec"); #endif char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */ int ch, offset, len, in_ssi_tag; if (include_level > 10) { mg_printf(nc, "SSI #include level is too deep (%s)", path); return; } in_ssi_tag = len = offset = 0; while ((ch = fgetc(fp)) != EOF) { if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') { size_t i = len - 2; in_ssi_tag = 0; /* Trim closing --> */ buf[i--] = '\0'; while (i > 0 && buf[i] == ' ') { buf[i--] = '\0'; } /* Handle known SSI directives */ if (memcmp(p, d_include.p, d_include.len) == 0) { do_ssi_include(nc, path, p + d_include.len + 1, include_level, opts); } else if (memcmp(p, d_call.p, d_call.len) == 0) { do_ssi_call(nc, p + d_call.len + 1); #ifndef MG_DISABLE_POPEN } else if (memcmp(p, d_exec.p, d_exec.len) == 0) { do_ssi_exec(nc, p + d_exec.len + 1); #endif } else { /* Silently ignore unknown SSI directive. */ } len = 0; } else if (ch == '<') { in_ssi_tag = 1; if (len > 0) { mg_send(nc, buf, (size_t) len); } len = 0; buf[len++] = ch & 0xff; } else if (in_ssi_tag) { if (len == (int) btag.len && memcmp(buf, btag.p, btag.len) != 0) { /* Not an SSI tag */ in_ssi_tag = 0; } else if (len == (int) sizeof(buf) - 2) { mg_printf(nc, "%s: SSI tag is too large", path); len = 0; } buf[len++] = ch & 0xff; } else { buf[len++] = ch & 0xff; if (len == (int) sizeof(buf)) { mg_send(nc, buf, (size_t) len); len = 0; } } } /* Send the rest of buffered data */ if (len > 0) { mg_send(nc, buf, (size_t) len); } } static void handle_ssi_request(struct mg_connection *nc, const char *path, const struct mg_serve_http_opts *opts) { FILE *fp; struct mg_str mime_type; if ((fp = fopen(path, "rb")) == NULL) { send_http_error(nc, 404, "Not Found"); } else { mg_set_close_on_exec(fileno(fp)); mime_type = get_mime_type(path, "text/plain", opts); mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "Content-Type: %.*s\r\n" "Connection: close\r\n\r\n", (int) mime_type.len, mime_type.p); send_ssi_file(nc, path, fp, 0, opts); fclose(fp); nc->flags |= MG_F_SEND_AND_CLOSE; } } #else static void handle_ssi_request(struct mg_connection *nc, const char *path, const struct mg_serve_http_opts *opts) { (void) path; (void) opts; send_http_error(nc, 500, "SSI disabled"); } #endif /* MG_DISABLE_SSI */ static void construct_etag(char *buf, size_t buf_len, const cs_stat_t *st) { snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, (int64_t) st->st_size); } static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); } static int parse_range_header(const struct mg_str *header, int64_t *a, int64_t *b) { /* * There is no snscanf. Headers are not guaranteed to be NUL-terminated, * so we have this. Ugh. */ int result; char *p = (char *) MG_MALLOC(header->len + 1); if (p == NULL) return 0; memcpy(p, header->p, header->len); p[header->len] = '\0'; result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); MG_FREE(p); return result; } static void mg_send_http_file2(struct mg_connection *nc, const char *path, cs_stat_t *st, struct http_message *hm, struct mg_serve_http_opts *opts) { struct proto_data_http *dp; struct mg_str mime_type; free_http_proto_data(nc); if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) { send_http_error(nc, 500, "Server Error"); /* LCOV_EXCL_LINE */ } else if ((dp->fp = fopen(path, "rb")) == NULL) { MG_FREE(dp); nc->proto_data = NULL; send_http_error(nc, 500, "Server Error"); } else if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { nc->proto_data = (void *) dp; handle_ssi_request(nc, path, opts); } else { char etag[50], current_time[50], last_modified[50], range[50]; time_t t = time(NULL); int64_t r1 = 0, r2 = 0, cl = st->st_size; struct mg_str *range_hdr = mg_get_http_header(hm, "Range"); int n, status_code = 200; /* Handle Range header */ range[0] = '\0'; if (range_hdr != NULL && (n = parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 && r2 >= 0) { /* If range is specified like "400-", set second limit to content len */ if (n == 1) { r2 = cl - 1; } if (r1 > r2 || r2 >= cl) { status_code = 416; cl = 0; snprintf(range, sizeof(range), "Content-Range: bytes */%" INT64_FMT "\r\n", (int64_t) st->st_size); } else { status_code = 206; cl = r2 - r1 + 1; snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", r1, r1 + cl - 1, (int64_t) st->st_size); fseeko(dp->fp, r1, SEEK_SET); } } construct_etag(etag, sizeof(etag), st); gmt_time_string(current_time, sizeof(current_time), &t); gmt_time_string(last_modified, sizeof(last_modified), &st->st_mtime); mime_type = get_mime_type(path, "text/plain", opts); /* * Content length casted to size_t because: * 1) that's the maximum buffer size anyway * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last * position * TODO(mkm): fix ESP8266 RTOS SDK */ mg_send_response_line(nc, status_code, opts->extra_headers); mg_printf(nc, "Date: %s\r\n" "Last-Modified: %s\r\n" "Accept-Ranges: bytes\r\n" "Content-Type: %.*s\r\n" #ifdef MG_DISABLE_HTTP_KEEP_ALIVE "Connection: close\r\n" #endif "Content-Length: %" SIZE_T_FMT "\r\n" "%sEtag: %s\r\n\r\n", current_time, last_modified, (int) mime_type.len, mime_type.p, (size_t) cl, range, etag); nc->proto_data = (void *) dp; dp->cl = cl; dp->type = DATA_FILE; transfer_file_data(nc); } } static void remove_double_dots(char *s) { char *p = s; while (*s != '\0') { *p++ = *s++; if (s[-1] == '/' || s[-1] == '\\') { while (s[0] != '\0') { if (s[0] == '/' || s[0] == '\\') { s++; } else if (s[0] == '.' && s[1] == '.') { s += 2; } else { break; } } } } *p = '\0'; } #endif static int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded) { int i, j, a, b; #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { if (src[i] == '%') { if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) && isxdigit(*(const unsigned char *) (src + i + 2))) { a = tolower(*(const unsigned char *) (src + i + 1)); b = tolower(*(const unsigned char *) (src + i + 2)); dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); i += 2; } else { return -1; } } else if (is_form_url_encoded && src[i] == '+') { dst[j] = ' '; } else { dst[j] = src[i]; } } dst[j] = '\0'; /* Null-terminate the destination */ return i >= src_len ? j : -1; } int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, size_t dst_len) { const char *p, *e, *s; size_t name_len; int len; if (dst == NULL || dst_len == 0) { len = -2; } else if (buf->p == NULL || name == NULL || buf->len == 0) { len = -1; dst[0] = '\0'; } else { name_len = strlen(name); e = buf->p + buf->len; len = -1; dst[0] = '\0'; for (p = buf->p; p + name_len < e; p++) { if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' && !mg_ncasecmp(name, p, name_len)) { p += name_len + 1; s = (const char *) memchr(p, '&', (size_t)(e - p)); if (s == NULL) { s = e; } len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); if (len == -1) { len = -2; } break; } } } return len; } void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) { char chunk_size[50]; int n; n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len); mg_send(nc, chunk_size, n); mg_send(nc, buf, len); mg_send(nc, "\r\n", 2); } void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) { char mem[500], *buf = mem; int len; va_list ap; va_start(ap, fmt); len = mg_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { mg_send_http_chunk(nc, buf, len); } /* LCOV_EXCL_START */ if (buf != mem && buf != NULL) { MG_FREE(buf); } /* LCOV_EXCL_STOP */ } void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) { char mem[500], *buf = mem; int i, j, len; va_list ap; va_start(ap, fmt); len = mg_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { for (i = j = 0; i < len; i++) { if (buf[i] == '<' || buf[i] == '>') { mg_send(nc, buf + j, i - j); mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4); j = i + 1; } } mg_send(nc, buf + j, i - j); } /* LCOV_EXCL_START */ if (buf != mem && buf != NULL) { MG_FREE(buf); } /* LCOV_EXCL_STOP */ } int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, size_t buf_size) { int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name); const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL; if (buf != NULL && buf_size > 0) buf[0] = '\0'; if (hdr == NULL) return 0; /* Find where variable starts */ for (s = hdr->p; s != NULL && s + n < end; s++) { if ((s == hdr->p || s[-1] == ch || s[-1] == ch1) && s[n] == '=' && !memcmp(s, var_name, n)) break; } if (s != NULL && &s[n + 1] < end) { s += n + 1; if (*s == '"' || *s == '\'') { ch = ch1 = *s++; } p = s; while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) { if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++; buf[len++] = *p++; } if (len >= (int) buf_size || (ch != ' ' && *p != ch)) { len = 0; } else { if (len > 0 && s[len - 1] == ',') len--; if (len > 0 && s[len - 1] == ';') len--; buf[len] = '\0'; } } return len; } #ifndef MG_DISABLE_FILESYSTEM static int is_file_hidden(const char *path, const struct mg_serve_http_opts *opts) { const char *p1 = opts->per_directory_auth_file; const char *p2 = opts->hidden_file_pattern; /* Strip directory path from the file name */ const char *pdir = strrchr(path, DIRSEP); if (pdir != NULL) { path = pdir + 1; } return !strcmp(path, ".") || !strcmp(path, "..") || (p1 != NULL && !strcmp(path, p1)) || (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0); } #ifndef MG_DISABLE_HTTP_DIGEST_AUTH static void mkmd5resp(const char *method, size_t method_len, const char *uri, size_t uri_len, const char *ha1, size_t ha1_len, const char *nonce, size_t nonce_len, const char *nc, size_t nc_len, const char *cnonce, size_t cnonce_len, const char *qop, size_t qop_len, char *resp) { static const char colon[] = ":"; static const size_t one = 1; char ha2[33]; cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL); cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc, nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len, colon, one, ha2, sizeof(ha2) - 1, NULL); } int mg_http_create_digest_auth_header(char *buf, size_t buf_len, const char *method, const char *uri, const char *auth_domain, const char *user, const char *passwd) { static const char colon[] = ":", qop[] = "auth"; static const size_t one = 1; char ha1[33], resp[33], cnonce[40]; snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) time(NULL)); cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain, (size_t) strlen(auth_domain), colon, one, passwd, (size_t) strlen(passwd), NULL); mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1, cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop, sizeof(qop) - 1, resp); return snprintf(buf, buf_len, "Authorization: Digest username=\"%s\"," "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s," "nonce=%s,response=%s\r\n", user, auth_domain, uri, qop, cnonce, cnonce, resp); } /* * Check for authentication timeout. * Clients send time stamp encoded in nonce. Make sure it is not too old, * to prevent replay attacks. * Assumption: nonce is a hexadecimal number of seconds since 1970. */ static int check_nonce(const char *nonce) { unsigned long now = (unsigned long) time(NULL); unsigned long val = (unsigned long) strtoul(nonce, NULL, 16); return 1 || now < val || now - val < 3600; } /* * Authenticate HTTP request against opened passwords file. * Returns 1 if authenticated, 0 otherwise. */ static int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, FILE *fp) { struct mg_str *hdr; char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)]; char user[50], cnonce[20], response[40], uri[200], qop[20], nc[20], nonce[30]; char expected_response[33]; /* Parse "Authorization:" header, fail fast on parse error */ if (hm == NULL || fp == NULL || (hdr = mg_get_http_header(hm, "Authorization")) == NULL || mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 || mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 || mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 || mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 || mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 || mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 || mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 || check_nonce(nonce) == 0) { return 0; } /* * Read passwords file line by line. If should have htdigest format, * i.e. each line should be a colon-separated sequence: * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD */ while (fgets(buf, sizeof(buf), fp) != NULL) { if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 && strcmp(user, f_user) == 0 && /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */ strcmp(auth_domain, f_domain) == 0) { /* User and domain matched, check the password */ mkmd5resp(hm->method.p, hm->method.len, hm->uri.p, hm->uri.len, f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce, strlen(cnonce), qop, strlen(qop), expected_response); return mg_casecmp(response, expected_response) == 0; } } /* None of the entries in the passwords file matched - return failure */ return 0; } static int is_authorized(struct http_message *hm, const char *path, int is_directory, const char *domain, const char *passwords_file, int is_global_pass_file) { char buf[MAX_PATH_SIZE]; const char *p; FILE *fp; int authorized = 1; if (domain != NULL && passwords_file != NULL) { if (is_global_pass_file) { fp = fopen(passwords_file, "r"); } else if (is_directory) { snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file); fp = fopen(buf, "r"); } else { if ((p = strrchr(path, '/')) == NULL && (p = strrchr(path, '\\')) == NULL) { p = path; } snprintf(buf, sizeof(buf), "%.*s/%s", (int) (p - path), path, passwords_file); fp = fopen(buf, "r"); } if (fp != NULL) { authorized = mg_http_check_digest_auth(hm, domain, fp); fclose(fp); } } return authorized; } #else static int is_authorized(struct http_message *hm, const char *path, int is_directory, const char *domain, const char *passwords_file, int is_global_pass_file) { (void) hm; (void) path; (void) is_directory; (void) domain; (void) passwords_file; (void) is_global_pass_file; return 1; } #endif #ifndef MG_DISABLE_DIRECTORY_LISTING static size_t mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) { static const char *dont_escape = "._-$,;~()"; static const char *hex = "0123456789abcdef"; size_t i = 0, j = 0; for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) { if (isalnum(*(const unsigned char *) (src + i)) || strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) { dst[j] = src[i]; } else if (j + 3 < dst_len) { dst[j] = '%'; dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4]; dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf]; j += 2; } } dst[j] = '\0'; return j; } static void escape(const char *src, char *dst, size_t dst_len) { size_t n = 0; while (*src != '\0' && n + 5 < dst_len) { unsigned char ch = *(unsigned char *) src++; if (ch == '<') { n += snprintf(dst + n, dst_len - n, "%s", "&lt;"); } else { dst[n++] = ch; } } dst[n] = '\0'; } static void print_dir_entry(struct mg_connection *nc, const char *file_name, cs_stat_t *stp) { char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE]; int64_t fsize = stp->st_size; int is_dir = S_ISDIR(stp->st_mode); const char *slash = is_dir ? "/" : ""; if (is_dir) { snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); } else { /* * We use (double) cast below because MSVC 6 compiler cannot * convert unsigned __int64 to double. */ if (fsize < 1024) { snprintf(size, sizeof(size), "%d", (int) fsize); } else if (fsize < 0x100000) { snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); } else if (fsize < 0x40000000) { snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); } else { snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); } } strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); escape(file_name, path, sizeof(path)); mg_url_encode(file_name, strlen(file_name), href, sizeof(href)); mg_printf_http_chunk(nc, "<tr><td><a href=\"%s%s\">%s%s</a></td>" "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n", href, slash, path, slash, mod, is_dir ? -1 : fsize, size); } static void scan_directory(struct mg_connection *nc, const char *dir, const struct mg_serve_http_opts *opts, void (*func)(struct mg_connection *, const char *, cs_stat_t *)) { char path[MAX_PATH_SIZE]; cs_stat_t st; struct dirent *dp; DIR *dirp; if ((dirp = (opendir(dir))) != NULL) { while ((dp = readdir(dirp)) != NULL) { /* Do not show current dir and hidden files */ if (is_file_hidden(dp->d_name, opts)) { continue; } snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name); if (mg_stat(path, &st) == 0) { func(nc, dp->d_name, &st); } } closedir(dirp); } } static void send_directory_listing(struct mg_connection *nc, const char *dir, struct http_message *hm, struct mg_serve_http_opts *opts) { static const char *sort_js_code = "<script>function srt(tb, col) {" "var tr = Array.prototype.slice.call(tb.rows, 0)," "tr = tr.sort(function (a, b) { var c1 = a.cells[col], c2 = b.cells[col]," "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), " "t1 = a.cells[2].getAttribute('name'), " "t2 = b.cells[2].getAttribute('name'); " "return t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : " "n1 ? parseInt(n2) - parseInt(n1) : " "c1.textContent.trim().localeCompare(c2.textContent.trim()); });"; static const char *sort_js_code2 = "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]);}" "window.onload = function() { " "var tb = document.getElementById('tb');" "document.onclick = function(ev){ " "var c = ev.target.rel; if (c) srt(tb, c)}; srt(tb, 2); };</script>"; mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", "Content-Type", "text/html; charset=utf-8"); mg_printf_http_chunk( nc, "<html><head><title>Index of %.*s</title>%s%s" "<style>th,td {text-align: left; padding-right: 1em; }</style></head>" "<body><h1>Index of %.*s</h1><pre><table cellpadding=\"0\"><thead>" "<tr><th><a href=# rel=0>Name</a></th><th>" "<a href=# rel=1>Modified</a</th>" "<th><a href=# rel=2>Size</a></th></tr>" "<tr><td colspan=\"3\"><hr></td></tr></thead><tbody id=tb>", (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2, (int) hm->uri.len, hm->uri.p); scan_directory(nc, dir, opts, print_dir_entry); mg_printf_http_chunk(nc, "%s", "</tbody></body></html>"); mg_send_http_chunk(nc, "", 0); /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */ nc->flags |= MG_F_SEND_AND_CLOSE; } #endif /* MG_DISABLE_DIRECTORY_LISTING */ #ifndef MG_DISABLE_DAV static void print_props(struct mg_connection *nc, const char *name, cs_stat_t *stp) { char mtime[64], buf[MAX_PATH_SIZE * 3]; time_t t = stp->st_mtime; /* store in local variable for NDK compile */ gmt_time_string(mtime, sizeof(mtime), &t); mg_url_encode(name, strlen(name), buf, sizeof(buf)); mg_printf(nc, "<d:response>" "<d:href>%s</d:href>" "<d:propstat>" "<d:prop>" "<d:resourcetype>%s</d:resourcetype>" "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>" "<d:getlastmodified>%s</d:getlastmodified>" "</d:prop>" "<d:status>HTTP/1.1 200 OK</d:status>" "</d:propstat>" "</d:response>\n", buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "", (int64_t) stp->st_size, mtime); } static void handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts) { static const char header[] = "HTTP/1.1 207 Multi-Status\r\n" "Connection: close\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n" "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n"; static const char footer[] = "</d:multistatus>\n"; const struct mg_str *depth = mg_get_http_header(hm, "Depth"); /* Print properties for the requested resource itself */ if (S_ISDIR(stp->st_mode) && strcmp(opts->enable_directory_listing, "yes") != 0) { mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n"); } else { char uri[MAX_PATH_SIZE]; mg_send(nc, header, sizeof(header) - 1); snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p); print_props(nc, uri, stp); if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) { scan_directory(nc, path, opts, print_props); } mg_send(nc, footer, sizeof(footer) - 1); nc->flags |= MG_F_SEND_AND_CLOSE; } } static void handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm) { int status_code = 500; if (mg_get_http_header(hm, "Content-Length") != NULL) { status_code = 415; } else if (!mg_mkdir(path, 0755)) { status_code = 201; } else if (errno == EEXIST) { status_code = 405; } else if (errno == EACCES) { status_code = 403; } else if (errno == ENOENT) { status_code = 409; } send_http_error(nc, status_code, NULL); } static int remove_directory(const char *dir) { char path[MAX_PATH_SIZE]; struct dirent *dp; cs_stat_t st; DIR *dirp; if ((dirp = opendir(dir)) == NULL) return 0; while ((dp = readdir(dirp)) != NULL) { if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue; snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); mg_stat(path, &st); if (S_ISDIR(st.st_mode)) { remove_directory(path); } else { remove(path); } } closedir(dirp); rmdir(dir); return 1; } static void handle_delete(struct mg_connection *nc, const char *path) { cs_stat_t st; if (mg_stat(path, &st) != 0) { send_http_error(nc, 404, NULL); } else if (S_ISDIR(st.st_mode)) { remove_directory(path); send_http_error(nc, 204, NULL); } else if (remove(path) == 0) { send_http_error(nc, 204, NULL); } else { send_http_error(nc, 423, NULL); } } /* Return -1 on error, 1 on success. */ static int create_itermediate_directories(const char *path) { const char *s = path; /* Create intermediate directories if they do not exist */ while (*s) { if (*s == '/') { char buf[MAX_PATH_SIZE]; cs_stat_t st; snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path); buf[sizeof(buf) - 1] = '\0'; if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) { return -1; } } s++; } return 1; } static void handle_put(struct mg_connection *nc, const char *path, struct http_message *hm) { cs_stat_t st; const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length"); int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201; struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data; free_http_proto_data(nc); if ((rc = create_itermediate_directories(path)) == 0) { mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); } else if (rc == -1) { send_http_error(nc, 500, NULL); } else if (cl_hdr == NULL) { send_http_error(nc, 411, NULL); } else if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) { send_http_error(nc, 500, NULL); /* LCOV_EXCL_LINE */ } else if ((dp->fp = fopen(path, "w+b")) == NULL) { send_http_error(nc, 500, NULL); free_http_proto_data(nc); } else { const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range"); int64_t r1 = 0, r2 = 0; dp->type = DATA_PUT; mg_set_close_on_exec(fileno(dp->fp)); dp->cl = to64(cl_hdr->p); if (range_hdr != NULL && parse_range_header(range_hdr, &r1, &r2) > 0) { status_code = 206; fseeko(dp->fp, r1, SEEK_SET); dp->cl = r2 > r1 ? r2 - r1 + 1 : dp->cl - r1; } mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); nc->proto_data = dp; /* Remove HTTP request from the mbuf, leave only payload */ mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len); transfer_file_data(nc); } } #endif /* MG_DISABLE_DAV */ static int is_dav_request(const struct mg_str *s) { return !mg_vcmp(s, "PUT") || !mg_vcmp(s, "DELETE") || !mg_vcmp(s, "MKCOL") || !mg_vcmp(s, "PROPFIND"); } /* * Given a directory path, find one of the files specified in the * comma-separated list of index files `list`. * First found index file wins. If an index file is found, then gets * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`. * If index file is not found, then `path` and `stp` remain unchanged. */ MG_INTERNAL int find_index_file(char *path, size_t path_len, const char *list, cs_stat_t *stp) { cs_stat_t st; size_t n = strlen(path); struct mg_str vec; int found = 0; /* The 'path' given to us points to the directory. Remove all trailing */ /* directory separator characters from the end of the path, and */ /* then append single directory separator character. */ while (n > 0 && (path[n - 1] == '/' || path[n - 1] == '\\')) { n--; } /* Traverse index files list. For each entry, append it to the given */ /* path and see if the file exists. If it exists, break the loop */ while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) { /* Prepare full path to the index file */ snprintf(path + n, path_len - n, "/%.*s", (int) vec.len, vec.p); path[path_len - 1] = '\0'; /* Does it exist? */ if (!mg_stat(path, &st)) { /* Yes it does, break the loop */ *stp = st; found = 1; break; } } /* If no index file exists, restore directory path, keep trailing slash. */ if (!found) { path[n] = '\0'; strncat(path + n, "/", path_len - n); } return found; } static int send_port_based_redirect(struct mg_connection *c, struct http_message *hm, const struct mg_serve_http_opts *opts) { const char *rewrites = opts->url_rewrites; struct mg_str a, b; char local_port[20] = {'%'}; #ifndef MG_ESP8266 mg_sock_to_str(c->sock, local_port + 1, sizeof(local_port) - 1, MG_SOCK_STRINGIFY_PORT); #else /* TODO(lsm): remove when mg_sock_to_str() is implemented in LWIP codepath */ snprintf(local_port, sizeof(local_port), "%s", "%0"); #endif while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (mg_vcmp(&a, local_port) == 0) { mg_send_response_line(c, 301, NULL); mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n", (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1), hm->uri.p); return 1; } } return 0; } static void uri_to_path(struct http_message *hm, char *buf, size_t buf_len, const struct mg_serve_http_opts *opts) { char uri[MG_MAX_PATH]; struct mg_str a, b, *host_hdr = mg_get_http_header(hm, "Host"); const char *rewrites = opts->url_rewrites; mg_url_decode(hm->uri.p, hm->uri.len, uri, sizeof(uri), 0); remove_double_dots(uri); snprintf(buf, buf_len, "%s%s", opts->document_root, uri); #ifndef MG_DISABLE_DAV if (is_dav_request(&hm->method) && opts->dav_document_root != NULL) { snprintf(buf, buf_len, "%s%s", opts->dav_document_root, uri); } #endif /* Handle URL rewrites */ while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (a.len > 1 && a.p[0] == '@' && host_hdr != NULL && host_hdr->len == a.len - 1 && mg_ncasecmp(a.p + 1, host_hdr->p, a.len - 1) == 0) { /* This is a virtual host rewrite: @domain.name=document_root_dir */ snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.p, uri); break; } else { /* This is a usual rewrite, URI=directory */ int match_len = mg_match_prefix(a.p, a.len, uri); if (match_len > 0) { snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.p, uri + match_len); break; } } } } #ifndef MG_DISABLE_CGI #ifdef _WIN32 struct threadparam { sock_t s; HANDLE hPipe; }; static int wait_until_ready(sock_t sock, int for_read) { fd_set set; FD_ZERO(&set); FD_SET(sock, &set); return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1; } static void *push_to_stdin(void *arg) { struct threadparam *tp = (struct threadparam *) arg; int n, sent, stop = 0; DWORD k; char buf[BUFSIZ]; while (!stop && wait_until_ready(tp->s, 1) && (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; for (sent = 0; !stop && sent < n; sent += k) { if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; } } DBG(("%s", "FORWARED EVERYTHING TO CGI")); CloseHandle(tp->hPipe); MG_FREE(tp); _endthread(); return NULL; } static void *pull_from_stdout(void *arg) { struct threadparam *tp = (struct threadparam *) arg; int k = 0, stop = 0; DWORD n, sent; char buf[BUFSIZ]; while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { for (sent = 0; !stop && sent < n; sent += k) { if (wait_until_ready(tp->s, 0) && (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1; } } DBG(("%s", "EOF FROM CGI")); CloseHandle(tp->hPipe); shutdown(tp->s, 2); // Without this, IO thread may get truncated data closesocket(tp->s); MG_FREE(tp); _endthread(); return NULL; } static void spawn_stdio_thread(sock_t sock, HANDLE hPipe, void *(*func)(void *)) { struct threadparam *tp = (struct threadparam *) MG_MALLOC(sizeof(*tp)); if (tp != NULL) { tp->s = sock; tp->hPipe = hPipe; mg_start_thread(func, tp); } } static void abs_path(const char *utf8_path, char *abs_path, size_t len) { wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE]; to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); } static pid_t start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { STARTUPINFOW si; PROCESS_INFORMATION pi; HANDLE a[2], b[2], me = GetCurrentProcess(); wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE]; char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE]; DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; FILE *fp; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); CreatePipe(&a[0], &a[1], NULL, 0); CreatePipe(&b[0], &b[1], NULL, 0); DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) { buf[0] = buf[1] = '\0'; fgets(buf, sizeof(buf), fp); buf[sizeof(buf) - 1] = '\0'; if (buf[0] == '#' && buf[1] == '!') { interp = buf + 2; /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */ while (*interp != '\0' && isspace(*(unsigned char *) interp)) { interp++; } } fclose(fp); } snprintf(buf, sizeof(buf), "%s/%s", dir, cmd); abs_path(buf, buf2, ARRAY_SIZE(buf2)); abs_path(dir, buf5, ARRAY_SIZE(buf5)); to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); if (interp != NULL) { abs_path(interp, buf4, ARRAY_SIZE(buf4)); snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2); } else { snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2); } to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); #if 0 printf("[%ls] [%ls]\n", full_dir, wcmd); #endif if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, (void *) env, full_dir, &si, &pi) != 0) { spawn_stdio_thread(sock, a[1], push_to_stdin); spawn_stdio_thread(sock, b[0], pull_from_stdout); } else { CloseHandle(a[1]); CloseHandle(b[0]); closesocket(sock); } DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */ CloseHandle(si.hStdOutput); CloseHandle(si.hStdInput); /* TODO(lsm): check if we need close process and thread handles too */ /* CloseHandle(pi.hThread); */ /* CloseHandle(pi.hProcess); */ return pi.hProcess; } #else static pid_t start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { char buf[500]; pid_t pid = fork(); (void) env; if (pid == 0) { /* * In Linux `chdir` declared with `warn_unused_result` attribute * To shutup compiler we have yo use result in some way */ int tmp = chdir(dir); (void) tmp; (void) dup2(sock, 0); (void) dup2(sock, 1); closesocket(sock); /* * After exec, all signal handlers are restored to their default values, * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's * implementation, SIGCHLD's handler will leave unchanged after exec * if it was set to be ignored. Restore it to default action. */ signal(SIGCHLD, SIG_DFL); if (interp == NULL) { execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */ } else { execle(interp, interp, cmd, (char *) 0, envp); } snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n" "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, strerror(errno)); send(1, buf, strlen(buf), 0); exit(EXIT_FAILURE); /* exec call failed */ } return pid; } #endif /* _WIN32 */ /* * Append VARIABLE=VALUE\0 string to the buffer, and add a respective * pointer into the vars array. */ static char *addenv(struct cgi_env_block *block, const char *fmt, ...) { int n, space; char *added = block->buf + block->len; va_list ap; /* Calculate how much space is left in the buffer */ space = sizeof(block->buf) - (block->len + 2); if (space > 0) { /* Copy VARIABLE=VALUE\0 string into the free space */ va_start(ap, fmt); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" n = vsnprintf(added, (size_t) space, fmt, ap); #pragma GCC diagnostic pop va_end(ap); /* Make sure we do not overflow buffer and the envp array */ if (n > 0 && n + 1 < space && block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { /* Append a pointer to the added string into the envp array */ block->vars[block->nvars++] = added; /* Bump up used length counter. Include \0 terminator */ block->len += n + 1; } } return added; } static void addenv2(struct cgi_env_block *blk, const char *name) { const char *s; if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s); } static void prepare_cgi_environment(struct mg_connection *nc, const char *prog, const struct http_message *hm, const struct mg_serve_http_opts *opts, struct cgi_env_block *blk) { const char *s, *slash; struct mg_str *h; char *p; size_t i; blk->len = blk->nvars = 0; blk->nc = nc; if ((s = getenv("SERVER_NAME")) != NULL) { addenv(blk, "SERVER_NAME=%s", s); } else { char buf[100]; mg_sock_to_str(nc->sock, buf, sizeof(buf), 3); addenv(blk, "SERVER_NAME=%s", buf); } addenv(blk, "SERVER_ROOT=%s", opts->document_root); addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root); addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION); /* Prepare the environment block */ addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */ /* TODO(lsm): fix this for IPv6 case */ /*addenv(blk, "SERVER_PORT=%d", ri->remote_port); */ addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p); #if 0 addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip); addenv(blk, "REMOTE_PORT=%d", ri->remote_port); #endif addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p, hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len, hm->query_string.p); /* SCRIPT_NAME */ #if 0 if (nc->path_info != NULL) { addenv(blk, "SCRIPT_NAME=%.*s", (int) (strlen(ri->uri) - strlen(nc->path_info)), ri->uri); addenv(blk, "PATH_INFO=%s", nc->path_info); } else { #endif s = strrchr(prog, '/'); slash = hm->uri.p + hm->uri.len; while (slash > hm->uri.p && *slash != '/') { slash--; } addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - hm->uri.p), hm->uri.p, s == NULL ? prog : s); #if 0 } #endif addenv(blk, "SCRIPT_FILENAME=%s", prog); addenv(blk, "PATH_TRANSLATED=%s", prog); addenv(blk, "HTTPS=%s", nc->ssl != NULL ? "on" : "off"); if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) != NULL) { addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p); } if (hm->query_string.len > 0) { addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len, hm->query_string.p); } if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) != NULL) { addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p); } addenv2(blk, "PATH"); addenv2(blk, "TMP"); addenv2(blk, "TEMP"); addenv2(blk, "TMPDIR"); addenv2(blk, "PERLLIB"); addenv2(blk, MG_ENV_EXPORT_TO_CGI); #if defined(_WIN32) addenv2(blk, "COMSPEC"); addenv2(blk, "SYSTEMROOT"); addenv2(blk, "SystemDrive"); addenv2(blk, "ProgramFiles"); addenv2(blk, "ProgramFiles(x86)"); addenv2(blk, "CommonProgramFiles(x86)"); #else addenv2(blk, "LD_LIBRARY_PATH"); #endif /* _WIN32 */ /* Add all headers as HTTP_* variables */ for (i = 0; hm->header_names[i].len > 0; i++) { p = addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len, hm->header_names[i].p, (int) hm->header_values[i].len, hm->header_values[i].p); /* Convert variable name into uppercase, and change - to _ */ for (; *p != '=' && *p != '\0'; p++) { if (*p == '-') *p = '_'; *p = (char) toupper(*(unsigned char *) p); } } blk->vars[blk->nvars++] = NULL; blk->buf[blk->len++] = '\0'; } static void cgi_ev_handler(struct mg_connection *cgi_nc, int ev, void *ev_data) { struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data; (void) ev_data; if (nc == NULL) return; switch (ev) { case MG_EV_RECV: /* * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n" * It outputs headers, then body. Headers might include "Status" * header, which changes CODE, and it might include "Location" header * which changes CODE to 302. * * Therefore we do not send the output from the CGI script to the user * until all CGI headers are received. * * Here we parse the output from the CGI script, and if all headers has * been received, send appropriate reply line, and forward all * received headers to the client. */ if (nc->flags & MG_F_USER_1) { struct mbuf *io = &cgi_nc->recv_mbuf; int len = get_request_len(io->buf, io->len); if (len == 0) break; if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) { cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; send_http_error(nc, 500, "Bad headers"); } else { struct http_message hm; struct mg_str *h; parse_http_headers(io->buf, io->buf + io->len, io->len, &hm); /*printf("=== %d [%.*s]\n", k, k, io->buf);*/ if (mg_get_http_header(&hm, "Location") != NULL) { mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n"); } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) { mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p); } else { mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n"); } } nc->flags &= ~MG_F_USER_1; } if (!(nc->flags & MG_F_USER_1)) { mg_forward(cgi_nc, nc); } break; case MG_EV_CLOSE: free_http_proto_data(cgi_nc); nc->flags |= MG_F_SEND_AND_CLOSE; nc->user_data = NULL; break; } } static void handle_cgi(struct mg_connection *nc, const char *prog, const struct http_message *hm, const struct mg_serve_http_opts *opts) { struct proto_data_http *dp; struct cgi_env_block blk; char dir[MAX_PATH_SIZE]; const char *p; sock_t fds[2]; prepare_cgi_environment(nc, prog, hm, opts, &blk); /* * CGI must be executed in its own directory. 'dir' must point to the * directory containing executable program, 'p' must point to the * executable program name relative to 'dir'. */ if ((p = strrchr(prog, '/')) == NULL) { snprintf(dir, sizeof(dir), "%s", "."); } else { snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); prog = p + 1; } /* * Try to create socketpair in a loop until success. mg_socketpair() * can be interrupted by a signal and fail. * TODO(lsm): use sigaction to restart interrupted syscall */ do { mg_socketpair(fds, SOCK_STREAM); } while (fds[0] == INVALID_SOCKET); free_http_proto_data(nc); if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) { send_http_error(nc, 500, "OOM"); /* LCOV_EXCL_LINE */ } else if (start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir, fds[1]) != 0) { size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len); dp->type = DATA_CGI; dp->cgi_nc = mg_add_sock(nc->mgr, fds[0], cgi_ev_handler); dp->cgi_nc->user_data = nc; dp->cgi_nc->proto_data = dp; nc->flags |= MG_F_USER_1; /* Push POST data to the CGI */ if (n > 0 && n < nc->recv_mbuf.len) { mg_send(dp->cgi_nc, hm->body.p, n); } mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len); } else { closesocket(fds[0]); send_http_error(nc, 500, "CGI failure"); } #ifndef _WIN32 closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */ #endif } #endif static int mg_get_month_index(const char *s) { static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; size_t i; for (i = 0; i < ARRAY_SIZE(month_names); i++) if (!strcmp(s, month_names[i])) return (int) i; return -1; } static int mg_num_leap_years(int year) { return year / 4 - year / 100 + year / 400; } /* Parse UTC date-time string, and return the corresponding time_t value. */ MG_INTERNAL time_t mg_parse_date_string(const char *datetime) { static const unsigned short days_before_month[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; char month_str[32]; int second, minute, hour, day, month, year, leap_days, days; time_t result = (time_t) 0; if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6)) && year > 1970 && (month = mg_get_month_index(month_str)) != -1) { leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970); year -= 1970; days = year * 365 + days_before_month[month] + (day - 1) + leap_days; result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; } return result; } MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) { struct mg_str *hdr; if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) { char etag[64]; construct_etag(etag, sizeof(etag), st); return mg_vcasecmp(hdr, etag) == 0; } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) { return st->st_mtime <= mg_parse_date_string(hdr->p); } else { return 0; } } static void mg_send_digest_auth_request(struct mg_connection *c, const char *domain) { mg_printf(c, "HTTP/1.1 401 Unauthorized\r\n" "WWW-Authenticate: Digest qop=\"auth\", " "realm=\"%s\", nonce=\"%lu\"\r\n" "Content-Length: 0\r\n\r\n", domain, (unsigned long) time(NULL)); } void mg_send_http_file(struct mg_connection *nc, char *path, size_t path_buf_len, struct http_message *hm, struct mg_serve_http_opts *opts) { int stat_result, is_directory, is_dav = is_dav_request(&hm->method); uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr); cs_stat_t st; DBG(("serving [%s]", path)); stat_result = mg_stat(path, &st); is_directory = !stat_result && S_ISDIR(st.st_mode); if (mg_check_ip_acl(opts->ip_acl, remote_ip) != 1) { /* Not allowed to connect */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (is_dav && opts->dav_document_root == NULL) { send_http_error(nc, 501, NULL); } else if (!is_authorized(hm, path, is_directory, opts->auth_domain, opts->global_auth_file, 1) || !is_authorized(hm, path, is_directory, opts->auth_domain, opts->per_directory_auth_file, 0)) { mg_send_digest_auth_request(nc, opts->auth_domain); } else if ((stat_result != 0 || is_file_hidden(path, opts)) && !is_dav) { mg_printf(nc, "%s", "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"); } else if (is_directory && path[strlen(path) - 1] != '/' && !is_dav) { mg_printf(nc, "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n" "Content-Length: 0\r\n\r\n", (int) hm->uri.len, hm->uri.p); #ifndef MG_DISABLE_DAV } else if (!mg_vcmp(&hm->method, "PROPFIND")) { handle_propfind(nc, path, &st, hm, opts); #ifndef MG_DISABLE_DAV_AUTH } else if (is_dav && (opts->dav_auth_file == NULL || !is_authorized(hm, path, is_directory, opts->auth_domain, opts->dav_auth_file, 1))) { mg_send_digest_auth_request(nc, opts->auth_domain); #endif } else if (!mg_vcmp(&hm->method, "MKCOL")) { handle_mkcol(nc, path, hm); } else if (!mg_vcmp(&hm->method, "DELETE")) { handle_delete(nc, path); } else if (!mg_vcmp(&hm->method, "PUT")) { handle_put(nc, path, hm); #endif } else if (S_ISDIR(st.st_mode) && !find_index_file(path, path_buf_len, opts->index_files, &st)) { if (strcmp(opts->enable_directory_listing, "yes") == 0) { #ifndef MG_DISABLE_DIRECTORY_LISTING send_directory_listing(nc, path, hm, opts); #else send_http_error(nc, 501, NULL); #endif } else { send_http_error(nc, 403, NULL); } } else if (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern), path) > 0) { #if !defined(MG_DISABLE_CGI) handle_cgi(nc, path, hm, opts); #else send_http_error(nc, 501, NULL); #endif /* MG_DISABLE_CGI */ } else if (mg_is_not_modified(hm, &st)) { send_http_error(nc, 304, "Not Modified"); } else { mg_send_http_file2(nc, path, &st, hm, opts); } } void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts) { char path[MG_MAX_PATH]; struct mg_str *hdr; if (send_port_based_redirect(nc, hm, &opts)) { return; } if (opts.document_root == NULL) { opts.document_root = "."; } if (opts.per_directory_auth_file == NULL) { opts.per_directory_auth_file = ".htpasswd"; } if (opts.enable_directory_listing == NULL) { opts.enable_directory_listing = "yes"; } if (opts.cgi_file_pattern == NULL) { opts.cgi_file_pattern = "**.cgi$|**.php$"; } if (opts.ssi_pattern == NULL) { opts.ssi_pattern = "**.shtml$|**.shtm$"; } if (opts.index_files == NULL) { opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php"; } uri_to_path(hm, path, sizeof(path), &opts); mg_send_http_file(nc, path, sizeof(path), hm, &opts); /* Close connection for non-keep-alive requests */ if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 || ((hdr = mg_get_http_header(hm, "Connection")) != NULL && mg_vcmp(hdr, "keep-alive") != 0)) { #if 0 nc->flags |= MG_F_SEND_AND_CLOSE; #endif } } #endif /* MG_DISABLE_FILESYSTEM */ struct mg_connection *mg_connect_http(struct mg_mgr *mgr, mg_event_handler_t ev_handler, const char *url, const char *extra_headers, const char *post_data) { struct mg_connection *nc = NULL; char *addr = NULL; const char *path = NULL; int use_ssl = 0, addr_len = 0, port_i = -1; if (memcmp(url, "http://", 7) == 0) { url += 7; } else if (memcmp(url, "https://", 8) == 0) { url += 8; use_ssl = 1; #ifndef MG_ENABLE_SSL return NULL; /* SSL is not enabled, cannot do HTTPS URLs */ #endif } while (*url != '\0') { addr = (char *) MG_REALLOC(addr, addr_len + 5 /* space for port too. */); if (addr == NULL) { DBG(("OOM")); return NULL; } if (*url == '/') { url++; break; } if (*url == ':') port_i = addr_len; addr[addr_len++] = *url; addr[addr_len] = '\0'; url++; } if (addr_len == 0) goto cleanup; if (port_i < 0) { port_i = addr_len; strcpy(addr + port_i, use_ssl ? ":443" : ":80"); } else { port_i = -1; } if (path == NULL) path = url; DBG(("%s %s", addr, path)); if ((nc = mg_connect(mgr, addr, ev_handler)) != NULL) { mg_set_protocol_http_websocket(nc); if (use_ssl) { #ifdef MG_ENABLE_SSL mg_set_ssl(nc, NULL, NULL); #endif } /* If the port was addred by us, restore the original host. */ if (port_i >= 0) addr[port_i] = '\0'; mg_printf(nc, "%s /%s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT "\r\n%s\r\n%s", post_data == NULL ? "GET" : "POST", path, addr, post_data == NULL ? 0 : strlen(post_data), extra_headers == NULL ? "" : extra_headers, post_data == NULL ? "" : post_data); } cleanup: MG_FREE(addr); return nc; } static size_t get_line_len(const char *buf, size_t buf_len) { size_t len = 0; while (len < buf_len && buf[len] != '\n') len++; return buf[len] == '\n' ? len + 1 : 0; } size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, size_t var_name_len, char *file_name, size_t file_name_len, const char **data, size_t *data_len) { static const char cd[] = "Content-Disposition: "; size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1; if (buf == NULL || buf_len <= 0) return 0; if ((hl = get_request_len(buf, buf_len)) <= 0) return 0; if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0; /* Get boundary length */ bl = get_line_len(buf, buf_len); /* Loop through headers, fetch variable name and file name */ var_name[0] = file_name[0] = '\0'; for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) { if (mg_ncasecmp(cd, buf + n, cdl) == 0) { struct mg_str header; header.p = buf + n + cdl; header.len = ll - (cdl + 2); mg_http_parse_header(&header, "name", var_name, var_name_len); mg_http_parse_header(&header, "filename", file_name, file_name_len); } } /* Scan through the body, search for terminating boundary */ for (pos = hl; pos + (bl - 2) < buf_len; pos++) { if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) { if (data_len != NULL) *data_len = (pos - 2) - hl; if (data != NULL) *data = buf + hl; return pos; } } return 0; } #endif /* MG_DISABLE_HTTP */ #ifdef NS_MODULE_LINES #line 1 "src/util.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "internal.h" */ const char *mg_skip(const char *s, const char *end, const char *delims, struct mg_str *v) { v->p = s; while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++; v->len = s - v->p; while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++; return s; } static int lowercase(const char *s) { return tolower(*(const unsigned char *) s); } int mg_ncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); return diff; } int mg_casecmp(const char *s1, const char *s2) { return mg_ncasecmp(s1, s2, (size_t) ~0); } int mg_vcasecmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2); if (r == 0) { return n1 - n2; } return r; } int mg_vcmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2); if (r == 0) { return n1 - n2; } return r; } #ifndef MG_DISABLE_FILESYSTEM int mg_stat(const char *path, cs_stat_t *st) { #ifdef _WIN32 wchar_t wpath[MAX_PATH_SIZE]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); return _wstati64(wpath, (struct _stati64 *) st); #else return stat(path, st); #endif } FILE *mg_fopen(const char *path, const char *mode) { #ifdef _WIN32 wchar_t wpath[MAX_PATH_SIZE], wmode[10]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); to_wchar(mode, wmode, ARRAY_SIZE(wmode)); return _wfopen(wpath, wmode); #else return fopen(path, mode); #endif } int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */ #ifdef _WIN32 wchar_t wpath[MAX_PATH_SIZE]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); return _wopen(wpath, flag, mode); #else return open(path, flag, mode); /* LCOV_EXCL_LINE */ #endif } #endif void mg_base64_encode(const unsigned char *src, int src_len, char *dst) { cs_base64_encode(src, src_len, dst); } int mg_base64_decode(const unsigned char *s, int len, char *dst) { return cs_base64_decode(s, len, dst); } #ifdef MG_ENABLE_THREADS void *mg_start_thread(void *(*f)(void *), void *p) { #ifdef _WIN32 return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p); #else pthread_t thread_id = (pthread_t) 0; pthread_attr_t attr; (void) pthread_attr_init(&attr); (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1 (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE); #endif pthread_create(&thread_id, &attr, f, p); pthread_attr_destroy(&attr); return (void *) thread_id; #endif } #endif /* MG_ENABLE_THREADS */ /* Set close-on-exec bit for a given socket. */ void mg_set_close_on_exec(sock_t sock) { #ifdef _WIN32 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); #else fcntl(sock, F_SETFD, FD_CLOEXEC); #endif } void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, int flags) { int is_v6; if (buf == NULL || len <= 0) return; buf[0] = '\0'; #if defined(MG_ENABLE_IPV6) is_v6 = sa->sa.sa_family == AF_INET6; #else is_v6 = 0; #endif if (flags & MG_SOCK_STRINGIFY_IP) { #if defined(MG_ENABLE_IPV6) const void *addr = NULL; char *start = buf; socklen_t capacity = len; if (!is_v6) { addr = &sa->sin.sin_addr; } else { addr = (void *) &sa->sin6.sin6_addr; if (flags & MG_SOCK_STRINGIFY_PORT) { *buf = '['; start++; capacity--; } } if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) { *buf = '\0'; } #elif defined(_WIN32) || defined(MG_ESP8266) /* Only Windoze Vista (and newer) have inet_ntop() */ strncpy(buf, inet_ntoa(sa->sin.sin_addr), len); #else inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len); #endif } if (flags & MG_SOCK_STRINGIFY_PORT) { int port = ntohs(sa->sin.sin_port); if (flags & MG_SOCK_STRINGIFY_IP) { snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s:%d", (is_v6 ? "]" : ""), port); } else { snprintf(buf, len, "%d", port); } } } void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, int flags) { union socket_address sa; memset(&sa, 0, sizeof(sa)); mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); mg_sock_addr_to_str(&sa, buf, len, flags); } #ifndef MG_DISABLE_HEXDUMP int mg_hexdump(const void *buf, int len, char *dst, int dst_len) { const unsigned char *p = (const unsigned char *) buf; char ascii[17] = ""; int i, idx, n = 0; for (i = 0; i < len; i++) { idx = i % 16; if (idx == 0) { if (i > 0) n += snprintf(dst + n, dst_len - n, " %s\n", ascii); n += snprintf(dst + n, dst_len - n, "%04x ", i); } n += snprintf(dst + n, dst_len - n, " %02x", p[i]); ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; ascii[idx + 1] = '\0'; } while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", " "); n += snprintf(dst + n, dst_len - n, " %s\n\n", ascii); return n; } #endif int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) { va_list ap_copy; int len; va_copy(ap_copy, ap); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" len = vsnprintf(*buf, size, fmt, ap_copy); #pragma GCC diagnostic pop va_end(ap_copy); if (len < 0) { /* eCos and Windows are not standard-compliant and return -1 when * the buffer is too small. Keep allocating larger buffers until we * succeed or out of memory. */ *buf = NULL; /* LCOV_EXCL_START */ while (len < 0) { MG_FREE(*buf); size *= 2; if ((*buf = (char *) MG_MALLOC(size)) == NULL) break; va_copy(ap_copy, ap); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" len = vsnprintf(*buf, size, fmt, ap_copy); #pragma GCC diagnostic pop va_end(ap_copy); } /* LCOV_EXCL_STOP */ } else if (len >= (int) size) { /* Standard-compliant code path. Allocate a buffer that is large enough. */ if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) { len = -1; /* LCOV_EXCL_LINE */ } else { /* LCOV_EXCL_LINE */ va_copy(ap_copy, ap); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" len = vsnprintf(*buf, len + 1, fmt, ap_copy); #pragma GCC diagnostic pop va_end(ap_copy); } } return len; } #if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP) void mg_hexdump_connection(struct mg_connection *nc, const char *path, const void *buf, int num_bytes, int ev) { FILE *fp = NULL; char *hexbuf, src[60], dst[60]; int buf_size = num_bytes * 5 + 100; if (strcmp(path, "-") == 0) { fp = stdout; } else if (strcmp(path, "--") == 0) { fp = stderr; #ifndef MG_DISABLE_FILESYSTEM } else { fp = fopen(path, "a"); #endif } if (fp == NULL) return; mg_conn_addr_to_str(nc, src, sizeof(src), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT | MG_SOCK_STRINGIFY_REMOTE); fprintf( fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL), (void*) nc, src, ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND ? "->" : ev == MG_EV_ACCEPT ? "<A" : ev == MG_EV_CONNECT ? "C>" : "XX", dst, num_bytes); if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) { mg_hexdump(buf, num_bytes, hexbuf, buf_size); fprintf(fp, "%s", hexbuf); MG_FREE(hexbuf); } if (fp != stdin && fp != stdout) fclose(fp); } #endif int mg_is_big_endian(void) { static const int n = 1; /* TODO(mkm) use compiletime check with 4-byte char literal */ return ((char *) &n)[0] == 0; } const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, struct mg_str *eq_val) { if (list == NULL || *list == '\0') { /* End of the list */ list = NULL; } else { val->p = list; if ((list = strchr(val->p, ',')) != NULL) { /* Comma found. Store length and shift the list ptr */ val->len = list - val->p; list++; } else { /* This value is the last one */ list = val->p + strlen(val->p); val->len = list - val->p; } if (eq_val != NULL) { /* Value has form "x=y", adjust pointers and lengths */ /* so that val points to "x", and eq_val points to "y". */ eq_val->len = 0; eq_val->p = (const char *) memchr(val->p, '=', val->len); if (eq_val->p != NULL) { eq_val->p++; /* Skip over '=' character */ eq_val->len = val->p + val->len - eq_val->p; val->len = (eq_val->p - val->p) - 1; } } } return list; } int mg_match_prefix(const char *pattern, int pattern_len, const char *str) { const char *or_str; int len, res, i = 0, j = 0; if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) { res = mg_match_prefix(pattern, or_str - pattern, str); return res > 0 ? res : mg_match_prefix( or_str + 1, (pattern + pattern_len) - (or_str + 1), str); } for (; i < pattern_len; i++, j++) { if (pattern[i] == '?' && str[j] != '\0') { continue; } else if (pattern[i] == '$') { return str[j] == '\0' ? j : -1; } else if (pattern[i] == '*') { i++; if (pattern[i] == '*') { i++; len = (int) strlen(str + j); } else { len = (int) strcspn(str + j, "/"); } if (i == pattern_len) { return j + len; } do { res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len); } while (res == -1 && len-- > 0); return res == -1 ? -1 : j + res + len; } else if (lowercase(&pattern[i]) != lowercase(&str[j])) { return -1; } } return j; } #ifdef NS_MODULE_LINES #line 1 "src/json-rpc.c" /**/ #endif /* Copyright (c) 2014 Cesanta Software Limited */ /* All rights reserved */ #ifndef MG_DISABLE_JSON_RPC /* Amalgamated: #include "internal.h" */ int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req, const char *result_fmt, ...) { static const struct json_token null_tok = {"null", 4, 0, JSON_TYPE_NULL}; const struct json_token *id = req->id == NULL ? &null_tok : req->id; va_list ap; int n = 0; n += json_emit(buf + n, len - n, "{s:s,s:", "jsonrpc", "2.0", "id"); if (id->type == JSON_TYPE_STRING) { n += json_emit_quoted_str(buf + n, len - n, id->ptr, id->len); } else { n += json_emit_unquoted_str(buf + n, len - n, id->ptr, id->len); } n += json_emit(buf + n, len - n, ",s:", "result"); va_start(ap, result_fmt); n += json_emit_va(buf + n, len - n, result_fmt, ap); va_end(ap); n += json_emit(buf + n, len - n, "}"); return n; } int mg_rpc_create_request(char *buf, int len, const char *method, const char *id, const char *params_fmt, ...) { va_list ap; int n = 0; n += json_emit(buf + n, len - n, "{s:s,s:s,s:s,s:", "jsonrpc", "2.0", "id", id, "method", method, "params"); va_start(ap, params_fmt); n += json_emit_va(buf + n, len - n, params_fmt, ap); va_end(ap); n += json_emit(buf + n, len - n, "}"); return n; } int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req, int code, const char *message, const char *fmt, ...) { va_list ap; int n = 0; n += json_emit(buf + n, len - n, "{s:s,s:V,s:{s:i,s:s,s:", "jsonrpc", "2.0", "id", req->id == NULL ? "null" : req->id->ptr, req->id == NULL ? 4 : req->id->len, "error", "code", code, "message", message, "data"); va_start(ap, fmt); n += json_emit_va(buf + n, len - n, fmt, ap); va_end(ap); n += json_emit(buf + n, len - n, "}}"); return n; } int mg_rpc_create_std_error(char *buf, int len, struct mg_rpc_request *req, int code) { const char *message = NULL; switch (code) { case JSON_RPC_PARSE_ERROR: message = "parse error"; break; case JSON_RPC_INVALID_REQUEST_ERROR: message = "invalid request"; break; case JSON_RPC_METHOD_NOT_FOUND_ERROR: message = "method not found"; break; case JSON_RPC_INVALID_PARAMS_ERROR: message = "invalid parameters"; break; case JSON_RPC_SERVER_ERROR: message = "server error"; break; default: message = "unspecified error"; break; } return mg_rpc_create_error(buf, len, req, code, message, "N"); } int mg_rpc_dispatch(const char *buf, int len, char *dst, int dst_len, const char **methods, mg_rpc_handler_t *handlers) { struct json_token tokens[200]; struct mg_rpc_request req; int i, n; memset(&req, 0, sizeof(req)); n = parse_json(buf, len, tokens, sizeof(tokens) / sizeof(tokens[0])); if (n <= 0) { int err_code = (n == JSON_STRING_INVALID) ? JSON_RPC_PARSE_ERROR : JSON_RPC_SERVER_ERROR; return mg_rpc_create_std_error(dst, dst_len, &req, err_code); } req.message = tokens; req.id = find_json_token(tokens, "id"); req.method = find_json_token(tokens, "method"); req.params = find_json_token(tokens, "params"); if (req.id == NULL || req.method == NULL) { return mg_rpc_create_std_error(dst, dst_len, &req, JSON_RPC_INVALID_REQUEST_ERROR); } for (i = 0; methods[i] != NULL; i++) { int mlen = strlen(methods[i]); if (mlen == req.method->len && memcmp(methods[i], req.method->ptr, mlen) == 0) break; } if (methods[i] == NULL) { return mg_rpc_create_std_error(dst, dst_len, &req, JSON_RPC_METHOD_NOT_FOUND_ERROR); } return handlers[i](dst, dst_len, &req); } int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks, int max_toks, struct mg_rpc_reply *rep, struct mg_rpc_error *er) { int n = parse_json(buf, len, toks, max_toks); memset(rep, 0, sizeof(*rep)); memset(er, 0, sizeof(*er)); if (n > 0) { if ((rep->result = find_json_token(toks, "result")) != NULL) { rep->message = toks; rep->id = find_json_token(toks, "id"); } else { er->message = toks; er->id = find_json_token(toks, "id"); er->error_code = find_json_token(toks, "error.code"); er->error_message = find_json_token(toks, "error.message"); er->error_data = find_json_token(toks, "error.data"); } } return n; } #endif /* MG_DISABLE_JSON_RPC */ #ifdef NS_MODULE_LINES #line 1 "src/mqtt.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef MG_DISABLE_MQTT /* Amalgamated: #include "internal.h" */ static int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { uint8_t header; int cmd; size_t len = 0; int var_len = 0; char *vlen = &io->buf[1]; if (io->len < 2) return -1; header = io->buf[0]; cmd = header >> 4; /* decode mqtt variable length */ do { len += (*vlen & 127) << 7 * (vlen - &io->buf[1]); } while ((*vlen++ & 128) != 0 && ((size_t)(vlen - io->buf) <= io->len)); if (io->len < (size_t)(len - 1)) return -1; mbuf_remove(io, 1 + (vlen - &io->buf[1])); mm->cmd = cmd; mm->qos = MG_MQTT_GET_QOS(header); switch (cmd) { case MG_MQTT_CMD_CONNECT: /* TODO(mkm): parse keepalive and will */ break; case MG_MQTT_CMD_CONNACK: mm->connack_ret_code = io->buf[1]; var_len = 2; break; case MG_MQTT_CMD_PUBACK: case MG_MQTT_CMD_PUBREC: case MG_MQTT_CMD_PUBREL: case MG_MQTT_CMD_PUBCOMP: case MG_MQTT_CMD_SUBACK: mm->message_id = ntohs(*(uint16_t *) io->buf); var_len = 2; break; case MG_MQTT_CMD_PUBLISH: { uint16_t topic_len = ntohs(*(uint16_t *) io->buf); mm->topic = (char *) MG_MALLOC(topic_len + 1); mm->topic[topic_len] = 0; strncpy(mm->topic, io->buf + 2, topic_len); var_len = topic_len + 2; if (MG_MQTT_GET_QOS(header) > 0) { mm->message_id = ntohs(*(uint16_t *) io->buf); var_len += 2; } } break; case MG_MQTT_CMD_SUBSCRIBE: /* * topic expressions are left in the payload and can be parsed with * `mg_mqtt_next_subscribe_topic` */ mm->message_id = ntohs(*(uint16_t *) io->buf); var_len = 2; break; default: printf("TODO: UNHANDLED COMMAND %d\n", cmd); break; } mbuf_remove(io, var_len); return len - var_len; } static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) { int len; struct mbuf *io = &nc->recv_mbuf; struct mg_mqtt_message mm; memset(&mm, 0, sizeof(mm)); nc->handler(nc, ev, ev_data); switch (ev) { case MG_EV_RECV: len = parse_mqtt(io, &mm); if (len == -1) break; /* not fully buffered */ mm.payload.p = io->buf; mm.payload.len = len; nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm); if (mm.topic) { MG_FREE(mm.topic); } mbuf_remove(io, mm.payload.len); break; } } void mg_set_protocol_mqtt(struct mg_connection *nc) { nc->proto_handler = mqtt_handler; } void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { static struct mg_send_mqtt_handshake_opts opts; mg_send_mqtt_handshake_opt(nc, client_id, opts); } void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, struct mg_send_mqtt_handshake_opts opts) { uint8_t header = MG_MQTT_CMD_CONNECT << 4; uint8_t rem_len; uint16_t keep_alive; uint16_t client_id_len; /* * 9: version_header(len, magic_string, version_number), 1: flags, 2: * keep-alive timer, * 2: client_identifier_len, n: client_id */ rem_len = 9 + 1 + 2 + 2 + strlen(client_id); mg_send(nc, &header, 1); mg_send(nc, &rem_len, 1); mg_send(nc, "\00\06MQIsdp\03", 9); mg_send(nc, &opts.flags, 1); if (opts.keep_alive == 0) { opts.keep_alive = 60; } keep_alive = htons(opts.keep_alive); mg_send(nc, &keep_alive, 2); client_id_len = htons(strlen(client_id)); mg_send(nc, &client_id_len, 2); mg_send(nc, client_id, strlen(client_id)); } static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd, uint8_t flags, size_t len) { size_t off = nc->send_mbuf.len - len; uint8_t header = cmd << 4 | (uint8_t) flags; uint8_t buf[1 + sizeof(size_t)]; uint8_t *vlen = &buf[1]; assert(nc->send_mbuf.len >= len); buf[0] = header; /* mqtt variable length encoding */ do { *vlen = len % 0x80; len /= 0x80; if (len > 0) *vlen |= 0x80; vlen++; } while (len > 0); mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf); } void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len) { size_t old_len = nc->send_mbuf.len; uint16_t topic_len = htons(strlen(topic)); uint16_t message_id_net = htons(message_id); mg_send(nc, &topic_len, 2); mg_send(nc, topic, strlen(topic)); if (MG_MQTT_GET_QOS(flags) > 0) { mg_send(nc, &message_id_net, 2); } mg_send(nc, data, len); mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags, nc->send_mbuf.len - old_len); } void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id) { size_t old_len = nc->send_mbuf.len; uint16_t message_id_n = htons(message_id); size_t i; mg_send(nc, (char *) &message_id_n, 2); for (i = 0; i < topics_len; i++) { uint16_t topic_len_n = htons(strlen(topics[i].topic)); mg_send(nc, &topic_len_n, 2); mg_send(nc, topics[i].topic, strlen(topics[i].topic)); mg_send(nc, &topics[i].qos, 1); } mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), nc->send_mbuf.len - old_len); } int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos) { unsigned char *buf = (unsigned char *) msg->payload.p + pos; if ((size_t) pos >= msg->payload.len) { return -1; } topic->len = buf[0] << 8 | buf[1]; topic->p = (char *) buf + 2; *qos = buf[2 + topic->len]; return pos + 2 + topic->len + 1; } void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id) { size_t old_len = nc->send_mbuf.len; uint16_t message_id_n = htons(message_id); size_t i; mg_send(nc, (char *) &message_id_n, 2); for (i = 0; i < topics_len; i++) { uint16_t topic_len_n = htons(strlen(topics[i])); mg_send(nc, &topic_len_n, 2); mg_send(nc, topics[i], strlen(topics[i])); } mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), nc->send_mbuf.len - old_len); } void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { uint8_t unused = 0; mg_send(nc, &unused, 1); mg_send(nc, &return_code, 1); mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); } /* * Sends a command which contains only a `message_id` and a QoS level of 1. * * Helper function. */ static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, uint16_t message_id) { uint16_t message_id_net = htons(message_id); mg_send(nc, &message_id_net, 2); mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2); } void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); } void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); } void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); } void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); } void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, uint16_t message_id) { size_t i; uint16_t message_id_net = htons(message_id); mg_send(nc, &message_id_net, 2); for (i = 0; i < qoss_len; i++) { mg_send(nc, &qoss[i], 1); } mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); } void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); } void mg_mqtt_ping(struct mg_connection *nc) { mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); } void mg_mqtt_pong(struct mg_connection *nc) { mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); } void mg_mqtt_disconnect(struct mg_connection *nc) { mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); } #endif /* MG_DISABLE_MQTT */ #ifdef NS_MODULE_LINES #line 1 "src/mqtt-broker.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "internal.h" */ #ifdef MG_ENABLE_MQTT_BROKER static void mg_mqtt_session_init(struct mg_mqtt_broker *brk, struct mg_mqtt_session *s, struct mg_connection *nc) { s->brk = brk; s->subscriptions = NULL; s->num_subscriptions = 0; s->nc = nc; } static void mg_mqtt_add_session(struct mg_mqtt_session *s) { s->next = s->brk->sessions; s->brk->sessions = s; s->prev = NULL; if (s->next != NULL) s->next->prev = s; } static void mg_mqtt_remove_session(struct mg_mqtt_session *s) { if (s->prev == NULL) s->brk->sessions = s->next; if (s->prev) s->prev->next = s->next; if (s->next) s->next->prev = s->prev; } static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) { size_t i; for (i = 0; i < s->num_subscriptions; i++) { MG_FREE((void *) s->subscriptions[i].topic); } MG_FREE(s->subscriptions); MG_FREE(s); } static void mg_mqtt_close_session(struct mg_mqtt_session *s) { mg_mqtt_remove_session(s); mg_mqtt_destroy_session(s); } void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) { brk->sessions = NULL; brk->user_data = user_data; } static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk, struct mg_connection *nc) { struct mg_mqtt_session *s = (struct mg_mqtt_session *) malloc(sizeof *s); if (s == NULL) { /* LCOV_EXCL_START */ mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE); return; /* LCOV_EXCL_STOP */ } /* TODO(mkm): check header (magic and version) */ mg_mqtt_session_init(brk, s, nc); s->user_data = nc->user_data; nc->user_data = s; mg_mqtt_add_session(s); mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED); } static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc, struct mg_mqtt_message *msg) { struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data; uint8_t qoss[512]; size_t qoss_len = 0; struct mg_str topic; uint8_t qos; int pos; struct mg_mqtt_topic_expression *te; for (pos = 0; (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) { qoss[qoss_len++] = qos; } ss->subscriptions = (struct mg_mqtt_topic_expression *) realloc( ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len); for (pos = 0; (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1; ss->num_subscriptions++) { te = &ss->subscriptions[ss->num_subscriptions]; te->topic = (char *) malloc(topic.len + 1); te->qos = qos; strncpy((char *) te->topic, topic.p, topic.len + 1); } mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id); } /* * Matches a topic against a topic expression * * See http://goo.gl/iWk21X * * Returns 1 if it matches; 0 otherwise. */ static int mg_mqtt_match_topic_expression(const char *exp, const char *topic) { /* TODO(mkm): implement real matching */ int len = strlen(exp); if (strchr(exp, '#')) { len -= 2; } return strncmp(exp, topic, len) == 0; } static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk, struct mg_mqtt_message *msg) { struct mg_mqtt_session *s; size_t i; for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { for (i = 0; i < s->num_subscriptions; i++) { if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic, msg->topic)) { mg_mqtt_publish(s->nc, msg->topic, 0, 0, msg->payload.p, msg->payload.len); break; } } } } void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) { struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data; struct mg_mqtt_broker *brk; if (nc->listener) { brk = (struct mg_mqtt_broker *) nc->listener->user_data; } else { brk = (struct mg_mqtt_broker *) nc->user_data; } switch (ev) { case MG_EV_ACCEPT: mg_set_protocol_mqtt(nc); break; case MG_EV_MQTT_CONNECT: mg_mqtt_broker_handle_connect(brk, nc); break; case MG_EV_MQTT_SUBSCRIBE: mg_mqtt_broker_handle_subscribe(nc, msg); break; case MG_EV_MQTT_PUBLISH: mg_mqtt_broker_handle_publish(brk, msg); break; case MG_EV_CLOSE: if (nc->listener) { mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data); } break; } } struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, struct mg_mqtt_session *s) { return s == NULL ? brk->sessions : s->next; } #endif /* MG_ENABLE_MQTT_BROKER */ #ifdef NS_MODULE_LINES #line 1 "src/dns.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef MG_DISABLE_DNS /* Amalgamated: #include "internal.h" */ static int mg_dns_tid = 0xa0; struct mg_dns_header { uint16_t transaction_id; uint16_t flags; uint16_t num_questions; uint16_t num_answers; uint16_t num_authority_prs; uint16_t num_other_prs; }; struct mg_dns_resource_record *mg_dns_next_record( struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev) { struct mg_dns_resource_record *rr; for (rr = (prev == NULL ? msg->answers : prev + 1); rr - msg->answers < msg->num_answers; rr++) { if (rr->rtype == query) { return rr; } } return NULL; } int mg_dns_parse_record_data(struct mg_dns_message *msg, struct mg_dns_resource_record *rr, void *data, size_t data_len) { switch (rr->rtype) { case MG_DNS_A_RECORD: if (data_len < sizeof(struct in_addr)) { return -1; } if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) { return -1; } memcpy(data, rr->rdata.p, data_len); return 0; #ifdef MG_ENABLE_IPV6 case MG_DNS_AAAA_RECORD: if (data_len < sizeof(struct in6_addr)) { return -1; /* LCOV_EXCL_LINE */ } memcpy(data, rr->rdata.p, data_len); return 0; #endif case MG_DNS_CNAME_RECORD: mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len); return 0; } return -1; } int mg_dns_insert_header(struct mbuf *io, size_t pos, struct mg_dns_message *msg) { struct mg_dns_header header; memset(&header, 0, sizeof(header)); header.transaction_id = msg->transaction_id; header.flags = htons(msg->flags); header.num_questions = htons(msg->num_questions); header.num_answers = htons(msg->num_answers); return mbuf_insert(io, pos, &header, sizeof(header)); } int mg_dns_copy_body(struct mbuf *io, struct mg_dns_message *msg) { return mbuf_append(io, msg->pkt.p + sizeof(struct mg_dns_header), msg->pkt.len - sizeof(struct mg_dns_header)); } static int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) { const char *s; unsigned char n; size_t pos = io->len; do { if ((s = strchr(name, '.')) == NULL) { s = name + len; } if (s - name > 127) { return -1; /* TODO(mkm) cover */ } n = s - name; /* chunk length */ mbuf_append(io, &n, 1); /* send length */ mbuf_append(io, name, n); if (*s == '.') { n++; } name += n; len -= n; } while (*s != '\0'); mbuf_append(io, "\0", 1); /* Mark end of host name */ return io->len - pos; } int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, const char *name, size_t nlen, const void *rdata, size_t rlen) { size_t pos = io->len; uint16_t u16; uint32_t u32; if (rr->kind == MG_DNS_INVALID_RECORD) { return -1; /* LCOV_EXCL_LINE */ } if (mg_dns_encode_name(io, name, nlen) == -1) { return -1; } u16 = htons(rr->rtype); mbuf_append(io, &u16, 2); u16 = htons(rr->rclass); mbuf_append(io, &u16, 2); if (rr->kind == MG_DNS_ANSWER) { u32 = htonl(rr->ttl); mbuf_append(io, &u32, 4); if (rr->rtype == MG_DNS_CNAME_RECORD) { int clen; /* fill size after encoding */ size_t off = io->len; mbuf_append(io, &u16, 2); if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) { return -1; } u16 = clen; io->buf[off] = u16 >> 8; io->buf[off + 1] = u16 & 0xff; } else { u16 = htons(rlen); mbuf_append(io, &u16, 2); mbuf_append(io, rdata, rlen); } } return io->len - pos; } void mg_send_dns_query(struct mg_connection *nc, const char *name, int query_type) { struct mg_dns_message *msg = (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg)); struct mbuf pkt; struct mg_dns_resource_record *rr = &msg->questions[0]; DBG(("%s %d", name, query_type)); mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */); msg->transaction_id = ++mg_dns_tid; msg->flags = 0x100; msg->num_questions = 1; mg_dns_insert_header(&pkt, 0, msg); rr->rtype = query_type; rr->rclass = 1; /* Class: inet */ rr->kind = MG_DNS_QUESTION; if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) { /* TODO(mkm): return an error code */ goto cleanup; /* LCOV_EXCL_LINE */ } /* TCP DNS requires messages to be prefixed with len */ if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons(pkt.len); mbuf_insert(&pkt, 0, &len, 2); } mg_send(nc, pkt.buf, pkt.len); mbuf_free(&pkt); cleanup: MG_FREE(msg); } static unsigned char *mg_parse_dns_resource_record( unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, int reply) { unsigned char *name = data; int chunk_len, data_len; while (data < end && (chunk_len = *data)) { if (((unsigned char *) data)[0] & 0xc0) { data += 1; break; } data += chunk_len + 1; } rr->name.p = (char *) name; rr->name.len = data - name + 1; data++; if (data > end - 4) { return data; } rr->rtype = data[0] << 8 | data[1]; data += 2; rr->rclass = data[0] << 8 | data[1]; data += 2; rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION; if (reply) { if (data >= end - 6) { return data; } rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 | data[2] << 8 | data[3]; data += 4; data_len = *data << 8 | *(data + 1); data += 2; rr->rdata.p = (char *) data; rr->rdata.len = data_len; data += data_len; } return data; } int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) { struct mg_dns_header *header = (struct mg_dns_header *) buf; unsigned char *data = (unsigned char *) buf + sizeof(*header); unsigned char *end = (unsigned char *) buf + len; int i; msg->pkt.p = buf; msg->pkt.len = len; if (len < (int) sizeof(*header)) { return -1; /* LCOV_EXCL_LINE */ } msg->transaction_id = header->transaction_id; msg->flags = ntohs(header->flags); msg->num_questions = ntohs(header->num_questions); msg->num_answers = ntohs(header->num_answers); for (i = 0; i < msg->num_questions && i < (int) ARRAY_SIZE(msg->questions); i++) { data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0); } for (i = 0; i < msg->num_answers && i < (int) ARRAY_SIZE(msg->answers); i++) { data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1); } return 0; } size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, char *dst, int dst_len) { int chunk_len; char *old_dst = dst; const unsigned char *data = (unsigned char *) name->p; const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len; if (data >= end) { return 0; } while ((chunk_len = *data++)) { int leeway = dst_len - (dst - old_dst); if (data >= end) { return 0; } if (chunk_len & 0xc0) { uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0]; if (off >= msg->pkt.len) { return 0; } data = (unsigned char *) msg->pkt.p + off; continue; } if (chunk_len > leeway) { chunk_len = leeway; } if (data + chunk_len >= end) { return 0; } memcpy(dst, data, chunk_len); data += chunk_len; dst += chunk_len; leeway -= chunk_len; if (leeway == 0) { return dst - old_dst; } *dst++ = '.'; } if (dst != old_dst) { *--dst = 0; } return dst - old_dst; } static void dns_handler(struct mg_connection *nc, int ev, void *ev_data) { struct mbuf *io = &nc->recv_mbuf; struct mg_dns_message msg; /* Pass low-level events to the user handler */ nc->handler(nc, ev, ev_data); switch (ev) { case MG_EV_RECV: if (!(nc->flags & MG_F_UDP)) { mbuf_remove(&nc->recv_mbuf, 2); } if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) { /* reply + recursion allowed + format error */ memset(&msg, 0, sizeof(msg)); msg.flags = 0x8081; mg_dns_insert_header(io, 0, &msg); if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons(io->len); mbuf_insert(io, 0, &len, 2); } mg_send(nc, io->buf, io->len); } else { /* Call user handler with parsed message */ nc->handler(nc, MG_DNS_MESSAGE, &msg); } mbuf_remove(io, io->len); break; } } void mg_set_protocol_dns(struct mg_connection *nc) { nc->proto_handler = dns_handler; } #endif /* MG_DISABLE_DNS */ #ifdef NS_MODULE_LINES #line 1 "src/dns-server.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifdef MG_ENABLE_DNS_SERVER /* Amalgamated: #include "internal.h" */ struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, struct mg_dns_message *msg) { struct mg_dns_reply rep; rep.msg = msg; rep.io = io; rep.start = io->len; /* reply + recursion allowed */ msg->flags |= 0x8080; mg_dns_copy_body(io, msg); msg->num_answers = 0; return rep; } void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) { size_t sent = r->io->len - r->start; mg_dns_insert_header(r->io, r->start, r->msg); if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons(sent); mbuf_insert(r->io, r->start, &len, 2); } if (&nc->send_mbuf != r->io) { mg_send(nc, r->io->buf + r->start, r->io->len - r->start); r->io->len = r->start; } } int mg_dns_reply_record(struct mg_dns_reply *reply, struct mg_dns_resource_record *question, const char *name, int rtype, int ttl, const void *rdata, size_t rdata_len) { struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg; char rname[512]; struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers]; if (msg->num_answers >= MG_MAX_DNS_ANSWERS) { return -1; /* LCOV_EXCL_LINE */ } if (name == NULL) { name = rname; rname[511] = 0; mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1); } *ans = *question; ans->kind = MG_DNS_ANSWER; ans->rtype = rtype; ans->ttl = ttl; if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata, rdata_len) == -1) { return -1; /* LCOV_EXCL_LINE */ }; msg->num_answers++; return 0; } #endif /* MG_ENABLE_DNS_SERVER */ #ifdef NS_MODULE_LINES #line 1 "src/resolv.c" /**/ #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef MG_DISABLE_RESOLVER /* Amalgamated: #include "internal.h" */ #ifndef MG_DEFAULT_NAMESERVER #define MG_DEFAULT_NAMESERVER "8.8.8.8" #endif static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53"; MG_INTERNAL char mg_dns_server[256]; struct mg_resolve_async_request { char name[1024]; int query; mg_resolve_callback_t callback; void *data; time_t timeout; int max_retries; /* state */ time_t last_time; int retries; }; /* * Find what nameserver to use. * * Return 0 if OK, -1 if error */ static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) { int ret = -1; #ifdef _WIN32 int i; LONG err; HKEY hKey, hSub; char subkey[512], value[128], *key = "SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces"; if ((err = RegOpenKey(HKEY_LOCAL_MACHINE, key, &hKey)) != ERROR_SUCCESS) { fprintf(stderr, "cannot open reg key %s: %d\n", key, err); ret = -1; } else { for (ret = -1, i = 0; RegEnumKey(hKey, i, subkey, sizeof(subkey)) == ERROR_SUCCESS; i++) { DWORD type, len = sizeof(value); if (RegOpenKey(hKey, subkey, &hSub) == ERROR_SUCCESS && (RegQueryValueEx(hSub, "NameServer", 0, &type, (void *) value, &len) == ERROR_SUCCESS || RegQueryValueEx(hSub, "DhcpNameServer", 0, &type, (void *) value, &len) == ERROR_SUCCESS)) { /* * See https://github.com/cesanta/mongoose/issues/176 * The value taken from the registry can be empty, a single * IP address, or multiple IP addresses separated by comma. * If it's empty, check the next interface. * If it's multiple IP addresses, take the first one. */ char *comma = strchr(value, ','); if (value[0] == '\0') { continue; } if (comma != NULL) { *comma = '\0'; } snprintf(name, name_len, "udp://%s:53", value); ret = 0; RegCloseKey(hSub); break; } } RegCloseKey(hKey); } #elif !defined(MG_DISABLE_FILESYSTEM) FILE *fp; char line[512]; if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) { ret = -1; } else { /* Try to figure out what nameserver to use */ for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) { char buf[256]; if (sscanf(line, "nameserver %255[^\n\t #]s", buf) == 1) { snprintf(name, name_len, "udp://%s:53", buf); ret = 0; break; } } (void) fclose(fp); } #else snprintf(name, name_len, "%s", mg_default_dns_server); #endif /* _WIN32 */ return ret; } int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) { #ifndef MG_DISABLE_FILESYSTEM /* TODO(mkm) cache /etc/hosts */ FILE *fp; char line[1024]; char *p; char alias[256]; unsigned int a, b, c, d; int len = 0; if ((fp = fopen("/etc/hosts", "r")) == NULL) { return -1; } for (; fgets(line, sizeof(line), fp) != NULL;) { if (line[0] == '#') continue; if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) { /* TODO(mkm): handle ipv6 */ continue; } for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) { if (strcmp(alias, name) == 0) { usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d); fclose(fp); return 0; } } } fclose(fp); #endif return -1; } static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) { time_t now = time(NULL); struct mg_resolve_async_request *req; struct mg_dns_message *msg; DBG(("ev=%d", ev)); req = (struct mg_resolve_async_request *) nc->user_data; switch (ev) { case MG_EV_CONNECT: case MG_EV_POLL: if (req->retries > req->max_retries) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; } if (now - req->last_time >= req->timeout) { mg_send_dns_query(nc, req->name, req->query); req->last_time = now; req->retries++; } break; case MG_EV_RECV: msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg)); if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 && msg->num_answers > 0) { req->callback(msg, req->data); nc->user_data = NULL; MG_FREE(req); } MG_FREE(msg); nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_SEND: /* * If a send error occurs, prevent closing of the connection by the core. * We will retry after timeout. */ nc->flags &= ~MG_F_CLOSE_IMMEDIATELY; mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len); break; case MG_EV_CLOSE: /* If we got here with request still not done, fire an error callback. */ if (req != NULL) { req->callback(NULL, req->data); nc->user_data = NULL; MG_FREE(req); } break; } } int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data) { struct mg_resolve_async_opts opts; memset(&opts, 0, sizeof(opts)); return mg_resolve_async_opt(mgr, name, query, cb, data, opts); } int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data, struct mg_resolve_async_opts opts) { struct mg_resolve_async_request *req; struct mg_connection *dns_nc; const char *nameserver = opts.nameserver_url; DBG(("%s %d", name, query)); /* resolve with DNS */ req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req)); if (req == NULL) { return -1; } strncpy(req->name, name, sizeof(req->name)); req->query = query; req->callback = cb; req->data = data; /* TODO(mkm): parse defaults out of resolve.conf */ req->max_retries = opts.max_retries ? opts.max_retries : 2; req->timeout = opts.timeout ? opts.timeout : 5; /* Lazily initialize dns server */ if (nameserver == NULL && mg_dns_server[0] == '\0' && mg_get_ip_address_of_nameserver(mg_dns_server, sizeof(mg_dns_server)) == -1) { strncpy(mg_dns_server, mg_default_dns_server, sizeof(mg_dns_server)); } if (nameserver == NULL) { nameserver = mg_dns_server; } dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh); if (dns_nc == NULL) { free(req); return -1; } dns_nc->user_data = req; return 0; } #endif /* MG_DISABLE_RESOLVE */ #ifdef NS_MODULE_LINES #line 1 "src/coap.c" /**/ #endif /* * Copyright (c) 2015 Cesanta Software Limited * All rights reserved * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, 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. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ /* Amalgamated: #include "internal.h" */ #ifdef MG_ENABLE_COAP void mg_coap_free_options(struct mg_coap_message *cm) { while (cm->options != NULL) { struct mg_coap_option *next = cm->options->next; MG_FREE(cm->options); cm->options = next; } } struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, uint32_t number, char *value, size_t len) { struct mg_coap_option *new_option = (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option)); new_option->number = number; new_option->value.p = value; new_option->value.len = len; if (cm->options == NULL) { cm->options = cm->optiomg_tail = new_option; } else { /* * A very simple attention to help clients to compose options: * CoAP wants to see options ASC ordered. * Could be change by using sort in coap_compose */ if (cm->optiomg_tail->number <= new_option->number) { /* if option is already ordered just add it */ cm->optiomg_tail = cm->optiomg_tail->next = new_option; } else { /* looking for appropriate position */ struct mg_coap_option *current_opt = cm->options; struct mg_coap_option *prev_opt = 0; while (current_opt != NULL) { if (current_opt->number > new_option->number) { break; } prev_opt = current_opt; current_opt = current_opt->next; } if (prev_opt != NULL) { prev_opt->next = new_option; new_option->next = current_opt; } else { /* insert new_option to the beginning */ new_option->next = cm->options; cm->options = new_option; } } } return new_option; } /* * Fills CoAP header in mg_coap_message. * * Helper function. */ static char *coap_parse_header(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { if (io->len < sizeof(uint32_t)) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; return NULL; } /* * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version * number. Implementations of this specification MUST set this field * to 1 (01 binary). Other values are reserved for future versions. * Messages with unknown version numbers MUST be silently ignored. */ if (((uint8_t) *ptr >> 6) != 1) { cm->flags |= MG_COAP_IGNORE; return NULL; } /* * Type (T): 2-bit unsigned integer. Indicates if this message is of * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or * Reset (3). */ cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4; cm->flags |= MG_COAP_MSG_TYPE_FIELD; /* * Token Length (TKL): 4-bit unsigned integer. Indicates the length of * the variable-length Token field (0-8 bytes). Lengths 9-15 are * reserved, MUST NOT be sent, and MUST be processed as a message * format error. */ cm->token.len = *ptr & 0x0F; if (cm->token.len > 8) { cm->flags |= MG_COAP_FORMAT_ERROR; return NULL; } ptr++; /* * Code: 8-bit unsigned integer, split into a 3-bit class (most * significant bits) and a 5-bit detail (least significant bits) */ cm->code_class = (uint8_t) *ptr >> 5; cm->code_detail = *ptr & 0x1F; cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD); ptr++; /* Message ID: 16-bit unsigned integer in network byte order. */ cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1); cm->flags |= MG_COAP_MSG_ID_FIELD; ptr += 2; return ptr; } /* * Fills token information in mg_coap_message. * * Helper function. */ static char *coap_get_token(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { if (cm->token.len != 0) { if (ptr + cm->token.len > io->buf + io->len) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; return NULL; } else { cm->token.p = ptr; ptr += cm->token.len; cm->flags |= MG_COAP_TOKEN_FIELD; } } return ptr; } /* * Returns Option Delta or Length. * * Helper function. */ static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) { int ret = 0; if (*opt_info == 13) { /* * 13: An 8-bit unsigned integer follows the initial byte and * indicates the Option Delta/Length minus 13. */ if (ptr < io->buf + io->len) { *opt_info = (uint8_t) *ptr + 13; ret = sizeof(uint8_t); } else { ret = -1; /* LCOV_EXCL_LINE */ } } else if (*opt_info == 14) { /* * 14: A 16-bit unsigned integer in network byte order follows the * initial byte and indicates the Option Delta/Length minus 269. */ if (ptr + sizeof(uint8_t) < io->buf + io->len) { *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269; ret = sizeof(uint16_t); } else { ret = -1; /* LCOV_EXCL_LINE */ } } return ret; } /* * Fills options in mg_coap_message. * * Helper function. * * General options format: * +---------------+---------------+ * | Option Delta | Option Length | 1 byte * +---------------+---------------+ * \ Option Delta (extended) \ 0-2 bytes * +-------------------------------+ * / Option Length (extended) \ 0-2 bytes * +-------------------------------+ * \ Option Value \ 0 or more bytes * +-------------------------------+ */ static char *coap_get_options(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { uint16_t prev_opt = 0; if (ptr == io->buf + io->len) { /* end of packet, ok */ return NULL; } /* 0xFF is payload marker */ while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) { uint16_t option_delta, option_lenght; int optinfo_len; /* Option Delta: 4-bit unsigned integer */ option_delta = ((uint8_t) *ptr & 0xF0) >> 4; /* Option Length: 4-bit unsigned integer */ option_lenght = *ptr & 0x0F; if (option_delta == 15 || option_lenght == 15) { /* * 15: Reserved for future use. If the field is set to this value, * it MUST be processed as a message format error */ cm->flags |= MG_COAP_FORMAT_ERROR; break; } ptr++; /* check for extended option delta */ optinfo_len = coap_get_ext_opt(ptr, io, &option_delta); if (optinfo_len == -1) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += optinfo_len; /* check or extended option lenght */ optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght); if (optinfo_len == -1) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += optinfo_len; /* * Instead of specifying the Option Number directly, the instances MUST * appear in order of their Option Numbers and a delta encoding is used * between them. */ option_delta += prev_opt; mg_coap_add_option(cm, option_delta, ptr, option_lenght); prev_opt = option_delta; if (ptr + option_lenght > io->buf + io->len) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += option_lenght; } if ((cm->flags & MG_COAP_ERROR) != 0) { mg_coap_free_options(cm); return NULL; } cm->flags |= MG_COAP_OPTIOMG_FIELD; if (ptr == io->buf + io->len) { /* end of packet, ok */ return NULL; } ptr++; return ptr; } uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) { char *ptr; memset(cm, 0, sizeof(*cm)); if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) { return cm->flags; } if ((ptr = coap_get_token(ptr, io, cm)) == NULL) { return cm->flags; } if ((ptr = coap_get_options(ptr, io, cm)) == NULL) { return cm->flags; } /* the rest is payload */ cm->payload.len = io->len - (ptr - io->buf); if (cm->payload.len != 0) { cm->payload.p = ptr; cm->flags |= MG_COAP_PAYLOAD_FIELD; } return cm->flags; } /* * Calculates extended size of given Opt Number/Length in coap message. * * Helper function. */ static size_t coap_get_ext_opt_size(uint32_t value) { int ret = 0; if (value >= 13 && value <= 0xFF + 13) { ret = sizeof(uint8_t); } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { ret = sizeof(uint16_t); } return ret; } /* * Splits given Opt Number/Length into base and ext values. * * Helper function. */ static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) { int ret = 0; if (value < 13) { *base = value; } else if (value >= 13 && value <= 0xFF + 13) { *base = 13; *ext = value - 13; ret = sizeof(uint8_t); } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { *base = 14; *ext = value - 269; ret = sizeof(uint16_t); } return ret; } /* * Puts uint16_t (in network order) into given char stream. * * Helper function. */ static char *coap_add_uint16(char *ptr, uint16_t val) { *ptr = val >> 8; ptr++; *ptr = val & 0x00FF; ptr++; return ptr; } /* * Puts extended value of Opt Number/Length into given char stream. * * Helper function. */ static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) { if (len == sizeof(uint8_t)) { *ptr = val; ptr++; } else if (len == sizeof(uint16_t)) { ptr = coap_add_uint16(ptr, val); } return ptr; } /* * Verifies given mg_coap_message and calculates message size for it. * * Helper function. */ static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm, size_t *len) { struct mg_coap_option *opt; uint32_t prev_opt_number; *len = 4; /* header */ if (cm->msg_type > MG_COAP_MSG_MAX) { return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD; } if (cm->token.len > 8) { return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD; } if (cm->code_class > 7) { return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD; } if (cm->code_detail > 31) { return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD; } *len += cm->token.len; if (cm->payload.len != 0) { *len += cm->payload.len + 1; /* ... + 1; add payload marker */ } opt = cm->options; prev_opt_number = 0; while (opt != NULL) { *len += 1; /* basic delta/length */ *len += coap_get_ext_opt_size(opt->number); *len += coap_get_ext_opt_size((uint32_t) opt->value.len); /* * Current implementation performs check if * option_number > previous option_number and produces an error * TODO(alashkin): write design doc with limitations * May be resorting is more suitable solution. */ if ((opt->next != NULL && opt->number > opt->next->number) || opt->value.len > 0xFFFF + 269 || opt->number - prev_opt_number > 0xFFFF + 269) { return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD; } *len += opt->value.len; opt = opt->next; } return 0; } uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) { struct mg_coap_option *opt; uint32_t res, prev_opt_number; size_t prev_io_len, packet_size; char *ptr; res = coap_calculate_packet_size(cm, &packet_size); if (res != 0) { return res; } /* saving previous lenght to handle non-empty mbuf */ prev_io_len = io->len; mbuf_append(io, NULL, packet_size); ptr = io->buf + prev_io_len; /* * since cm is verified, it is possible to use bits shift operator * without additional zeroing of unused bits */ /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */ *ptr = (1 << 6) | (cm->msg_type << 4) | (cm->token.len); ptr++; /* code class: 3 bits, code detail: 5 bits */ *ptr = (cm->code_class << 5) | (cm->code_detail); ptr++; ptr = coap_add_uint16(ptr, cm->msg_id); if (cm->token.len != 0) { memcpy(ptr, cm->token.p, cm->token.len); ptr += cm->token.len; } opt = cm->options; prev_opt_number = 0; while (opt != NULL) { uint8_t delta_base = 0, length_base = 0; uint16_t delta_ext, length_ext; size_t opt_delta_len = coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext); size_t opt_lenght_len = coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext); *ptr = (delta_base << 4) | length_base; ptr++; ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len); ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len); if (opt->value.len != 0) { memcpy(ptr, opt->value.p, opt->value.len); ptr += opt->value.len; } prev_opt_number = opt->number; opt = opt->next; } if (cm->payload.len != 0) { *ptr = 0xFF; ptr++; memcpy(ptr, cm->payload.p, cm->payload.len); } return 0; } uint32_t mg_coap_send_message(struct mg_connection *nc, struct mg_coap_message *cm) { struct mbuf packet_out; uint32_t compose_res; mbuf_init(&packet_out, 0); compose_res = mg_coap_compose(cm, &packet_out); if (compose_res != 0) { return compose_res; /* LCOV_EXCL_LINE */ } mg_send(nc, packet_out.buf, (int) packet_out.len); mbuf_free(&packet_out); return 0; } uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) { struct mg_coap_message cm; memset(&cm, 0, sizeof(cm)); cm.msg_type = MG_COAP_MSG_ACK; cm.msg_id = msg_id; return mg_coap_send_message(nc, &cm); } static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) { struct mbuf *io = &nc->recv_mbuf; struct mg_coap_message cm; uint32_t parse_res; memset(&cm, 0, sizeof(cm)); nc->handler(nc, ev, ev_data); switch (ev) { case MG_EV_RECV: parse_res = mg_coap_parse(io, &cm); if ((parse_res & MG_COAP_IGNORE) == 0) { if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) { /* * Since we support UDP only * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR */ cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */ } /* LCOV_EXCL_LINE */ nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm); } mg_coap_free_options(&cm); mbuf_remove(io, io->len); break; } } /* * Attach built-in CoAP event handler to the given connection. * * The user-defined event handler will receive following extra events: * * - MG_EV_COAP_CON * - MG_EV_COAP_NOC * - MG_EV_COAP_ACK * - MG_EV_COAP_RST */ int mg_set_protocol_coap(struct mg_connection *nc) { /* supports UDP only */ if ((nc->flags & MG_F_UDP) == 0) { return -1; } nc->proto_handler = coap_handler; return 0; } #endif /* MG_DISABLE_COAP */
31.655129
88
0.551245
[ "object" ]
162dc9da1e68dc2461d3072a4121e4288a0c16ec
11,402
cpp
C++
data/AGNC-Lab_Quad/multithreaded/threads/control_thread.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/AGNC-Lab_Quad/multithreaded/threads/control_thread.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/AGNC-Lab_Quad/multithreaded/threads/control_thread.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
#include "control_thread.h" void *AttControl_Timer(void *threadID){ printf("AttControl_Timer has started!\n"); int SamplingTime = 5; //Sampling time in milliseconds int localCurrentState; while(1){ WaitForEvent(e_Timeout,SamplingTime); //Check system state pthread_mutex_lock(&stateMachine_Mutex); localCurrentState = currentState; pthread_mutex_unlock(&stateMachine_Mutex); //check if system should be terminated if(localCurrentState == TERMINATE){ break; } SetEvent(e_AttControl_trigger); } printf("AttControl_Timer stopping...\n"); //Shutdown here threadCount -= 1; pthread_exit(NULL); } void *AttControl_Task(void *threadID){ printf("AttControl_Task has started!\n"); //Initialize PIDs (sets initial errors to zero) pthread_mutex_lock(&PID_Mutex); initializePID(&PID_att); initializePID(&PID_angVel); pthread_mutex_unlock(&PID_Mutex); float dt = 0.005; //Sampling time float takeOffThrust = 0.3; //Minimum thrust for resetting integral control Matrix<float, 3, 1> localAttRef; //Vectors of zeros Matrix<float, 3, 1> Zero_3x1 = Matrix<float, 3, 1>::Zero(3, 1); Matrix<float, 3, 3> Zero_3x3 = Matrix<float, 3, 3>::Zero(3, 3); Matrix<float, 3, 1> feedforward = Zero_3x1; Matrix<float, 4, 1> IMU_localData_Quat; Matrix<float, 3, 1> IMU_localData_Vel; Matrix<float, 3, 1> IMU_localData_RPY; Matrix<float, 3, 1> inputTorque; Matrix<float, 4, 1> PCA_localData; float localThrust = 0; int localCurrentState; int localYawSource; Matrix<float, 3, 1> error_att; Matrix<float, 3, 1> error_att_vel; Matrix<float, 3, 1> wDes; Matrix<float, 3, 3> Rdes = Zero_3x3; Matrix<float, 3, 3> Rbw; //Matrix<float, 3, 3> Rdes = RPY2Rot(0,0,0); //PrintMatrix<float, 3, 3>(Concatenate3Matrix<float, 3, 1>_2_Matrix<float, 3, 3>(PID_att.K_p, PID_att.K_d, PID_att.K_i)); //PrintMatrix<float, 3, 3>(Concatenate3Matrix<float, 3, 1>_2_Matrix<float, 3, 3>(PID_angVel.K_p, PID_angVel.K_d, PID_angVel.K_i)); while(1){ WaitForEvent(e_AttControl_trigger,500); //Check system state pthread_mutex_lock(&stateMachine_Mutex); localCurrentState = currentState; pthread_mutex_unlock(&stateMachine_Mutex); //check if system should be terminated if(localCurrentState == TERMINATE){ break; } //Grab attitude reference if(localCurrentState == ATTITUDE_MODE){ pthread_mutex_lock(&attRefJoy_Mutex); localAttRef = attRefJoy; feedforward = angVelRefJoy; pthread_mutex_unlock(&attRefJoy_Mutex); //Throttle pthread_mutex_lock(&ThrustJoy_Mutex); localThrust = ThrustJoy; pthread_mutex_unlock(&ThrustJoy_Mutex); Rdes = RPY2Rot(localAttRef(0), localAttRef(1), localAttRef(2)); //fix this } else if (localCurrentState == POSITION_JOY_MODE){ pthread_mutex_lock(&attRefPosControl_Mutex); Rdes = Rdes_PosControl; pthread_mutex_unlock(&attRefPosControl_Mutex); pthread_mutex_lock(&ThrustPosControl_Mutex); localThrust = ThrustPosControl; pthread_mutex_unlock(&ThrustPosControl_Mutex); } else if (localCurrentState == POSITION_ROS_MODE){ pthread_mutex_lock(&attRefPosControl_Mutex); Rdes = Rdes_PosControl; pthread_mutex_unlock(&attRefPosControl_Mutex); pthread_mutex_lock(&ThrustPosControl_Mutex); localThrust = ThrustPosControl; pthread_mutex_unlock(&ThrustPosControl_Mutex); } else if (localCurrentState == MOTOR_MODE){ pthread_mutex_lock(&ThrustJoy_Mutex); localThrust = ThrustJoy; pthread_mutex_unlock(&ThrustJoy_Mutex); inputTorque = Zero_3x1; } else{ localThrust = 0; } //Control attitude if in attitude / position modes if((localCurrentState == ATTITUDE_MODE) || (localCurrentState == POSITION_JOY_MODE) || (localCurrentState == POSITION_ROS_MODE)){ pthread_mutex_lock(&YawSource_Mutex); localYawSource = YawSource; pthread_mutex_unlock(&YawSource_Mutex); //Grab attitude estimation if (localYawSource == _IMU){ pthread_mutex_lock(&IMU_Mutex); IMU_localData_Quat = IMU_Data_Quat; IMU_localData_Vel = IMU_Data_AngVel; IMU_localData_RPY = IMU_Data_RPY; pthread_mutex_unlock(&IMU_Mutex); } else{ pthread_mutex_lock(&PVA_Vicon_Mutex); IMU_localData_Quat = IMU_Data_Quat_ViconYaw; pthread_mutex_unlock(&PVA_Vicon_Mutex); pthread_mutex_lock(&IMU_Mutex); IMU_localData_Vel = IMU_Data_AngVel; IMU_localData_RPY = IMU_Data_RPY; pthread_mutex_unlock(&IMU_Mutex); } Rbw = Quat2rot(IMU_localData_Quat); //Calculate attitude error error_att = AttitudeErrorVector(Rbw, Rdes); //PrintMatrix<float, 3, 1>(error_att, "error_att"); //Update PID pthread_mutex_lock(&PID_Mutex); if(!isNanVec3(error_att)){ updateErrorPID(&PID_att, feedforward, error_att, Zero_3x1, dt); } //Dont integrate integrator if not in minimum thrust if (localThrust < takeOffThrust){ resetIntegralErrorPID(&PID_att); } //Reference for inner loop (angular velocity control) wDes = outputPID(PID_att); //Calculate angular velocity error and update PID error_att_vel = wDes-IMU_localData_Vel; updateErrorPID(&PID_angVel, feedforward, error_att_vel, Zero_3x1, dt); if (localThrust < takeOffThrust){ resetIntegralErrorPID(&PID_angVel); } //This scale of 16.0 should be excluded eventually (incorporate it in gains) inputTorque = outputPID(PID_angVel)*(1.0/16.0); pthread_mutex_unlock(&PID_Mutex); } //Distribute power to motors pthread_mutex_lock(&Contr_Input_Mutex); Contr_Input << localThrust, inputTorque; PCA_localData = u2pwmXshape(Contr_Input); pthread_mutex_unlock(&Contr_Input_Mutex); //Send motor commands pthread_mutex_lock(&PCA_Mutex); PCA_Data = PCA_localData; pthread_mutex_unlock(&PCA_Mutex); } printf("AttControl_Task stopping...\n"); threadCount -= 1; pthread_exit(NULL); } void *PosControl_Timer(void *threadID){ printf("PosControl_Timer has started!\n"); int SamplingTime = 10; //Sampling time in milliseconds int localCurrentState; while(1){ WaitForEvent(e_Timeout,SamplingTime); //Check system state pthread_mutex_lock(&stateMachine_Mutex); localCurrentState = currentState; pthread_mutex_unlock(&stateMachine_Mutex); //check if system should be terminated if(localCurrentState == TERMINATE){ break; } SetEvent(e_PosControl_trigger); } printf("PosControl_Timer stopping...\n"); //Shutdown here threadCount -= 1; pthread_exit(NULL); } void *PosControl_Task(void *threadID){ printf("PosControl_Task has started!\n"); float dt = 0.010; //Sampling time double m = 0.26, g_z = 9.81; //Mass and gravity for quadcopter double nominalThrust = 2.5; int localCurrentState; float yawDesired; Matrix<float, 3, 1> e_Pos, e_Vel; //error in position and velocity Matrix<float, 3, 1> acc_Ref; //Desired acceleration Matrix<float, 3, 1> feedForward; //Feedforward vector Matrix<float, 3, 1> Fdes; Matrix<float, 3, 1> z_bdes, x_cdes, y_bdes, x_bdes; Matrix<float, 4, 1> IMU_localData_Quat; qcontrol_defs::PVA localPVAEst_quadVicon, localPVA_quadVicon, localPVA_Ref; float cos_YawHalf, sin_YawHalf; Matrix<float, 3, 1> z_w; //z vector of the inertial frame Matrix<float, 3, 1> z_b; //z vector of the body frame z_w << 0, 0, 1; //Initialize PIDs (sets initial errors to zero) pthread_mutex_lock(&PID_Mutex); initializePID(&PID_pos); pthread_mutex_unlock(&PID_Mutex); while(1){ WaitForEvent(e_PosControl_trigger,500); //Check system state pthread_mutex_lock(&stateMachine_Mutex); localCurrentState = currentState; pthread_mutex_unlock(&stateMachine_Mutex); //check if system should be terminated if(localCurrentState == TERMINATE){ break; } //Grab attitude estimation // pthread_mutex_lock(&IMU_Mutex); // IMU_localData_Quat = IMU_Data_Quat; // pthread_mutex_unlock(&IMU_Mutex); pthread_mutex_lock(&PVA_Vicon_Mutex); IMU_localData_Quat = IMU_Data_Quat_ViconYaw; pthread_mutex_unlock(&PVA_Vicon_Mutex); //Grab position and velocity estimation pthread_mutex_lock(&PVA_Kalman_Mutex); localPVAEst_quadVicon = PVA_quadKalman; pthread_mutex_unlock(&PVA_Kalman_Mutex); pthread_mutex_lock(&PVA_Vicon_Mutex); localPVA_quadVicon = PVA_quadVicon; pthread_mutex_unlock(&PVA_Vicon_Mutex); // pthread_mutex_lock(&PVA_Vicon_Mutex); // localPVA_quadVicon = PVA_quadVicon; // pthread_mutex_unlock(&PVA_Vicon_Mutex); //Grab joystick position and velocity reference if(localCurrentState == POSITION_JOY_MODE){ pthread_mutex_lock(&posRefJoy_Mutex); localPVA_Ref = PVA_RefJoy; pthread_mutex_unlock(&posRefJoy_Mutex); } else if(localCurrentState == POSITION_ROS_MODE){ pthread_mutex_lock(&posRefJoy_Mutex); localPVA_Ref = PVA_RefClient; pthread_mutex_unlock(&posRefJoy_Mutex); } //Grab yaw reference pthread_mutex_lock(&attRefJoy_Mutex); yawDesired = attRefJoy(2); pthread_mutex_unlock(&attRefJoy_Mutex); //Calculate position and velocity errors e_Pos << localPVA_Ref.pos.position.x - localPVA_quadVicon.pos.position.x, localPVA_Ref.pos.position.y - localPVA_quadVicon.pos.position.y, localPVA_Ref.pos.position.z - localPVA_quadVicon.pos.position.z; e_Vel << localPVA_Ref.vel.linear.x - localPVAEst_quadVicon.vel.linear.x, localPVA_Ref.vel.linear.y - localPVAEst_quadVicon.vel.linear.y, localPVA_Ref.vel.linear.z - localPVAEst_quadVicon.vel.linear.z; //Get feedforward vector acc_Ref << localPVA_Ref.acc.linear.x, localPVA_Ref.acc.linear.y, localPVA_Ref.acc.linear.z; feedForward = z_w*nominalThrust + acc_Ref; // feedForward = Add3x1Vec(ScaleMatrix<float, 3, 1>(z_w, nominalThrust), ScaleMatrix<float, 3, 1>(acc_Ref, 1.0/gz));//feedForward = m*gz*z_w + m*ref_dotdot //Vehicle attitude Matrix<float, 3, 3> Rbw = Quat2rot(IMU_localData_Quat); z_b = Rbw*z_w; //z vector of the vehicle in inertial frame //Update data in PID, calculate results pthread_mutex_lock(&PID_Mutex); updateErrorPID(&PID_pos, feedForward, e_Pos, e_Vel, dt); //Dont integrate integrator if not in POS_Control mode if (localCurrentState != POSITION_JOY_MODE && localCurrentState != POSITION_ROS_MODE){ resetIntegralErrorPID(&PID_pos); } //Calculate 3d world desired force for the quadcopter and normalize it Fdes = outputPID(PID_pos); pthread_mutex_unlock(&PID_Mutex); //Desired thrust in body frame pthread_mutex_lock(&ThrustPosControl_Mutex); ThrustPosControl = Fdes.dot(z_b); pthread_mutex_unlock(&ThrustPosControl_Mutex); //Find desired attitude from desired force and yaw angle z_bdes = normalizeVec3(Fdes); cos_YawHalf = localPVA_Ref.pos.orientation.w; sin_YawHalf = localPVA_Ref.pos.orientation.z; //cos(2a) = 2cos^2(a) - 1 //sin(2a) = 2*sin(a)cos(a) // x_cdes << 2*pow(cos_YawHalf,2.0) - 1.0, // 2*sin_YawHalf*cos_YawHalf, // 0; x_cdes << 1.0, 0, 0; y_bdes = normalizeVec3(z_bdes.cross(x_cdes)); x_bdes = y_bdes.cross(z_bdes); //Set desired rotation matrix for attitude pthread_mutex_lock(&attRefPosControl_Mutex); Rdes_PosControl << x_bdes, y_bdes, z_bdes; pthread_mutex_unlock(&attRefPosControl_Mutex); // PrintMatrix<float, 3, 3>(Rdes); } printf("PosControl_Task stopping...\n"); threadCount -= 1; pthread_exit(NULL); }
30.084433
159
0.728293
[ "vector", "3d" ]
162e3e3dc4da9f5833906b0419102106e9a64382
12,459
hpp
C++
ql/experimental/volatility/zabrsmilesection.hpp
japari/QuantLib
c2670bd433289eaf98410e911d87156595ca6d67
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/volatility/zabrsmilesection.hpp
japari/QuantLib
c2670bd433289eaf98410e911d87156595ca6d67
[ "BSD-3-Clause" ]
1
2020-07-17T18:49:22.000Z
2020-07-17T18:49:22.000Z
ql/experimental/volatility/zabrsmilesection.hpp
TheOnlyDyson/QuantLib
78a144bbc5030c9e417e810e44ee48cffe40cf70
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2014 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file zabrsmilesection.hpp \brief zabr smile section */ #ifndef quantlib_zabr_smile_section_hpp #define quantlib_zabr_smile_section_hpp #include <ql/pricingengines/blackformula.hpp> #include <ql/termstructures/volatility/smilesection.hpp> #include <ql/time/daycounters/actual365fixed.hpp> #include <ql/experimental/volatility/zabr.hpp> #include <ql/termstructures/volatility/smilesectionutils.hpp> #include <vector> using std::exp; namespace QuantLib { // Evaluation Tags struct ZabrShortMaturityLognormal {}; struct ZabrShortMaturityNormal {}; struct ZabrLocalVolatility {}; struct ZabrFullFd {}; template <typename Evaluation> class ZabrSmileSection : public SmileSection { public: ZabrSmileSection(Time timeToExpiry, Rate forward, const std::vector<Real> &zabrParameters, const std::vector<Real> &moneyness = std::vector<Real>(), const Size fdRefinement = 5); ZabrSmileSection(const Date &d, Rate forward, const std::vector<Real> &zabrParameters, const DayCounter &dc = Actual365Fixed(), const std::vector<Real> &moneyness = std::vector<Real>(), const Size fdRefinement = 5); Real minStrike() const { return 0.0; } Real maxStrike() const { return QL_MAX_REAL; } Real atmLevel() const { return model_->forward(); } Real optionPrice(Rate strike, Option::Type type = Option::Call, Real discount = 1.0) const { return optionPrice(strike, type, discount, Evaluation()); } boost::shared_ptr<ZabrModel> model() { return model_; } protected: Volatility volatilityImpl(Rate strike) const { return volatilityImpl(strike, Evaluation()); } private: void init(const std::vector<Real> &moneyness) { init(moneyness, Evaluation()); init2(Evaluation()); init3(Evaluation()); } void init(const std::vector<Real> &moneyness, ZabrShortMaturityLognormal); void init(const std::vector<Real> &moneyness, ZabrShortMaturityNormal); void init(const std::vector<Real> &moneyness, ZabrLocalVolatility); void init(const std::vector<Real> &moneyness, ZabrFullFd); void init2(ZabrShortMaturityLognormal); void init2(ZabrShortMaturityNormal); void init2(ZabrLocalVolatility); void init2(ZabrFullFd); void init3(ZabrShortMaturityLognormal); void init3(ZabrShortMaturityNormal); void init3(ZabrLocalVolatility); void init3(ZabrFullFd); Real optionPrice(Rate strike, Option::Type type, Real discount, ZabrShortMaturityLognormal) const; Real optionPrice(Rate strike, Option::Type type, Real discount, ZabrShortMaturityNormal) const; Real optionPrice(Rate strike, Option::Type type, Real discount, ZabrLocalVolatility) const; Real optionPrice(Rate strike, Option::Type type, Real discount, ZabrFullFd) const; Volatility volatilityImpl(Rate strike, ZabrShortMaturityLognormal) const; Volatility volatilityImpl(Rate strike, ZabrShortMaturityNormal) const; Volatility volatilityImpl(Rate strike, ZabrLocalVolatility) const; Volatility volatilityImpl(Rate strike, ZabrFullFd) const; boost::shared_ptr<ZabrModel> model_; Evaluation evaluation_; Rate forward_; std::vector<Real> params_; const Size fdRefinement_; std::vector<Real> strikes_, callPrices_; boost::shared_ptr<Interpolation> callPriceFct_; Real a_, b_; }; template <typename Evaluation> ZabrSmileSection<Evaluation>::ZabrSmileSection( Time timeToExpiry, Rate forward, const std::vector<Real> &zabrParams, const std::vector<Real> &moneyness, const Size fdRefinement) : SmileSection(timeToExpiry, DayCounter()), forward_(forward), params_(zabrParams), fdRefinement_(fdRefinement) { init(moneyness); } template <typename Evaluation> ZabrSmileSection<Evaluation>::ZabrSmileSection( const Date &d, Rate forward, const std::vector<Real> &zabrParams, const DayCounter &dc, const std::vector<Real> &moneyness, const Size fdRefinement) : SmileSection(d, dc, Date()), forward_(forward), params_(zabrParams), fdRefinement_(fdRefinement) { init(moneyness); } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init(const std::vector<Real> &, ZabrShortMaturityLognormal) { model_ = boost::shared_ptr<ZabrModel>( new ZabrModel(exerciseTime(), forward_, params_[0], params_[1], params_[2], params_[3], params_[4])); } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init(const std::vector<Real> &a, ZabrShortMaturityNormal) { init(a, ZabrShortMaturityLognormal()); } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init(const std::vector<Real> &moneyness, ZabrLocalVolatility) { QL_REQUIRE(params_.size() >= 5, "zabr expects 5 parameters (alpha,beta,nu,rho,gamma) but (" << params_.size() << ") given"); model_ = boost::shared_ptr<ZabrModel>( new ZabrModel(exerciseTime(), forward_, params_[0], params_[1], params_[2], params_[3], params_[4])); // set up strike grid for local vol or full fd flavour of this section // this is shared with SmileSectionUtils - unify later ? static const Real defaultMoney[] = { 0.0, 0.01, 0.05, 0.10, 0.25, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.0, 1.25, 1.5, 1.75, 2.0, 5.0, 7.5, 10.0, 15.0, 20.0}; std::vector<Real> tmp; if (moneyness.size() == 0) tmp = std::vector<Real>(defaultMoney, defaultMoney + 21); else tmp = std::vector<Real>(moneyness); strikes_.clear(); // should not be necessary, anyway Real lastF = 0.0; bool firstStrike = true; for (Size i = 0; i < tmp.size(); i++) { Real f = tmp[i] * forward_; if (f > 0.0) { if (!firstStrike) { for (Size j = 1; j <= fdRefinement_; ++j) { strikes_.push_back(lastF + ((double)j) * (f - lastF) / (fdRefinement_ + 1)); } } firstStrike = false; lastF = f; strikes_.push_back(f); } } } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init(const std::vector<Real> &moneyness, ZabrFullFd) { init(moneyness, ZabrLocalVolatility()); } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init2(ZabrShortMaturityLognormal) {} template <typename Evaluation> void ZabrSmileSection<Evaluation>::init2(ZabrShortMaturityNormal) {} template <typename Evaluation> void ZabrSmileSection<Evaluation>::init2(ZabrLocalVolatility) { callPrices_ = model_->fdPrice(strikes_); } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init2(ZabrFullFd) { callPrices_.resize(strikes_.size()); #pragma omp parallel for for (long i = 0; i < (long)strikes_.size(); i++) { callPrices_[i] = model_->fullFdPrice(strikes_[i]); } } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init3(ZabrShortMaturityLognormal) {} template <typename Evaluation> void ZabrSmileSection<Evaluation>::init3(ZabrShortMaturityNormal) {} template <typename Evaluation> void ZabrSmileSection<Evaluation>::init3(ZabrLocalVolatility) { strikes_.insert(strikes_.begin(), 0.0); callPrices_.insert(callPrices_.begin(), forward_); callPriceFct_ = boost::shared_ptr<Interpolation>(new CubicInterpolation( strikes_.begin(), strikes_.end(), callPrices_.begin(), CubicInterpolation::Spline, true, CubicInterpolation::SecondDerivative, 0.0, CubicInterpolation::SecondDerivative, 0.0)); // callPriceFct_ = // boost::shared_ptr<Interpolation>(new LinearInterpolation( // strikes_.begin(), strikes_.end(), callPrices_.begin())); callPriceFct_->enableExtrapolation(); // on the right side we extrapolate exponetially (because spline // does not make sense) // we precompute the necessary parameters here static const Real eps = 1E-5; // gap for first derivative computation Real c0 = callPriceFct_->operator()(strikes_.back()); Real c0p = (callPriceFct_->operator()(strikes_.back() - eps) - c0) / eps; a_ = c0p / c0; b_ = std::log(c0) + a_ * strikes_.back(); } template <typename Evaluation> void ZabrSmileSection<Evaluation>::init3(ZabrFullFd) { init3(ZabrLocalVolatility()); } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::optionPrice(Real strike, Option::Type type, Real discount, ZabrShortMaturityLognormal) const { return SmileSection::optionPrice(strike, type, discount); } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::optionPrice(Real strike, Option::Type type, Real discount, ZabrShortMaturityNormal) const { return bachelierBlackFormula( type, strike, forward_, model_->normalVolatility(strike) * std::sqrt(exerciseTime()), discount); } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::optionPrice(Rate strike, Option::Type type, Real discount, ZabrLocalVolatility) const { Real call = strike <= strikes_.back() ? callPriceFct_->operator()(strike) : exp(-a_ * strike + b_); if (type == Option::Call) return call * discount; else return (call - (forward_ - strike)) * discount; } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::optionPrice(Rate strike, Option::Type type, Real discount, ZabrFullFd) const { return optionPrice(strike, type, discount, ZabrLocalVolatility()); } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::volatilityImpl(Rate strike, ZabrShortMaturityLognormal) const { strike = std::max(1E-6, strike); return model_->lognormalVolatility(strike); } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::volatilityImpl(Rate strike, ZabrShortMaturityNormal) const { Real impliedVol = 0.0; try { Option::Type type; if (strike >= model_->forward()) type = Option::Call; else type = Option::Put; impliedVol = blackFormulaImpliedStdDev(type, strike, model_->forward(), optionPrice(strike, type, 1.0), 1.0) / std::sqrt(exerciseTime()); } catch (...) { } return impliedVol; } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::volatilityImpl(Rate strike, ZabrLocalVolatility) const { return volatilityImpl(strike, ZabrShortMaturityNormal()); } template <typename Evaluation> Real ZabrSmileSection<Evaluation>::volatilityImpl(Rate strike, ZabrFullFd) const { return volatilityImpl(strike, ZabrShortMaturityNormal()); } } #endif
37.640483
80
0.643551
[ "vector", "model" ]
16331037dc325724157ee0da9cf71ea00956baea
5,399
cc
C++
nq/nq.cc
gnartbx/noodles
26e4ab21cfe98a36d01774d54ff0451d0f71b572
[ "MIT" ]
null
null
null
nq/nq.cc
gnartbx/noodles
26e4ab21cfe98a36d01774d54ff0451d0f71b572
[ "MIT" ]
null
null
null
nq/nq.cc
gnartbx/noodles
26e4ab21cfe98a36d01774d54ff0451d0f71b572
[ "MIT" ]
null
null
null
#include <atomic> #include <chrono> #include <iostream> #include <limits> #include <mutex> #include <random> #include <thread> #include <gflags/gflags.h> #include <math.h> #include <signal.h> #include <time.h> #include "queens.h" DEFINE_int32(board_size, 8, "Number of rows/columns in the chess boards."); DEFINE_int32(num_threads, 32, "Number of threads to try to solve with."); DEFINE_int64(num_attempts, 1024, "Total number of attempts."); DEFINE_int64(max_tries, 24, "Number of random tries within an annealing iteration."); DEFINE_int32(annealing_steps, 200, "Maximum number of annealing steps run in each solution attempt"); DEFINE_int32( stats_interval_seconds, 10, "Interval between reporting stats, in seconds. No reporting if <= 0"); static const double T_max = 1.0; static const double T_min = 0.00001; class Stats { public: Stats() : start_(clock()), num_accepted_(0), num_rejected_(0), min_cost_(std::numeric_limits<short>::max()) {} void UpdateAccepted(size_t delta_accepted) { std::atomic_fetch_add(&num_accepted_, delta_accepted); } void UpdateRejected(size_t delta_rejected) { std::atomic_fetch_add(&num_rejected_, delta_rejected); } void UpdateMinCost(size_t min_cost) { if (min_cost < min_cost_) { std::lock_guard<std::mutex> lock(mutex_); min_cost_ = std::min(min_cost, min_cost_); } } size_t GetAccepted() const { return num_accepted_; } size_t GetRejected() const { return num_rejected_; } float GetElapsedSeconds() const { return (float)(clock() - start_) / CLOCKS_PER_SEC; } std::ostream &Dump(std::ostream &os) { return os << "Elapsed time: " << GetElapsedSeconds() << " (s)" << std::endl << "Rejected configs: " << GetRejected() << std::endl << "Accepted configs: " << GetAccepted() << std::endl << "Min cost: " << min_cost_ << std::endl; } private: clock_t start_; std::mutex mutex_; std::atomic<size_t> num_accepted_; std::atomic<size_t> num_rejected_; size_t min_cost_; }; volatile bool solved = false; volatile bool interrupted = false; static void handle_signal(int signum) { solved = interrupted = true; } static void solve(const nq::Queens &start, const double alpha, const int64_t max_tries, Stats *stats, volatile bool *found) { nq::Queens q = start; q.Randomize(); std::mt19937 rng(clock() + std::hash<std::thread::id>()(std::this_thread::get_id())); std::uniform_int_distribution<int> method_dist(0, 1); std::uniform_int_distribution<size_t> row_dist(0, q.num_rows() - 1); std::uniform_real_distribution<> accept_dist(0, 1); nq::Queens old_q = q; float old_cost = old_q.num_attacks(); float min_cost = old_cost; size_t num_steps = 0; size_t accepted = 0; size_t rejected = 0; for (float T = T_max; T > T_min && !*found; T = T * alpha) { for (int iteration = 0; iteration < max_tries && !*found; iteration++) { num_steps++; size_t first_row = row_dist(rng); size_t second_row = row_dist(rng); if (method_dist(rng) > 0) { q.Permute(first_row, second_row); } else { q.Swap(first_row, second_row); } float new_cost = q.num_attacks(); if (new_cost == 0 && !*found) { *found = true; std::cout << "Solved at step #" << num_steps << ", temperature " << T << std::endl << "Board:" << std::endl << q << std::endl; } if (old_cost >= new_cost || exp((old_cost - new_cost) / T) > accept_dist(rng)) { accepted++; old_q = q; old_cost = new_cost; min_cost = std::min(min_cost, old_cost); } else { rejected++; q = old_q; } } stats->UpdateAccepted(accepted); stats->UpdateRejected(rejected); stats->UpdateMinCost(min_cost); accepted = rejected = 0; } stats->UpdateAccepted(accepted); stats->UpdateRejected(rejected); stats->UpdateMinCost(min_cost); } int main(int argc, char **argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); float alpha = exp(log(T_min / T_max) / FLAGS_annealing_steps); nq::Queens q = nq::Queens::Create(FLAGS_board_size); int64_t remaining_tries = FLAGS_num_attempts; signal(SIGINT, &handle_signal); Stats stats; if (FLAGS_stats_interval_seconds > 0) { std::thread([&stats]() { while (true) { std::this_thread::sleep_for( std::chrono::seconds(FLAGS_stats_interval_seconds)); if (solved) { break; } stats.Dump(std::cout) << std::endl; } }).detach(); } while (remaining_tries > 0 && !solved) { int32_t num_threads = (FLAGS_num_threads <= remaining_tries) ? FLAGS_num_threads : remaining_tries; std::cout << "Remaining tries: " << remaining_tries << " ... Starting " << num_threads << " attempts." << std::endl; std::vector<std::thread> threads; for (int i = 0; i < num_threads; i++) { threads.emplace_back(solve, q, alpha, FLAGS_max_tries, &stats, &solved); } for (auto &thread : threads) { thread.join(); } remaining_tries -= num_threads; } stats.Dump(std::cout); return solved ? 0 : 1; }
29.183784
80
0.614743
[ "vector" ]
1633e332fa77b6c535b8723bc0884e202d97454d
2,475
hpp
C++
RealityCore/Source/Scipper/FrameCapture.hpp
Intro-Ventors/Re-Co-Desktop
8547cca9230069a36973ec836426d4610f30f8bb
[ "MIT" ]
null
null
null
RealityCore/Source/Scipper/FrameCapture.hpp
Intro-Ventors/Re-Co-Desktop
8547cca9230069a36973ec836426d4610f30f8bb
[ "MIT" ]
null
null
null
RealityCore/Source/Scipper/FrameCapture.hpp
Intro-Ventors/Re-Co-Desktop
8547cca9230069a36973ec836426d4610f30f8bb
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Intro-Ventors #pragma once #include "RScreenCapture.hpp" #include "../WebRTC/Connection.hpp" #include <ScreenCapture.h> #include <QObject> #include <QString> namespace Scipper { /** * Frame capture object. * This class is the base class for both window and monitor capture objects. */ class FrameCapture : public QObject, public RScreenCapture { Q_OBJECT public: using CaptureConfig = std::shared_ptr<SL::Screen_Capture::IScreenCaptureManager>; using Clock = std::chrono::high_resolution_clock; using TimePoint = std::chrono::time_point<Clock>; /** * Converting constructor. * * @param name The name of the frame. */ FrameCapture(QString name); /** * Toggle the record boolean. */ void toggleRecord() { m_bShouldRecord = true; } /** * Get the name of the frame. * * @return The QString object. */ const QString getName() const { return m_Name; } signals: /** * Signal indicating that a new frame was added. * * @param image The new image. */ void newFrame(std::shared_ptr<ImageData> image); protected: /** * Convert the BGRA image to RGBA. * * @param image The image reference. * @param delta The time delta between the current frame and the old frame. * @return The converted data. */ static std::shared_ptr<ImageData> convertRGBA(const SL::Screen_Capture::Image& image, const uint64_t delta); /** * Convert the BGRA image to RGBA. * * @param image The image reference. * @param delta The time delta between the current frame and the old frame. * @return The converted data. */ static std::shared_ptr<ImageData> convertRGBA_Test(const SL::Screen_Capture::Image& image, const uint64_t delta); /** * Convert the incoming image data to a PNG format. * * @param pImageData The image data to encode. * @return The encoded image. */ static EncodedImage convertPNG(const ImageData* pImageData); /** * Convert the incoming image data to a PNG format. * * @param image The image data from the Screen Capture Lite API. * @return The encoded image. */ static EncodedImage convertPNG(const SL::Screen_Capture::Image& image); protected: QString m_Name; std::shared_ptr<WebRTC::Connection> m_pConnection = nullptr; CaptureConfig m_pConfiguration = nullptr; std::atomic<bool> m_bShouldRecord = true; std::shared_ptr<ImageData> m_pImageData = nullptr; TimePoint m_TimePoint; }; }
25.255102
115
0.693737
[ "object" ]
1636927c76fcb8608988a36d6e83c982051a56ce
4,658
cc
C++
src/geometry/test/test_points.cc
jloveric/jali
635d46983acb66c824fabb0947803f5787356dc9
[ "BSD-3-Clause" ]
13
2017-05-01T13:30:01.000Z
2022-03-30T22:42:40.000Z
src/geometry/test/test_points.cc
mjgpinheiro/jali
fcfcf9f9889aec250eb715d7f98ac5860d640189
[ "BSD-3-Clause" ]
6
2018-04-05T14:15:21.000Z
2022-01-18T19:55:56.000Z
src/geometry/test/test_points.cc
mjgpinheiro/jali
fcfcf9f9889aec250eb715d7f98ac5860d640189
[ "BSD-3-Clause" ]
10
2017-05-05T22:28:56.000Z
2020-05-27T11:20:11.000Z
/* Copyright (c) 2019, Triad National Security, LLC All rights reserved. Copyright 2019. Triad National Security, LLC. This software was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so This is open source software distributed under the 3-clause BSD license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Triad National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 TRIAD NATIONAL SECURITY, LLC 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 TRIAD NATIONAL SECURITY, LLC 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 <UnitTest++.h> #include <iostream> #include "../Point.hh" #include "mpi.h" TEST(Point) { double x = 0.4, y = 0.6, z = 0.8; double xyz[3] = {1, 2, 3.5}; // Create different types of points JaliGeometry::Point p0(2); p0.set(x,y); CHECK_EQUAL(x,p0.x()); CHECK_EQUAL(y,p0.y()); JaliGeometry::Point p1(2); p1.set(2,xyz); CHECK_EQUAL(xyz[0],p1.x()); CHECK_EQUAL(xyz[1],p1.y()); x = x + 0.1; y = y + 0.1; JaliGeometry::Point p2(x,y); CHECK_EQUAL(x,p2.x()); CHECK_EQUAL(y,p2.y()); JaliGeometry::Point p3(p2); CHECK_EQUAL(x,p3.x()); CHECK_EQUAL(y,p3.y()); JaliGeometry::Point p4 = p2; CHECK_EQUAL(x,p4.x()); CHECK_EQUAL(y,p4.y()); JaliGeometry::Point p5(3); xyz[0] = x; xyz[1] = y; xyz[2] = z; p5.set(3,xyz); CHECK_EQUAL(x,p5.x()); CHECK_EQUAL(y,p5.y()); CHECK_EQUAL(z,p5.z()); // Create a bunch of 3D points and delete some of them to trigger // different patterns of deletion in the underlying coordinate // buffer int num3 = 25; JaliGeometry::Point *points3[25]; for (int i = 0; i < num3; ++i) { points3[i] = new JaliGeometry::Point(x,y,z); } // Now delete some points in 3D - point 3, 4, 5, 8, 7, 16, 18, 17 // Deletion of 3 is a stand alone deletion // Deletion of 4 followed by point 5 will cause merging of two holes // Deletion of 8 followed by point 7 will cause merging of two holes // Deletion of 16, 18, 17 will cause bridging of three holes // no obvious way of checking the underlying coordinate buffer // machinery except through a debugger delete points3[2]; delete points3[4]; delete points3[5]; delete points3[8]; delete points3[7]; delete points3[16]; delete points3[18]; delete points3[17]; // Create a bunch of mixed dim points int num = 25; std::vector<JaliGeometry::Point *> points; points.resize(25); for (int i = 0; i < num; ++i) { if (i%2) points[i] = new JaliGeometry::Point(x,y); else { points[i] = new JaliGeometry::Point(3); points[i]->set(x,y,z); } x = x + 1.0; y = y + 0.5; z = z + 2.0; } // Don't bother deleting other points. They will get deleted when exiting // we should test the mathematical operations as well here }
29.481013
77
0.7076
[ "vector", "3d" ]
16397adb8017097c6ea3e065e7a6028c7aeee055
9,949
cpp
C++
PotreeConverter/src/PotreeConverter.cpp
sverhoeven/PotreeConverter
48892b11cdaf185b2a90bf7d25aeab31b8c1552b
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
PotreeConverter/src/PotreeConverter.cpp
sverhoeven/PotreeConverter
48892b11cdaf185b2a90bf7d25aeab31b8c1552b
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
PotreeConverter/src/PotreeConverter.cpp
sverhoeven/PotreeConverter
48892b11cdaf185b2a90bf7d25aeab31b8c1552b
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include <boost/filesystem.hpp> #include <boost/algorithm/string/predicate.hpp> #include "PotreeConverter.h" #include "stuff.h" #include "LASPointReader.h" #include "PTXPointReader.h" #include "PotreeException.h" #include "PotreeWriter.h" #include "LASPointWriter.hpp" #include "BINPointWriter.hpp" #include "BINPointReader.hpp" #include "PlyPointReader.h" #include "XYZPointReader.hpp" #include <chrono> #include <sstream> #include <string> #include <map> #include <vector> #include <math.h> #include <fstream> using std::stringstream; using std::map; using std::string; using std::vector; using std::find; using std::chrono::high_resolution_clock; using std::chrono::milliseconds; using std::chrono::duration_cast; using std::fstream; using boost::iends_with; using boost::filesystem::is_directory; using boost::filesystem::directory_iterator; using boost::filesystem::is_regular_file; using boost::filesystem::path; namespace Potree{ PointReader *PotreeConverter::createPointReader(string path, PointAttributes pointAttributes){ PointReader *reader = NULL; if(boost::iends_with(path, ".las") || boost::iends_with(path, ".laz")){ reader = new LASPointReader(path); }else if(boost::iends_with(path, ".ptx")){ reader = new PTXPointReader(path); }else if(boost::iends_with(path, ".ply")){ reader = new PlyPointReader(path); }else if(boost::iends_with(path, ".xyz") || boost::iends_with(path, ".txt")){ reader = new XYZPointReader(path, format, colorRange, intensityRange); }else if(boost::iends_with(path, ".pts")){ vector<double> intensityRange; if(this->intensityRange.size() == 0){ intensityRange.push_back(-2048); intensityRange.push_back(+2047); } reader = new XYZPointReader(path, format, colorRange, intensityRange); }else if(boost::iends_with(path, ".bin")){ reader = new BINPointReader(path, aabb, scale, pointAttributes); } return reader; } PotreeConverter::PotreeConverter(string workDir, vector<string> sources){ this->workDir = workDir; this->sources = sources; } void PotreeConverter::prepare(){ // if sources contains directories, use files inside the directory instead vector<string> sourceFiles; for (const auto &source : sources) { path pSource(source); if(boost::filesystem::is_directory(pSource)){ boost::filesystem::directory_iterator it(pSource); for(;it != boost::filesystem::directory_iterator(); it++){ path pDirectoryEntry = it->path(); if(boost::filesystem::is_regular_file(pDirectoryEntry)){ string filepath = pDirectoryEntry.string(); if(boost::iends_with(filepath, ".las") || boost::iends_with(filepath, ".laz") || boost::iends_with(filepath, ".xyz") || boost::iends_with(filepath, ".pts") || boost::iends_with(filepath, ".ptx") || boost::iends_with(filepath, ".ply")){ sourceFiles.push_back(filepath); } } } }else if(boost::filesystem::is_regular_file(pSource)){ sourceFiles.push_back(source); } } this->sources = sourceFiles; pointAttributes = PointAttributes(); pointAttributes.add(PointAttribute::POSITION_CARTESIAN); for(const auto &attribute : outputAttributes){ if(attribute == "RGB"){ pointAttributes.add(PointAttribute::COLOR_PACKED); }else if(attribute == "INTENSITY"){ pointAttributes.add(PointAttribute::INTENSITY); }else if(attribute == "CLASSIFICATION"){ pointAttributes.add(PointAttribute::CLASSIFICATION); }else if(attribute == "NORMAL"){ pointAttributes.add(PointAttribute::NORMAL_OCT16); } } } AABB PotreeConverter::calculateAABB(){ AABB aabb; if(aabbValues.size() == 6){ Vector3<double> userMin(aabbValues[0],aabbValues[1],aabbValues[2]); Vector3<double> userMax(aabbValues[3],aabbValues[4],aabbValues[5]); aabb = AABB(userMin, userMax); }else{ for(string source : sources){ PointReader *reader = createPointReader(source, pointAttributes); AABB lAABB = reader->getAABB(); aabb.update(lAABB.min); aabb.update(lAABB.max); reader->close(); delete reader; } } return aabb; } void PotreeConverter::generatePage(string name){ string pagedir = this->workDir; string templateSourcePath = "./resources/page_template/examples/viewer_template.html"; string templateTargetPath = pagedir + "/examples/" + name + ".html"; Potree::copyDir(fs::path("./resources/page_template"), fs::path(pagedir)); fs::remove(pagedir + "/examples/viewer_template.html"); { // change viewer template ifstream in( templateSourcePath ); ofstream out( templateTargetPath ); string line; while(getline(in, line)){ if(line.find("<!-- INCLUDE SETTINGS HERE -->") != string::npos){ out << "\t<script src=\"./" << name << ".js\"></script>" << endl; }else if((outputFormat == Potree::OutputFormat::LAS || outputFormat == Potree::OutputFormat::LAZ) && line.find("<!-- INCLUDE ADDITIONAL DEPENDENCIES HERE -->") != string::npos){ out << "\t<script src=\"../libs/plasio/js/laslaz.js\"></script>" << endl; out << "\t<script src=\"../libs/plasio/vendor/bluebird.js\"></script>" << endl; out << "\t<script src=\"../build/js/laslaz.js\"></script>" << endl; }else{ out << line << endl; } } in.close(); out.close(); } { // write settings stringstream ssSettings; ssSettings << "var sceneProperties = {" << endl; ssSettings << "\tpath: \"" << "../resources/pointclouds/" << name << "/cloud.js\"," << endl; ssSettings << "\tcameraPosition: null, // other options: cameraPosition: [10,10,10]," << endl; ssSettings << "\tcameraTarget: null, // other options: cameraTarget: [0,0,0]," << endl; ssSettings << "\tfov: 60, // field of view in degrees," << endl; ssSettings << "\tsizeType: \"Adaptive\", // other options: \"Fixed\", \"Attenuated\"" << endl; ssSettings << "\tquality: null, // other options: \"Circles\", \"Interpolation\", \"Splats\"" << endl; ssSettings << "\tmaterial: \"RGB\", // other options: \"Height\", \"Intensity\", \"Classification\"" << endl; ssSettings << "\tpointLimit: 1, // max number of points in millions" << endl; ssSettings << "\tpointSize: 1, // " << endl; ssSettings << "\tnavigation: \"Orbit\", // other options: \"Orbit\", \"Flight\"" << endl; ssSettings << "\tuseEDL: false, " << endl; ssSettings << "};" << endl; ofstream fSettings; fSettings.open(pagedir + "/examples/" + name + ".js", ios::out); fSettings << ssSettings.str(); fSettings.close(); } } void PotreeConverter::convert(){ auto start = high_resolution_clock::now(); prepare(); long long pointsProcessed = 0; AABB aabb = calculateAABB(); cout << "AABB: " << endl << aabb << endl; aabb.makeCubic(); cout << "cubic AABB: " << endl << aabb << endl; if (diagonalFraction != 0) { spacing = (float)(aabb.size.length() / diagonalFraction); cout << "spacing calculated from diagonal: " << spacing << endl; } if(pageName.size() > 0){ generatePage(pageName); workDir = workDir + "/resources/pointclouds/" + pageName; } PotreeWriter *writer = NULL; if(fs::exists(fs::path(this->workDir + "/cloud.js"))){ if(storeOption == StoreOption::ABORT_IF_EXISTS){ cout << "ABORTING CONVERSION: target already exists: " << this->workDir << "/cloud.js" << endl; cout << "If you want to overwrite the existing conversion, specify --overwrite" << endl; cout << "If you want add new points to the existing conversion, make sure the new points "; cout << "are contained within the bounding box of the existing conversion and then specify --incremental" << endl; return; }else if(storeOption == StoreOption::OVERWRITE){ fs::remove_all(workDir + "/data"); fs::remove_all(workDir + "/temp"); fs::remove(workDir + "/cloud.js"); writer = new PotreeWriter(this->workDir, aabb, spacing, maxDepth, scale, outputFormat, pointAttributes); }else if(storeOption == StoreOption::INCREMENTAL){ writer = new PotreeWriter(this->workDir); writer->loadStateFromDisk(); } }else{ writer = new PotreeWriter(this->workDir, aabb, spacing, maxDepth, scale, outputFormat, pointAttributes); } if(writer == NULL){ return; } for (const auto &source : sources) { cout << "READING: " << source << endl; PointReader *reader = createPointReader(source, pointAttributes); while(reader->readNextPoint()){ pointsProcessed++; Point p = reader->getPoint(); writer->add(p); if((pointsProcessed % (1'000'000)) == 0){ writer->processStore(); writer->waitUntilProcessed(); auto end = high_resolution_clock::now(); long long duration = duration_cast<milliseconds>(end-start).count(); float seconds = duration / 1'000.0f; stringstream ssMessage; ssMessage.imbue(std::locale("")); ssMessage << "INDEXING: "; ssMessage << pointsProcessed << " points processed; "; ssMessage << writer->numAccepted << " points written; "; ssMessage << seconds << " seconds passed"; cout << ssMessage.str() << endl; } if((pointsProcessed % (10'000'000)) == 0){ cout << "FLUSHING: "; auto start = high_resolution_clock::now(); writer->flush(); auto end = high_resolution_clock::now(); long long duration = duration_cast<milliseconds>(end-start).count(); float seconds = duration / 1'000.0f; cout << seconds << "s" << endl; } //if(pointsProcessed >= 10'000'000){ // break; //} } reader->close(); delete reader; } cout << "closing writer" << endl; writer->flush(); writer->close(); float percent = (float)writer->numAccepted / (float)pointsProcessed; percent = percent * 100; auto end = high_resolution_clock::now(); long long duration = duration_cast<milliseconds>(end-start).count(); cout << endl; cout << "conversion finished" << endl; cout << pointsProcessed << " points were processed and " << writer->numAccepted << " points ( " << percent << "% ) were written to the output. " << endl; cout << "duration: " << (duration / 1000.0f) << "s" << endl; } }
31.484177
154
0.668208
[ "vector" ]
163b1009b957552e53504ed11393d20bd448fefa
5,341
cc
C++
passes/equiv/equiv_purge.cc
smoe/yosys
1114ce9210dfb9a0db981029377dc859abc3aa34
[ "ISC", "Unlicense", "MIT" ]
null
null
null
passes/equiv/equiv_purge.cc
smoe/yosys
1114ce9210dfb9a0db981029377dc859abc3aa34
[ "ISC", "Unlicense", "MIT" ]
null
null
null
passes/equiv/equiv_purge.cc
smoe/yosys
1114ce9210dfb9a0db981029377dc859abc3aa34
[ "ISC", "Unlicense", "MIT" ]
null
null
null
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct EquivPurgeWorker { Module *module; SigMap sigmap; int name_cnt; EquivPurgeWorker(Module *module) : module(module), sigmap(module), name_cnt(0) { } SigSpec make_output(SigSpec sig, IdString cellname) { if (sig.is_wire()) { Wire *wire = sig.as_wire(); if (wire->name[0] == '\\') { if (!wire->port_output) { log(" Module output: %s (%s)\n", log_signal(wire), log_id(cellname)); wire->port_output = true; } return wire; } } while (1) { IdString name = stringf("\\equiv_%d", name_cnt++); if (module->count_id(name)) continue; Wire *wire = module->addWire(name, GetSize(sig)); wire->port_output = true; module->connect(wire, sig); log(" Module output: %s (%s)\n", log_signal(wire), log_id(cellname)); return wire; } } SigSpec make_input(SigSpec sig) { if (sig.is_wire()) { Wire *wire = sig.as_wire(); if (wire->name[0] == '\\') { if (!wire->port_output) { log(" Module input: %s\n", log_signal(wire)); wire->port_input = true; } return module->addWire(NEW_ID, GetSize(sig)); } } while (1) { IdString name = stringf("\\equiv_%d", name_cnt++); if (module->count_id(name)) continue; Wire *wire = module->addWire(name, GetSize(sig)); wire->port_input = true; module->connect(sig, wire); log(" Module input: %s\n", log_signal(wire)); return module->addWire(NEW_ID, GetSize(sig)); } } void run() { log("Running equiv_purge on module %s:\n", log_id(module)); for (auto wire : module->wires()) { wire->port_input = false; wire->port_output = false; } pool<SigBit> queue, visited; // cache for traversing signal flow graph dict<SigBit, pool<IdString>> up_bit2cells; dict<IdString, pool<SigBit>> up_cell2bits; for (auto cell : module->cells()) { if (cell->type != "$equiv") { for (auto &port : cell->connections()) { if (cell->input(port.first)) for (auto bit : sigmap(port.second)) up_cell2bits[cell->name].insert(bit); if (cell->output(port.first)) for (auto bit : sigmap(port.second)) up_bit2cells[bit].insert(cell->name); } continue; } SigSpec sig_a = sigmap(cell->getPort("\\A")); SigSpec sig_b = sigmap(cell->getPort("\\B")); SigSpec sig_y = sigmap(cell->getPort("\\Y")); if (sig_a == sig_b) continue; for (auto bit : sig_a) queue.insert(bit); for (auto bit : sig_b) queue.insert(bit); for (auto bit : sig_y) visited.insert(bit); cell->setPort("\\Y", make_output(sig_y, cell->name)); } SigSpec srcsig; SigMap rewrite_sigmap(module); while (!queue.empty()) { pool<SigBit> next_queue; for (auto bit : queue) visited.insert(bit); for (auto bit : queue) { auto &cells = up_bit2cells[bit]; if (cells.empty()) { srcsig.append(bit); } else { for (auto cell : cells) for (auto bit : up_cell2bits[cell]) if (visited.count(bit) == 0) next_queue.insert(bit); } } next_queue.swap(queue); } srcsig.sort_and_unify(); for (SigChunk chunk : srcsig.chunks()) if (chunk.wire != nullptr) rewrite_sigmap.add(chunk, make_input(chunk)); for (auto cell : module->cells()) if (cell->type == "$equiv") cell->setPort("\\Y", rewrite_sigmap(sigmap(cell->getPort("\\Y")))); module->fixup_ports(); } }; struct EquivPurgePass : public Pass { EquivPurgePass() : Pass("equiv_purge", "purge equivalence checking module") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" equiv_purge [options] [selection]\n"); log("\n"); log("This command removes the proven part of an equivalence checking module, leaving\n"); log("only the unproven segments in the design. This will also remove and add module\n"); log("ports as needed.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, Design *design) { log_header(design, "Executing EQUIV_PURGE pass.\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-foobar") { // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_whole_modules_warn()) { EquivPurgeWorker worker(module); worker.run(); } } } EquivPurgePass; PRIVATE_NAMESPACE_END
25.312796
91
0.63284
[ "vector" ]
163ce42ee7d3e1d925d0b950eb97c8ceb817c7c9
5,496
cc
C++
device/fido/fake_fido_discovery_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
device/fido/fake_fido_discovery_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
device/fido/fake_fido_discovery_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "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 2018 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 "device/fido/fake_fido_discovery.h" #include <utility> #include "base/test/bind.h" #include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "device/fido/fido_discovery_factory.h" #include "device/fido/fido_test_data.h" #include "device/fido/mock_fido_device.h" #include "device/fido/mock_fido_discovery_observer.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace device { namespace test { using ::testing::_; class FakeFidoDiscoveryTest : public ::testing::Test { public: FakeFidoDiscoveryTest() = default; FakeFidoDiscoveryTest(const FakeFidoDiscoveryTest&) = delete; FakeFidoDiscoveryTest& operator=(const FakeFidoDiscoveryTest&) = delete; ~FakeFidoDiscoveryTest() override = default; protected: FakeFidoDiscoveryFactory fake_fido_discovery_factory_; base::test::TaskEnvironment task_environment_; }; using FakeFidoDiscoveryFactoryTest = FakeFidoDiscoveryTest; TEST_F(FakeFidoDiscoveryTest, Transport) { FakeFidoDiscovery discovery_hid( FidoTransportProtocol::kUsbHumanInterfaceDevice); EXPECT_EQ(FidoTransportProtocol::kUsbHumanInterfaceDevice, discovery_hid.transport()); } TEST_F(FakeFidoDiscoveryTest, InitialState) { FakeFidoDiscovery discovery(FidoTransportProtocol::kUsbHumanInterfaceDevice); ASSERT_FALSE(discovery.is_running()); ASSERT_FALSE(discovery.is_start_requested()); } TEST_F(FakeFidoDiscoveryTest, StartDiscovery) { FakeFidoDiscovery discovery(FidoTransportProtocol::kUsbHumanInterfaceDevice); MockFidoDiscoveryObserver observer; discovery.set_observer(&observer); discovery.Start(); ASSERT_TRUE(discovery.is_start_requested()); ASSERT_FALSE(discovery.is_running()); EXPECT_CALL(observer, DiscoveryStarted(&discovery, true, std::vector<FidoAuthenticator*>())); discovery.WaitForCallToStartAndSimulateSuccess(); ASSERT_TRUE(discovery.is_running()); ASSERT_TRUE(discovery.is_start_requested()); } TEST_F(FakeFidoDiscoveryTest, WaitThenStartStopDiscovery) { FakeFidoDiscovery discovery(FidoTransportProtocol::kUsbHumanInterfaceDevice); MockFidoDiscoveryObserver observer; discovery.set_observer(&observer); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindLambdaForTesting([&]() { discovery.Start(); })); discovery.WaitForCallToStart(); ASSERT_FALSE(discovery.is_running()); ASSERT_TRUE(discovery.is_start_requested()); EXPECT_CALL(observer, DiscoveryStarted(&discovery, true, std::vector<FidoAuthenticator*>())); discovery.SimulateStarted(true); ASSERT_TRUE(discovery.is_running()); ASSERT_TRUE(discovery.is_start_requested()); } // Starting discovery and failing: instance stays in "not running" state TEST_F(FakeFidoDiscoveryTest, StartFail) { FakeFidoDiscovery discovery(FidoTransportProtocol::kUsbHumanInterfaceDevice); MockFidoDiscoveryObserver observer; discovery.set_observer(&observer); discovery.Start(); ASSERT_FALSE(discovery.is_running()); ASSERT_TRUE(discovery.is_start_requested()); EXPECT_CALL(observer, DiscoveryStarted(&discovery, false, std::vector<FidoAuthenticator*>())); discovery.SimulateStarted(false); ASSERT_FALSE(discovery.is_running()); ASSERT_TRUE(discovery.is_start_requested()); } // Adding device is possible both before and after discovery actually starts. TEST_F(FakeFidoDiscoveryTest, AddDevice) { FakeFidoDiscovery discovery(FidoTransportProtocol::kUsbHumanInterfaceDevice); MockFidoDiscoveryObserver observer; discovery.set_observer(&observer); discovery.Start(); auto device0 = std::make_unique<MockFidoDevice>(); EXPECT_CALL(*device0, GetId()).WillOnce(::testing::Return("device0")); base::RunLoop device0_done; discovery.AddDevice(std::move(device0)); EXPECT_CALL(observer, DiscoveryStarted(&discovery, true, testing::SizeIs(1))) .WillOnce(testing::InvokeWithoutArgs( [&device0_done]() { device0_done.Quit(); })); discovery.SimulateStarted(true); device0_done.Run(); ::testing::Mock::VerifyAndClearExpectations(&observer); auto device1 = std::make_unique<MockFidoDevice>(); EXPECT_CALL(*device1, GetId()).WillOnce(::testing::Return("device1")); base::RunLoop device1_done; EXPECT_CALL(observer, AuthenticatorAdded(&discovery, _)) .WillOnce(testing::InvokeWithoutArgs( [&device1_done]() { device1_done.Quit(); })); discovery.AddDevice(std::move(device1)); device1_done.Run(); ::testing::Mock::VerifyAndClearExpectations(&observer); } #if !defined(OS_ANDROID) TEST_F(FakeFidoDiscoveryFactoryTest, ForgesUsbFactoryFunction) { auto* injected_fake_discovery = fake_fido_discovery_factory_.ForgeNextHidDiscovery(); ASSERT_EQ(FidoTransportProtocol::kUsbHumanInterfaceDevice, injected_fake_discovery->transport()); std::vector<std::unique_ptr<FidoDiscoveryBase>> produced_discoveries = fake_fido_discovery_factory_.Create( FidoTransportProtocol::kUsbHumanInterfaceDevice); ASSERT_EQ(produced_discoveries.size(), 1u); EXPECT_EQ(injected_fake_discovery, produced_discoveries[0].get()); } #endif } // namespace test } // namespace device
34.35
79
0.762555
[ "vector" ]
163fc2c64ac544d2aecf014d33452bf471e75a8e
5,839
cpp
C++
eddiebot_apps/room_segmentation/common/src/morphological_segmentation.cpp
TooSchoolForCool/EddieBot-ROS
5dad6d5a6eb974135b7c9587abc0ae17d1ec6760
[ "Apache-2.0" ]
5
2019-05-15T19:31:47.000Z
2019-08-31T01:12:35.000Z
eddiebot_apps/room_segmentation/common/src/morphological_segmentation.cpp
TooSchoolForCool/EddieBot-ROS
5dad6d5a6eb974135b7c9587abc0ae17d1ec6760
[ "Apache-2.0" ]
null
null
null
eddiebot_apps/room_segmentation/common/src/morphological_segmentation.cpp
TooSchoolForCool/EddieBot-ROS
5dad6d5a6eb974135b7c9587abc0ae17d1ec6760
[ "Apache-2.0" ]
4
2019-06-03T12:21:44.000Z
2019-12-25T08:57:46.000Z
#include <room_segmentation/morphological_segmentation.h> #include <room_segmentation/wavefront_region_growing.h> #include <room_segmentation/contains.h> MorphologicalSegmentation::MorphologicalSegmentation() { } void MorphologicalSegmentation::segmentMap(const cv::Mat& map_to_be_labeled, cv::Mat& segmented_map, double map_resolution_from_subscription, double room_area_factor_lower_limit, double room_area_factor_upper_limit) { /*This segmentation algorithm does: * 1. collect the map data * 2. erode the map to extract contours * 3. find the extracted contures and save them if they fullfill the room-area criterion * 4. draw and fill the saved contoures in a clone of the map from 1. with a random colour * 5. get the obstacle information from the original map and draw them in the clone from 4. * 6. spread the coloured regions to the white Pixels */ //make two map clones to work with cv::Mat temporary_map_to_find_rooms = map_to_be_labeled.clone(); //map to find the rooms and for eroding //**************erode temporary_map until last possible room found**************** //erode map a specified amount of times std::vector < std::vector<cv::Point> > saved_contours; //saving variable for every contour that is between the upper and the lower limit ROS_INFO("starting eroding"); for (int counter = 0; counter < 73; counter++) { //erode the map one time cv::Mat eroded_map; cv::Point anchor(-1, -1); //needed for opencv erode cv::erode(temporary_map_to_find_rooms, eroded_map, cv::Mat(), anchor, 1); //save the more eroded map temporary_map_to_find_rooms = eroded_map; //Save the eroded map in a second map, which is used to find the contours. This is neccesarry, because //the function findContours changes the given map and would make it impossible to work any further with it cv::Mat contour_map = eroded_map.clone(); //find Contours in the more eroded map std::vector < std::vector<cv::Point> > temporary_contours; //temporary saving-variable //hierarchy saves if the contours are hole-contours: //hierarchy[{0,1,2,3}]={next contour (same level), previous contour (same level), child contour, parent contour} //child-contour = 1 if it has one, = -1 if not, same for parent_contour std::vector < cv::Vec4i > hierarchy; cv::findContours(contour_map, temporary_contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); if (temporary_contours.size() != 0) { //check every contour if it fullfills the criteria of a room for (int current_contour = 0; current_contour < temporary_contours.size(); current_contour++) { //only take first level contours --> second level contours belong to holes and doesn't need to be looked at if (hierarchy[current_contour][3] == -1) { //check if contour is large/small enough for a room double room_area = map_resolution_from_subscription * map_resolution_from_subscription * cv::contourArea(temporary_contours[current_contour]); //subtract the area from the hole contours inside the found contour, because the contour area grows extremly large if it is a closed loop for (int hole = 0; hole < temporary_contours.size(); hole++) { if (hierarchy[hole][3] == current_contour) //check if the parent of the hole is the current looked at contour { room_area -= map_resolution_from_subscription * map_resolution_from_subscription * cv::contourArea(temporary_contours[hole]); } } if (room_area_factor_lower_limit < room_area && room_area < room_area_factor_upper_limit) { //save contour for later drawing in map saved_contours.push_back(temporary_contours[current_contour]); //make region black if room found --> region doesn't need to be looked at anymore cv::drawContours(temporary_map_to_find_rooms, temporary_contours, current_contour, cv::Scalar(0), CV_FILLED, 8, hierarchy, 2); } } } } } //*******************draw contures in new map*********************** std::cout << "Segmentation Found " << saved_contours.size() << " rooms." << std::endl; //draw filled contoures in new_map_to_draw_contours_ with random colour if this colour hasn't been used yet cv::Mat new_map_to_draw_contours; //map for drawing the found contours map_to_be_labeled.convertTo(segmented_map, CV_32SC1, 256, 0); std::vector < cv::Scalar > already_used_coloures; //vector for saving the already used coloures for (int idx = 0; idx < saved_contours.size(); idx++) { bool drawn = false; //checking-variable if contour has been drawn int draw_counter = 0; //counter to exit loop if it gets into an endless-loop (e.g. when there are more rooms than possible) do { draw_counter++; cv::Scalar fill_colour(rand() % 52224 + 13056); if (!contains(already_used_coloures, fill_colour) || draw_counter > 250) { //if colour is unique draw Contour in map cv::drawContours(segmented_map, saved_contours, idx, fill_colour, CV_FILLED); already_used_coloures.push_back(fill_colour); //add colour to used coloures drawn = true; } } while (!drawn); } //*************************obstacles*********************** //get obstacle informations and draw them into the new map ROS_INFO("starting getting obstacle information"); for (int row = 0; row < map_to_be_labeled.rows; ++row) { for (int col = 0; col < map_to_be_labeled.cols; ++col) { //find obstacles = black pixels if (map_to_be_labeled.at<unsigned char>(row, col) == 0) { segmented_map.at<int>(row, col) = 0; } } } ROS_INFO("drawn obstacles in map"); //**************spread the colored region by making white pixel around a contour their color**************** //spread the coloured regions to the white Pixels wavefrontRegionGrowing(segmented_map); ROS_INFO("filled white pixels in new map"); }
48.256198
142
0.712793
[ "vector" ]
16404085b7dbb0f14593aab7b03bc638c7d4ae6a
10,921
cpp
C++
pleasework/SerialPort.cpp
macrobomaster/cv-pi
df5a24faba45aa671b05ccc498eeeceda2d82ad7
[ "MIT" ]
null
null
null
pleasework/SerialPort.cpp
macrobomaster/cv-pi
df5a24faba45aa671b05ccc498eeeceda2d82ad7
[ "MIT" ]
null
null
null
pleasework/SerialPort.cpp
macrobomaster/cv-pi
df5a24faba45aa671b05ccc498eeeceda2d82ad7
[ "MIT" ]
1
2019-02-26T19:31:20.000Z
2019-02-26T19:31:20.000Z
//! //! @file SerialPort.cpp //! @author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja) //! @created 2014-01-07 //! @last-modified 2017-11-27 //! @brief The main serial port class. //! @details //! See README.rst in repo root dir for more info. // System includes #include <iostream> #include <sstream> #include <stdio.h> // Standard input/output definitions #include <string.h> // String function definitions #include <unistd.h> // UNIX standard function definitions #include <fcntl.h> // File control definitions #include <errno.h> // Error number definitions #include <termios.h> // POSIX terminal control definitions (struct termios) #include <system_error> // For throwing std::system_error // User includescommx1out #include "Exception.hpp" #include "SerialPort.hpp" namespace mn { namespace CppLinuxSerial { SerialPort::SerialPort() { echo_ = false; timeout_ms_ = defaultTimeout_ms_; baudRate_ = defaultBaudRate_; readBufferSize_B_ = defaultReadBufferSize_B_; readBuffer_.reserve(readBufferSize_B_); } SerialPort::SerialPort(const std::string& device, BaudRate baudRate) : SerialPort() { device_ = device; baudRate_ = baudRate; } SerialPort::~SerialPort() { try { Close(); } catch(...) { // We can't do anything about this! // But we don't want to throw within destructor, so swallow } } void SerialPort::SetDevice(const std::string& device) { device_ = device; if(state_ == State::OPEN) ConfigureTermios(); } void SerialPort::SetBaudRate(BaudRate baudRate) { baudRate_ = baudRate; if(state_ == State::OPEN) ConfigureTermios(); } void SerialPort::Open() { //std::cout << "Attempting to open COM port \"" << device_ << "\"." << std::endl; if(device_.empty()) { THROW_EXCEPT("Attempted to open file when file path has not been assigned to."); } // Attempt to open file //this->fileDesc = open(this->filePath, O_RDWR | O_NOCTTY | O_NDELAY); // O_RDONLY for read-only, O_WRONLY for write only, O_RDWR for both read/write access // 3rd, optional parameter is mode_t mode fileDesc_ = open(device_.c_str(), O_RDWR); // Check status if(fileDesc_ == -1) { THROW_EXCEPT("Could not open device " + device_ + ". Is the device name correct and do you have read/write permission?"); } ConfigureTermios(); // std::cout << "COM port opened successfully." << std::endl; state_ = State::OPEN; } void SerialPort::SetEcho(bool value) { echo_ = value; ConfigureTermios(); } void SerialPort::ConfigureTermios() { //std::cout << "Configuring COM port \"" << device_ << "\"." << std::endl; //================== CONFIGURE ==================// termios tty = GetTermios(); //================= (.c_cflag) ===============// tty.c_cflag &= ~PARENB; // No parity bit is added to the output characters tty.c_cflag &= ~CSTOPB; // Only one stop-bit is used tty.c_cflag &= ~CSIZE; // CSIZE is a mask for the number of bits per character tty.c_cflag |= CS8; // Set to 8 bits per character tty.c_cflag &= ~CRTSCTS; // Disable hadrware flow control (RTS/CTS) tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1) //===================== BAUD RATE =================// switch(baudRate_) { case BaudRate::B_9600: cfsetispeed(&tty, B9600); cfsetospeed(&tty, B9600); break; case BaudRate::B_38400: cfsetispeed(&tty, B38400); cfsetospeed(&tty, B38400); break; case BaudRate::B_57600: cfsetispeed(&tty, B57600); cfsetospeed(&tty, B57600); break; case BaudRate::B_115200: cfsetispeed(&tty, B115200); cfsetospeed(&tty, B115200); break; case BaudRate::CUSTOM: // See https://gist.github.com/kennethryerson/f7d1abcf2633b7c03cf0 throw std::runtime_error("Custom baud rate not yet supported."); default: throw std::runtime_error(std::string() + "baudRate passed to " + __PRETTY_FUNCTION__ + " unrecognized."); } //===================== (.c_oflag) =================// tty.c_oflag = 0; // No remapping, no delays tty.c_oflag &= ~OPOST; // Make raw //================= CONTROL CHARACTERS (.c_cc[]) ==================// // c_cc[VTIME] sets the inter-character timer, in units of 0.1s. // Only meaningful when port is set to non-canonical mode // VMIN = 0, VTIME = 0: No blocking, return immediately with what is available // VMIN > 0, VTIME = 0: read() waits for VMIN bytes, could block indefinitely // VMIN = 0, VTIME > 0: Block until any amount of data is available, OR timeout occurs // VMIN > 0, VTIME > 0: Block until either VMIN characters have been received, or VTIME // after first character has elapsed // c_cc[WMIN] sets the number of characters to block (wait) for when read() is called. // Set to 0 if you don't want read to block. Only meaningful when port set to non-canonical mode if(timeout_ms_ == -1) { // Always wait for at least one byte, this could // block indefinitely tty.c_cc[VTIME] = 0; tty.c_cc[VMIN] = 1; } else if(timeout_ms_ == 0) { // Setting both to 0 will give a non-blocking read tty.c_cc[VTIME] = 0; tty.c_cc[VMIN] = 0; } else if(timeout_ms_ > 0) { tty.c_cc[VTIME] = (cc_t)(timeout_ms_/100); // 0.5 seconds read timeout tty.c_cc[VMIN] = 0; } //======================== (.c_iflag) ====================// tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); //=========================== LOCAL MODES (c_lflag) =======================// // Canonical input is when read waits for EOL or EOF characters before returning. In non-canonical mode, the rate at which // read() returns is instead controlled by c_cc[VMIN] and c_cc[VTIME] tty.c_lflag &= ~ICANON; // Turn off canonical input, which is suitable for pass-through echo_ ? (tty.c_lflag | ECHO ) : (tty.c_lflag & ~(ECHO)); // Configure echo depending on echo_ boolean tty.c_lflag &= ~ECHOE; // Turn off echo erase (echo erase only relevant if canonical input is active) tty.c_lflag &= ~ECHONL; // tty.c_lflag &= ~ISIG; // Disables recognition of INTR (interrupt), QUIT and SUSP (suspend) characters // Try and use raw function call //cfmakeraw(&tty); this->SetTermios(tty); /* // Flush port, then apply attributes tcflush(this->fileDesc, TCIFLUSH); if(tcsetattr(this->fileDesc, TCSANOW, &tty) != 0) { // Error occurred this->sp->PrintError(SmartPrint::Ss() << "Could not apply terminal attributes for \"" << this->filePath << "\" - " << strerror(errno)); return; }*/ } void SerialPort::Write(unsigned char* data) { if(state_ != State::OPEN) THROW_EXCEPT(std::string() + __PRETTY_FUNCTION__ + " called but state != OPEN. Please call Open() first."); if(fileDesc_ < 0) { THROW_EXCEPT(std::string() + __PRETTY_FUNCTION__ + " called but file descriptor < 0, indicating file has not been opened."); } //std::cout << data.c_str() << std::endl; //Wstd::cout << data.size() << std::endl; int writeResult = write(fileDesc_, data, 1); // Check status if (writeResult == -1) { throw std::system_error(EFAULT, std::system_category()); } } void SerialPort::Read(std::string& data) { data.clear(); if(fileDesc_ == 0) { //this->sp->PrintError(SmartPrint::Ss() << "Read() was called but file descriptor (fileDesc) was 0, indicating file has not been opened."); //return false; THROW_EXCEPT("Read() was called but file descriptor (fileDesc) was 0, indicating file has not been opened."); } // Allocate memory for read buffer // char buf [256]; // memset (&buf, '\0', sizeof buf); // Read from file // We provide the underlying raw array from the readBuffer_ vector to this C api. // This will work because we do not delete/resize the vector while this method // is called ssize_t n = read(fileDesc_, &readBuffer_[0], readBufferSize_B_); // Error Handling if(n < 0) { // Read was unsuccessful throw std::system_error(EFAULT, std::system_category()); } if(n > 0) { // buf[n] = '\0'; //printf("%s\r\n", buf); // data.append(buf); data = std::string(&readBuffer_[0], n); //std::cout << *str << " and size of string =" << str->size() << "\r\n"; } // If code reaches here, read must of been successful } termios SerialPort::GetTermios() { if(fileDesc_ == -1) throw std::runtime_error("GetTermios() called but file descriptor was not valid."); struct termios tty; memset(&tty, 0, sizeof(tty)); // Get current settings (will be stored in termios structure) if(tcgetattr(fileDesc_, &tty) != 0) { // Error occurred std::cout << "Could not get terminal attributes for \"" << device_ << "\" - " << strerror(errno) << std::endl; throw std::system_error(EFAULT, std::system_category()); //return false; } return tty; } void SerialPort::SetTermios(termios myTermios) { // Flush port, then apply attributes tcflush(fileDesc_, TCIFLUSH); if(tcsetattr(fileDesc_, TCSANOW, &myTermios) != 0) { // Error occurred std::cout << "Could not apply terminal attributes for \"" << device_ << "\" - " << strerror(errno) << std::endl; throw std::system_error(EFAULT, std::system_category()); } // Successful! } void SerialPort::Close() { if(fileDesc_ != -1) { auto retVal = close(fileDesc_); if(retVal != 0) THROW_EXCEPT("Tried to close serial port " + device_ + ", but close() failed."); fileDesc_ = -1; } state_ = State::CLOSED; } void SerialPort::SetTimeout(int32_t timeout_ms) { if(timeout_ms < -1) THROW_EXCEPT(std::string() + "timeout_ms provided to " + __PRETTY_FUNCTION__ + " was < -1, which is invalid."); if(timeout_ms > 25500) THROW_EXCEPT(std::string() + "timeout_ms provided to " + __PRETTY_FUNCTION__ + " was > 25500, which is invalid."); if(state_ == State::OPEN) THROW_EXCEPT(std::string() + __PRETTY_FUNCTION__ + " called while state == OPEN."); timeout_ms_ = timeout_ms; } } // namespace CppLinuxSerial } // namespace mn
33.603077
142
0.592162
[ "vector" ]
f37ee289975952def83c784189f058192134d339
3,045
cpp
C++
benchpress/benchmarks/black_scholes/cpp11_seq/src/black_scholes.cpp
bh107/benchpress
e1dcda446a986d4d828b14d807e37e10cf4a046b
[ "Apache-2.0" ]
6
2015-03-31T15:39:40.000Z
2022-03-16T21:30:49.000Z
benchpress/benchmarks/black_scholes/cpp11_seq/src/black_scholes.cpp
bh107/benchpress
e1dcda446a986d4d828b14d807e37e10cf4a046b
[ "Apache-2.0" ]
8
2015-04-13T12:03:56.000Z
2018-11-28T13:31:11.000Z
benchpress/benchmarks/black_scholes/cpp11_seq/src/black_scholes.cpp
bh107/benchpress
e1dcda446a986d4d828b14d807e37e10cf4a046b
[ "Apache-2.0" ]
4
2018-06-28T08:06:37.000Z
2021-05-20T17:30:25.000Z
#include <iostream> #include <sstream> #include <string> #include <cmath> #include <Random123/philox.h> #include <bp_util.h> using namespace std; typedef union philox2x32_as_1x64 { philox2x32_ctr_t orig; uint64_t combined; } philox2x32_as_1x64_t; double* model(int64_t samples) { const uint64_t key = 0; double* data = (double*)malloc(sizeof(double)*samples); for(int64_t count = 0; count<samples; ++count) { philox2x32_as_1x64_t counter; counter.combined = count; philox2x32_as_1x64_t x_philox; x_philox.orig = philox2x32( counter.orig, (philox2x32_key_t){ { key } } ); double x = x_philox.combined; x /= 18446744073709551616.000000; x *= 4.0; x += 58.0; // Model between 58-62 data[count] = x; } return data; } // The cumulative normal distribution function double cnd( double x ) { double L, K, w; double const a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937, a4 = -1.821255978, a5 = 1.330274429; L = fabs(x); K = 1.0 / (1.0 + 0.2316419 * L); w = 1.0 - 1.0 / sqrt(2 * M_PI) * exp(-L *L / 2) * (\ a1 * K + \ a2 * pow(K, 2) + \ a3 * pow(K, 3) + \ a4 * pow(K, 4) + \ a5 * pow(K, 5) ); return (x<0) ? 1.0 - w : w; } // The Black and Scholes (1973) Stock option formula void pricing(double* market, double *prices, size_t samples, size_t iterations, char flag, double x, double d_t, double r, double v) { double t = d_t; for(size_t iter=0; iter<iterations; ++iter) { double res = 0; for(size_t sample=0; sample<samples; ++sample) { double d1 = (log(market[sample]/x) + (r+v*v/2)*t) / (v*sqrt(t)); double d2 = d1-v*sqrt(t); if (flag == 'c') { res += market[sample] *cnd(d1)-x * exp(-r*t)*cnd(d2); } else { res += x * exp(-r*t) * cnd(-d2) - market[sample] * cnd(-d1); } } t += d_t; prices[iter] = res / samples; } } int main(int argc, char* argv[]) { bp_util_type bp = bp_util_create(argc, argv, 2); if (bp.args.has_error) { return 0; } const int samples = bp.args.sizes[0]; const int iterations = bp.args.sizes[1]; double* market = model(samples); // Generate pseudo-market data double* prices = (double*)malloc(sizeof(double)*iterations); // Prices bp.timer_start(); pricing( market, prices, samples, iterations, 'c', 65.0, 1.0 / 365.0, 0.08, 0.3 ); bp.timer_stop(); bp.print("black_scholes(cpp11_seq)"); if (bp.args.verbose) { // and values. printf("output: [ "); for(int i=0; i<iterations; ++i) { printf("%f ", prices[i]); } printf("]\n"); } free(market); free(prices); return 0; }
24.756098
76
0.516913
[ "model" ]
f380513b11c34b08e7b3443c735793edfad96dd4
1,241
cpp
C++
smacc/src/smacc/client.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
203
2019-04-11T16:42:10.000Z
2022-03-18T06:02:56.000Z
smacc/src/smacc/client.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
50
2019-04-18T09:09:48.000Z
2022-03-29T21:38:21.000Z
smacc/src/smacc/client.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
35
2019-09-10T15:06:37.000Z
2022-02-02T09:10:08.000Z
/***************************************************************************************************************** * ReelRobotix Inc. - Software License Agreement Copyright (c) 2018 * Authors: Pablo Inigo Blasco, Brett Aldrich * ******************************************************************************************************************/ #include <smacc/smacc_client.h> #include <smacc/impl/smacc_client_impl.h> namespace smacc { ISmaccClient::ISmaccClient() { } ISmaccClient::~ISmaccClient() { } void ISmaccClient::initialize() { } void ISmaccClient::getComponents(std::vector<std::shared_ptr<ISmaccComponent>> &components) { for (auto &ce : components_) { components.push_back(ce.second); } } std::string ISmaccClient::getName() const { std::string keyname = demangleSymbol(typeid(*this).name()); return keyname; } void ISmaccClient::setStateMachine(ISmaccStateMachine *stateMachine) { stateMachine_ = stateMachine; } void ISmaccClient::setOrthogonal(ISmaccOrthogonal* orthogonal) { orthogonal_ = orthogonal; } smacc::introspection::TypeInfo::Ptr ISmaccClient::getType() { return smacc::introspection::TypeInfo::getFromStdTypeInfo(typeid(*this)); } } // namespace smacc
22.563636
116
0.589041
[ "vector" ]
f38805b7f7dd1180df893996e7c883d502c1b6fa
11,565
cpp
C++
pxr/usd/lib/usd/clipCache.cpp
marsupial/USD
98d49911893d59be5a9904a29e15959affd530ec
[ "BSD-3-Clause" ]
9
2021-03-31T21:23:48.000Z
2022-03-05T09:29:27.000Z
pxr/usd/lib/usd/clipCache.cpp
marsupial/USD
98d49911893d59be5a9904a29e15959affd530ec
[ "BSD-3-Clause" ]
null
null
null
pxr/usd/lib/usd/clipCache.cpp
marsupial/USD
98d49911893d59be5a9904a29e15959affd530ec
[ "BSD-3-Clause" ]
1
2021-04-15T16:18:55.000Z
2021-04-15T16:18:55.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usd/clipCache.h" #include "pxr/usd/usd/debugCodes.h" #include "pxr/usd/usd/prim.h" #include "pxr/usd/usd/resolver.h" #include "pxr/usd/usd/tokens.h" #include "pxr/usd/pcp/layerStack.h" #include "pxr/usd/pcp/node.h" #include "pxr/usd/sdf/assetPath.h" #include "pxr/usd/sdf/layer.h" #include "pxr/usd/sdf/path.h" #include "pxr/base/vt/array.h" #include "pxr/base/gf/vec2d.h" #include "pxr/base/tf/ostreamMethods.h" #include <string> Usd_ClipCache::Usd_ClipCache() { } Usd_ClipCache::~Usd_ClipCache() { } struct Usd_ClipEntry { public: double startTime; SdfAssetPath clipAssetPath; SdfPath clipPrimPath; }; static bool _ValidateClipFields( const VtArray<SdfAssetPath>& clipAssetPaths, const std::string& clipPrimPath, const VtVec2dArray& clipActive, std::string* errMsg) { // Note that we do allow empty clipAssetPath and clipActive data; // this provides users with a way to 'block' clips specified in a // weaker layer. if (clipPrimPath.empty()) { *errMsg = "No clip prim path specified"; return false; } const size_t numClips = clipAssetPaths.size(); // Each entry in the 'clipAssetPaths' array is the asset path to a clip. for (const auto& clipAssetPath : clipAssetPaths) { if (clipAssetPath.GetAssetPath().empty()) { *errMsg = TfStringPrintf("Empty clip asset path in metadata '%s'", UsdTokens->clipAssetPaths.GetText()); return false; } } // The 'clipPrimPath' field identifies a prim from which clip data // will be read. if (not SdfPath::IsValidPathString(clipPrimPath, errMsg)) { return false; } const SdfPath path(clipPrimPath); if (not (path.IsAbsolutePath() and path.IsPrimPath())) { *errMsg = TfStringPrintf( "Path '%s' in metadata '%s' must be an absolute path to a prim", clipPrimPath.c_str(), UsdTokens->clipPrimPath.GetText()); return false; } // Each Vec2d in the 'clipActive' array is a (start frame, clip index) // tuple. Ensure the clip index points to a valid clip. for (const auto& startFrameAndClipIndex : clipActive) { if (startFrameAndClipIndex[1] < 0 or startFrameAndClipIndex[1] >= numClips) { *errMsg = TfStringPrintf( "Invalid clip index %d in metadata '%s'", (int)startFrameAndClipIndex[1], UsdTokens->clipActive.GetText()); return false; } } // Ensure that 'clipActive' does not specify multiple clips to be // active at the same time. typedef std::map<double, int> _ActiveClipMap; _ActiveClipMap activeClipMap; for (const auto& startFrameAndClipIndex : clipActive) { std::pair<_ActiveClipMap::iterator, bool> status = activeClipMap.insert(std::make_pair( startFrameAndClipIndex[0], startFrameAndClipIndex[1])); if (not status.second) { *errMsg = TfStringPrintf( "Clip %d cannot be active at time %.3f in metadata '%s' " "because clip %d was already specified as active at this time.", (int)startFrameAndClipIndex[1], startFrameAndClipIndex[0], UsdTokens->clipActive.GetText(), status.first->second); return false; } } return true; } static void _AddClipsFromNode( const PcpNodeRef& node, Usd_ClipCache::Clips* clips) { Usd_ResolvedClipInfo clipInfo; Usd_ResolveClipInfo(node, &clipInfo); // If we haven't found all of the required clip metadata we can just // bail out. Note that clipTimes and clipManifestAssetPath are *not* // required. if (not clipInfo.clipAssetPaths or not clipInfo.clipPrimPath or not clipInfo.clipActive) { return; } // The clip manifest is currently optional but can greatly improve // performance if specified. For debugging performance problems, // issue a message indicating if one hasn't been specified. if (not clipInfo.clipManifestAssetPath) { TF_DEBUG(USD_CLIPS).Msg( "No clip manifest specified for prim <%s> in LayerStack " "%s at spec <%s>. Performance may be improved if a " "manifest is specified.", node.GetRootNode().GetPath().GetString().c_str(), TfStringify(node.GetLayerStack()).c_str(), node.GetPath().GetString().c_str()); } // XXX: Possibly want a better way to inform consumers of the error // message.. std::string error; if (not _ValidateClipFields( *clipInfo.clipAssetPaths, *clipInfo.clipPrimPath, *clipInfo.clipActive, &error)) { TF_WARN( "Invalid clips specified for prim <%s> in LayerStack %s: %s", node.GetPath().GetString().c_str(), TfStringify(node.GetLayerStack()).c_str(), error.c_str()); return; } // If a clip manifest has been specified, create a clip for it. if (clipInfo.clipManifestAssetPath) { const Usd_ClipRefPtr clip(new Usd_Clip( /* clipSourceNode = */ node, /* clipSourceLayerIndex = */ clipInfo.indexOfLayerWhereAssetPathsFound, /* clipAssetPath = */ *clipInfo.clipManifestAssetPath, /* clipPrimPath = */ SdfPath(*clipInfo.clipPrimPath), /* clipStartTime = */ Usd_ClipTimesEarliest, /* clipEndTime = */ Usd_ClipTimesLatest, /* clipTimes = */ Usd_Clip::TimeMappings())); clips->manifestClip = clip; } // Generate a mapping of startTime -> clip entry. This allows us to // quickly determine the (startTime, endTime) for a given clip. typedef std::map<double, Usd_ClipEntry> _TimeToClipMap; _TimeToClipMap startTimeToClip; for (const auto& startFrameAndClipIndex : *clipInfo.clipActive) { const double startFrame = startFrameAndClipIndex[0]; const int clipIndex = (int)(startFrameAndClipIndex[1]); const SdfAssetPath& assetPath = (*clipInfo.clipAssetPaths)[clipIndex]; Usd_ClipEntry entry; entry.startTime = startFrame; entry.clipAssetPath = assetPath; entry.clipPrimPath = SdfPath(*clipInfo.clipPrimPath); // Validation should have caused us to bail out if there were any // conflicting clip activations set. TF_VERIFY(startTimeToClip.insert( std::make_pair(entry.startTime, entry)).second); } // Build up the final vector of clips. const _TimeToClipMap::const_iterator itBegin = startTimeToClip.begin(); const _TimeToClipMap::const_iterator itEnd = startTimeToClip.end(); _TimeToClipMap::const_iterator it = startTimeToClip.begin(); while (it != itEnd) { const Usd_ClipEntry clipEntry = it->second; const Usd_Clip::ExternalTime clipStartTime = (it == itBegin ? Usd_ClipTimesEarliest : it->first); ++it; const Usd_Clip::ExternalTime clipEndTime = (it == itEnd ? Usd_ClipTimesLatest : it->first); // Generate the clip time mapping that applies to this clip. Usd_Clip::TimeMappings timeMapping; if (clipInfo.clipTimes) { for (const auto& clipTime : *clipInfo.clipTimes) { const Usd_Clip::ExternalTime extTime = clipTime[0]; const Usd_Clip::InternalTime intTime = clipTime[1]; if (clipStartTime <= extTime and extTime < clipEndTime) { timeMapping.push_back( Usd_Clip::TimeMapping(extTime, intTime)); } } } const Usd_ClipRefPtr clip(new Usd_Clip( /* clipSourceNode = */ node, /* clipSourceLayerIndex = */ clipInfo.indexOfLayerWhereAssetPathsFound, /* clipAssetPath = */ clipEntry.clipAssetPath, /* clipPrimPath = */ clipEntry.clipPrimPath, /* clipStartTime = */ clipStartTime, /* clipEndTime = */ clipEndTime, /* clipTimes = */ timeMapping)); clips->valueClips.push_back(clip); } clips->sourceNode = node; clips->sourceLayerIndex = clipInfo.indexOfLayerWhereAssetPathsFound; } bool Usd_ClipCache::PopulateClipsForPrim( const SdfPath& path, const PcpPrimIndex& primIndex) { TRACE_FUNCTION(); std::vector<Clips> allClips; for (Usd_Resolver res(&primIndex); res.IsValid(); res.NextNode()) { Clips clipsFromNode; _AddClipsFromNode(res.GetNode(), &clipsFromNode); if (not clipsFromNode.valueClips.empty()) { allClips.push_back(clipsFromNode); } }; const bool primHasClips = not allClips.empty(); if (primHasClips) { tbb::mutex::scoped_lock lock(_mutex); const std::vector<Clips>& ancestralClips = _GetClipsForPrim_NoLock(path.GetParentPath()); allClips.insert( allClips.end(), ancestralClips.begin(), ancestralClips.end()); TF_DEBUG(USD_CLIPS).Msg( "Populated clips for prim <%s>\n", path.GetString().c_str()); _table[path].swap(allClips); } return primHasClips; } const std::vector<Usd_ClipCache::Clips>& Usd_ClipCache::GetClipsForPrim(const SdfPath& path) const { TRACE_FUNCTION(); tbb::mutex::scoped_lock lock(_mutex); return _GetClipsForPrim_NoLock(path); } const std::vector<Usd_ClipCache::Clips>& Usd_ClipCache::_GetClipsForPrim_NoLock(const SdfPath& path) const { for (SdfPath p = path; p != SdfPath::AbsoluteRootPath(); p = p.GetParentPath()) { _ClipTable::const_iterator it = _table.find(p); if (it != _table.end()) { return it->second; } } static const std::vector<Clips> empty; return empty; } void Usd_ClipCache::InvalidateClipsForPrim(const SdfPath& path, Lifeboat* lifeboat) { tbb::mutex::scoped_lock lock(_mutex); auto range = _table.FindSubtreeRange(path); for (auto entryIter = range.first; entryIter != range.second; ++entryIter) { const auto& entry = *entryIter; lifeboat->_clips.insert( lifeboat->_clips.end(), entry.second.begin(), entry.second.end()); } _table.erase(path); }
34.834337
80
0.635452
[ "vector" ]
f38cf9591e959c01f8b0c369377cb8f688fc29d9
7,831
cc
C++
bench/qs8-vmul.cc
Pandinosaurus/XNNPACK
5c7fd89ef54bd04feae964a19ce26b69afd9c804
[ "BSD-3-Clause" ]
null
null
null
bench/qs8-vmul.cc
Pandinosaurus/XNNPACK
5c7fd89ef54bd04feae964a19ce26b69afd9c804
[ "BSD-3-Clause" ]
null
null
null
bench/qs8-vmul.cc
Pandinosaurus/XNNPACK
5c7fd89ef54bd04feae964a19ce26b69afd9c804
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <cmath> #include <functional> #include <random> #include <vector> #include <benchmark/benchmark.h> #include "bench/utils.h" #include <xnnpack/AlignedAllocator.h> #include <xnnpack/common.h> #include <xnnpack/params.h> #include <xnnpack/params-init.h> #include <xnnpack/vmul.h> static void qs8_vmul( benchmark::State& state, xnn_qs8_vmul_minmax_ukernel_function vmul, xnn_init_qs8_mul_minmax_params_fn init_params, benchmark::utils::IsaCheckFunction isa_check = nullptr) { if (isa_check && !isa_check(state)) { return; } const size_t num_elements = state.range(0); std::random_device random_device; auto rng = std::mt19937(random_device()); auto i8rng = std::bind( std::uniform_int_distribution<int32_t>(std::numeric_limits<int8_t>::min(), std::numeric_limits<int8_t>::max()), std::ref(rng)); std::vector<int8_t, AlignedAllocator<int8_t, 64>> a(num_elements); std::vector<int8_t, AlignedAllocator<int8_t, 64>> b(num_elements); std::vector<int8_t, AlignedAllocator<int8_t, 64>> product(num_elements); std::generate(a.begin(), a.end(), std::ref(i8rng)); std::generate(b.begin(), b.end(), std::ref(i8rng)); union xnn_qs8_mul_minmax_params params; init_params(&params, 1 /* a zero point */, 1 /* b zero point */, 1 /* output zero point */, 0.75f /* product-output scale */, std::numeric_limits<int8_t>::min() + 1, std::numeric_limits<int8_t>::max() - 1); for (auto _ : state) { vmul(num_elements * sizeof(int8_t), a.data(), b.data(), product.data(), &params); } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } const size_t num_elements_per_iteration = num_elements; state.counters["num_elements"] = benchmark::Counter(uint64_t(state.iterations()) * num_elements_per_iteration, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 3 * num_elements * sizeof(int8_t); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } #if XNN_ARCH_ARM || XNN_ARCH_ARM64 BENCHMARK_CAPTURE(qs8_vmul, neonv8_ld64_x8, xnn_qs8_vmul_minmax_fp32_ukernel__neonv8_ld64_x8, xnn_init_qs8_mul_minmax_fp32_neonv8_params, benchmark::utils::CheckNEONV8) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, neonv8_ld64_x16, xnn_qs8_vmul_minmax_fp32_ukernel__neonv8_ld64_x16, xnn_init_qs8_mul_minmax_fp32_neonv8_params, benchmark::utils::CheckNEONV8) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, neonv8_ld128_x16, xnn_qs8_vmul_minmax_fp32_ukernel__neonv8_ld128_x16, xnn_init_qs8_mul_minmax_fp32_neonv8_params, benchmark::utils::CheckNEONV8) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, neon_ld64_x8, xnn_qs8_vmul_minmax_fp32_ukernel__neon_ld64_x8, xnn_init_qs8_mul_minmax_fp32_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, neon_ld64_x16, xnn_qs8_vmul_minmax_fp32_ukernel__neon_ld64_x16, xnn_init_qs8_mul_minmax_fp32_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, neon_ld128_x16, xnn_qs8_vmul_minmax_fp32_ukernel__neon_ld128_x16, xnn_init_qs8_mul_minmax_fp32_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 BENCHMARK_CAPTURE(qs8_vmul, avx_mul16_ld64_x8, xnn_qs8_vmul_minmax_fp32_ukernel__avx_mul16_ld64_x8, xnn_init_qs8_mul_minmax_fp32_sse4_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, avx_mul16_ld64_x16, xnn_qs8_vmul_minmax_fp32_ukernel__avx_mul16_ld64_x16, xnn_init_qs8_mul_minmax_fp32_sse4_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, sse41_mul16_ld64_x8, xnn_qs8_vmul_minmax_fp32_ukernel__sse41_mul16_ld64_x8, xnn_init_qs8_mul_minmax_fp32_sse4_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, sse41_mul16_ld64_x16, xnn_qs8_vmul_minmax_fp32_ukernel__sse41_mul16_ld64_x16, xnn_init_qs8_mul_minmax_fp32_sse4_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, sse2_mul16_ld64_x8, xnn_qs8_vmul_minmax_fp32_ukernel__sse2_mul16_ld64_x8, xnn_init_qs8_mul_minmax_fp32_sse2_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, sse2_mul16_ld64_x16, xnn_qs8_vmul_minmax_fp32_ukernel__sse2_mul16_ld64_x16, xnn_init_qs8_mul_minmax_fp32_sse2_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD BENCHMARK_CAPTURE(qs8_vmul, wasmsimd_mul32_ld64_x8, xnn_qs8_vmul_minmax_fp32_ukernel__wasmsimd_mul32_ld64_x8, xnn_init_qs8_mul_minmax_fp32_wasmsimd_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, wasmsimd_mul32_ld64_x16, xnn_qs8_vmul_minmax_fp32_ukernel__wasmsimd_mul32_ld64_x16, xnn_init_qs8_mul_minmax_fp32_wasmsimd_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); #endif // XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD BENCHMARK_CAPTURE(qs8_vmul, scalar_x1, xnn_qs8_vmul_minmax_fp32_ukernel__scalar_x1, xnn_init_qs8_mul_minmax_fp32_scalar_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, scalar_x2, xnn_qs8_vmul_minmax_fp32_ukernel__scalar_x2, xnn_init_qs8_mul_minmax_fp32_scalar_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qs8_vmul, scalar_x4, xnn_qs8_vmul_minmax_fp32_ukernel__scalar_x4, xnn_init_qs8_mul_minmax_fp32_scalar_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<int8_t, int8_t>) ->UseRealTime(); #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
43.027473
115
0.708849
[ "vector" ]
f38dff6d732c55eee5856b0a45676095373724a9
18,890
cpp
C++
source/msynth/MainFrame.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
1
2022-01-30T07:40:31.000Z
2022-01-30T07:40:31.000Z
source/msynth/MainFrame.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
source/msynth/MainFrame.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
/*----------------------------------------------------------------------------- MSynth (C)2000-2003 MRoc hifiShock required libs: dsound.lib winmm.lib xerces-c_2D.lib dxguid.lib dmoguids.lib amstrmid.lib msdmo.lib comctl32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib shlwapi.lib dxerr8.lib HISTORY v. 0.8 - Saveable Samplebanks v. 0.8a - Editable SampleNames v. 0.8b - Saveing machinestate with pattern v. 0.8c - Synth with Portamento v. 0.81 - bugfixes(samplePlayer), optimized, working v. 0.81a - bugfix v. 0.81b - bugfix maxAmp, title with fileNames v. 0.82 beta - StreamingAudio BufferCaps fixed, MSynth.ini for DxDevice, - MExceptions in WaveFileHandling(30%) v. 0.83 beta - Dialog for StreamingMode (Render current/whole pattern, - record live-session), - Sequencer with renderFunction, - MExceptionBugFix in MWavePlayer v. 0.83 - Performance-Tune in MControlButton, added more Accelerators - (return -> play/stop) v. 0.84 - Synth engine rewritten -> more OOP, vtable, - SynthControl, - WavePlayerControl - CenterDialogs, - bugfix slide in triangleOscilator - MEGA-Performancetune in MWavePlayer (interpolation) - SettingsDialog with choosable BufferLength & StickyFocus - (saved in msynth.ini) - Bitmap-Controls do not need CRect anymore, only x, y v. 0.85 - FX-dialog-try v. 0.86 - XML-FileFormat v. 0.87 - dynamical GUI v. 0.88 beta - Eventdriven DrumBox, Memoryleaks removes first betas out... v. 0.89 - Synthcount v. 0.9 beta - working v. 0.9a - some fixes, introducing SequencerControl v. 0.9b - new MAudioEngine v. 0.91 - MBeatBox in a own Frame v. 0.92 - MTransformatorCollection for MBeatBox (MasterFX for drums) v. 0.92 b - MPollingStreamingAudio and MAudioEngine v. 0.92 c - Link in MAboutDialog, working link to Help v. 0.92 d - help-link allways works(with error message), - transformer collection editor better userinterface - (add/remove automatic selection) v. 0.92 d2 - some codecleanings(SAFE_DELETE, ...) - removed some unused files from project - opened fx-editor when exiting app -> crash fixed v. 0.93 beta - opening pattern loads samplebank, - new Oscillator, MOscString, - new MDescriptedViewFactory, - MNoteSetp reacting on tab and cursor, - mutebutton(drumboxChannel) triggers note-off - void reset() in all transformers - frames are brought to front v. 0.94 beta - introducing Mixer Frame v. 0.95 beta - REWRITTEN -> now bufferBased, - stereo-out - many performance-tunes, better than ever before v. 0.96 alphaDV - introducting aplha state of MArrangeView and MSong, - MNoteFrame, MNoteGrid, MNoteControl, IAbstractNote, - IAbstractNoteList, MArrangeBar... - doublebuffered sliders, - removed memoryleak when exited over menu(file->exit), - new Oscilator MSineOsc v. 0.98 alpha - Removed everything from MainFrame -> MSong becomes the - most important component. v. 0.98 - introduces MTimeController, MArrangeView & Mixer most - important components. v. 1.0 beta1-3 - removes selectObject GDC bug, - added new splash - fixed bug in mbar serialisation (max startsAt was 16) - introducing MClipBoard - faster GUI work, FillRect -> FillSolidRect, (less brushes) v. 1.0 beta4 - MColorMap, MMultiOsc, MIIR (IIR), popup slider v. 1.0 beta5 - bugs in grids and windows removed, send fx v. 1.0 beta6 - much more bugfixes v. 1.0 beta7 - MGuiUtils, M3D***Buttons v. 1.0 beta8 - MProperties, MObject, MDefaultFactory... v. 1.0.0 - First demo release v. 1.0.1 - MSI Installer v. 1.0.2 - Interfaces -> I... , BpmControl,... v. 1.1.0 betadmo - DirectMediaObject Audiofilter support, - IControl, IControlCollection... v. 1.1.0 beta - Better controls with OnHover/RoolOver, - StringTable, english resources, - MUpdateThread v. 1.1.0.2 - ControlRegistry, AutomationTracker... v. 1.2.0.0 - better automation, buttons changed, bugs... v. 1.2.2.0 - removed fatal delete bug in arrange grid, bundled with docu v. 1.2.3.0 - Offscreen windows, interactive components, own scrollbars, own spinButtons, own combox v. 1.2.4.0 - introducing the sequencercontrol, removed MUpdateThread's own position calculation v. 1.3.0.0 - replaced all combos ->new bugs fixed - saves the editors' positions - many bugfixes: crashs when two bars with open editor are glown mem leaks when open bar editor and recording events loading synth when playing resulted in critical section deadlock waves from the windows audiorecorder can be loaded now envelope forgotten in moogfilter, but not working worth rescaling beatbox notes was possible by increasing resolution of bbbar from 16 up to 32 - controlguis only rerendering is necessary - fx rack frame hided behind mainframe - mscrollwnd replaced updatewindow -> redrawwindow (failed in release version) v. 1.4.0.0 - audiochannels as new instrument - many memory leaks removed - xerces xml compiled with same runtime version??? - complete restructuring code into packages - introduced Streams - rewrote MWave and introduced MWaveFileHeader - removed CWndListenerList from models, introduced normal interface observer - introduced MTreeDocument, completely new serialisation - introduced new tree document converter (MXmlConverter with matchings and converter) - waves saved in song file base64 encoded - MControlGui inheritanced from MyInteractiveWnd, interactiveWnd now handles right mouse (MMouseEvent) - small changes in grid classes - fixes in all sine oscis (oscis&lfo), more stable recursive algo found - rewrote MNoise based on a linear kongruence algo - more and more objects become a MObject - new MTransformer- and MSourceRegistry, transformer and oscs created by MObjectFactory - maximal loudness 2x because of silly fuck bug - introduced MCriticalSection & MSynchronisation - introduced MThread and IRunnable for work posted in gui thread, less wnd msgs - introduced IGraphics... - introduced MWndContainer... - introduced MLayout - MAudioEngine got MAudioThread - EQs bases on MBiquad - Sequencer rewritten, stream oriented... - Mixer rewritten # v. 1.5.0 - resource manager, string resource v. 1.5.1 - dynamics, patterns - rewrote GUI MFC->win32 -----------------------------------------------------------------------------*/ #include "MainFrame.h" #include <gui/MApp.h> #include <gui/dialog/MFileDialog.h> #define SEQUENCER_CONTROL_ID 1000 #define ARRANGE_ID 2000 #define MIXER_ID 3000 #define FXRACK_ID 4000 #define DEF_WIDTH 640 #define DEF_HEIGHT 480 MainFrame::MainFrame( String fileName ) : ivPtSequencerControlWnd(0), ivPtMixerControl(0), ivPtArrangeFrame(0), ivPtFxRackFrame(0), ivFileName(""), ivFullFileName(""), ivPtSequencerControl( 0 ) { setActionOnClose( MTopWnd::ActionOnClose::QUIT ); } MainFrame::~MainFrame() { MApp::getInstance()->setMainWnd( 0 ); MLogger::logMessage( "<mainframe::~mainframe/>\n" ); if( ivPtSequencerControl && ivPtSequencerControl->getPlayState() == IPlayState::PLAYING || ivPtSequencerControl && ivPtSequencerControl->getPlayState() == IPlayState::SESSION_PLAYING || ivPtSequencerControl && ivPtSequencerControl->getPlayState() == IPlayState::SESSION_NOT_PLAYING ) { ivPtSequencerControl->stop(); } if( ivPtArrangeFrame ) { removeChild( ivPtArrangeFrame ); delete ivPtArrangeFrame; ivPtArrangeFrame = 0; } if( ivPtSequencerControlWnd ) { removeChild( ivPtSequencerControlWnd ); delete ivPtSequencerControlWnd; ivPtSequencerControlWnd = 0; } if( ivPtSequencerControl ) { delete ivPtSequencerControl; ivPtSequencerControl = 0; } MTimeController::release(); } bool MainFrame::create( MRect rect, MTopWnd* pWnd ) { int x = (GetSystemMetrics( SM_CXSCREEN )-DEF_WIDTH) / 2; int y = (GetSystemMetrics( SM_CYSCREEN )-DEF_HEIGHT) / 2; bool back = MFrameWnd::create( MRect( x, y, DEF_WIDTH, DEF_HEIGHT ), pWnd ); if( back == false ) MLogger::logError( "MainFrame::MainFrame: create failed" ); else { MMenu* pMenu = new MMenu(); pMenu->load( IDR_MENU1 ); setMenu( pMenu ); setIcon( new MIcon( IDI_ICON1 ) ); // init models... init(); // init controls... ivPtSequencerControlWnd = new MSequencerControlWnd(); ivPtSequencerControlWnd->SetSequencerControl( ivPtSequencerControl ); ivPtSequencerControlWnd->setRect( MRect( 0, 0, 630, 55 ) ); addChild( ivPtSequencerControlWnd ); ivPtSequencerControlWnd->updateFromModel(); ivPtArrangeFrame = new MArrangeFrame( ARRANGE_ID, ivPtSequencerControl->getSong(), ivPtSequencerControl->getTimeControl(), ivPtSequencerControl->getUpdateThread(), ivPtSequencerControl->getSequencer() ); ivPtArrangeFrame->setTimeController( ivPtSequencerControl->getTimeControl() ); addChild( ivPtArrangeFrame ); ivPtArrangeFrame->updateFromModel(); ivPtArrangeFrame->updateFromPartSize(); ivPtArrangeFrame->setVisible( true ); updateWindowText(); doLayout(); /*if( ! fileName.IsEmpty() ) { open( fileName ); ivPtSequencerControlWnd->updateFromModel(); ivPtSequencerControl->start(); }*/ } return back; } void MainFrame::onClose() { #ifndef _DEBUG if( MMessageBox::showQuestion( "QUIT" ) == IDYES ) #endif { if( ivPtArrangeFrame ) ivPtArrangeFrame->closeChildFrames(); SAFE_DELETE( ivPtFxRackFrame ); SAFE_DELETE( ivPtMixerControl ); MFrameWnd::onClose(); } MApp::getInstance()->setQuit(); } void MainFrame::init() { MLogger::logMessage( "<mainframe::init/>\n" ); // song... Sequencer* ptSequencer = new Sequencer(); MSong* ptSong = new MSong( ptSequencer ); ptSong->newSong(); // sequencer... ptSequencer->setSong( ptSong ); ptSequencer->setTimeController( MTimeController::getInstance() ); // update thread... MUpdateThread* ptUpdateThread = new MUpdateThread( MTimeController::getInstance(), ptSequencer ); ivPtSequencerControl = new MSequencerControl(); ivPtSequencerControl->setSequencer( ptSequencer ); ivPtSequencerControl->setUpdateThread( ptUpdateThread ); ivPtSequencerControl->setSong( ptSong ); ivPtSequencerControl->setTimeControl( MTimeController::getInstance() ); initStreamingEngine(); } void MainFrame::initStreamingEngine() { MLogger::logMessage( "<mainframe::initstreamingengine/>\n" ); if( ivPtSequencerControl && ivPtSequencerControl->getPlayState() == IPlayState::PLAYING || ivPtSequencerControl && ivPtSequencerControl->getPlayState() == IPlayState::SESSION_PLAYING || ivPtSequencerControl && ivPtSequencerControl->getPlayState() == IPlayState::SESSION_NOT_PLAYING ) { ivPtSequencerControl->stop(); } try { ivPtSequencerControl->getAudioEngine()->create( ivPtSequencerControl->getSequencer() ); } catch( MException ae ) { MMessageBox::showError( ae.getExceptionDescripton() ); exit( -1 ); } } void MainFrame::updateWindowText() { String title = MApp::getInstance()->getAppName(); if( ivFileName != "" ) title += " [" + ivFileName + "]"; setText(title); } void MainFrame::doLayout() { MSize size = getClientSize(); if( ivPtSequencerControlWnd ) ivPtSequencerControlWnd->setRect( MRect( 0, 0, size.getWidth(), 55 ) ); if( ivPtArrangeFrame ) ivPtArrangeFrame->setRect( MRect( 0, 55, size.getWidth()-1, size.getHeight() - 55 ) ); } void MainFrame::onNew() { MLogger::logMessage( "<mainframe::onnew/>\n" ); if( ivPtArrangeFrame ) ivPtArrangeFrame->closeChildFrames(); ivPtSequencerControl->getSong()->newSong(); ivPtSequencerControl->getSequencer()->newSong(); ivFileName = ""; ivFullFileName = ""; updateWindowText(); } void MainFrame::onOpen() { MLogger::logMessage( "<mainframe::open/>\n" ); MFileDialog dlg; if( dlg.showOpenDialog( this, "Open song", "MSynth Song\0*.MXL\0All files\0*.*\0\0" ) ) { open( dlg.getSelectedFile() ); ivFileName = dlg.getSelectedFile(); ivFullFileName = dlg.getSelectedFile().Left( dlg.getSelectedFile().ReverseFind( '\\' ) ); if( ivPtSequencerControlWnd ) ivPtSequencerControlWnd->updateFromModel(); updateWindowText(); } } void MainFrame::onSave() { MLogger::logMessage( "<mainframe::onsave/>\n" ); if( ivFullFileName != "" ) { ivPtArrangeFrame->storeChildPositions(); MTreeNode* ptNode = ivPtSequencerControl->getSequencer()->save(); MFileHandling::getInstance()->saveMXLFile( ivFullFileName, ptNode ); delete ptNode; } else onSaveAs(); } void MainFrame::onSaveAs() { MLogger::logMessage( "<mainframe::onsaveas/>\n" ); MFileDialog dlg; if( dlg.showSaveDialog( this, "Save song", "MSynth Song\0*.MXL\0All files\0*.*\0\0" ) ) { ivFileName = dlg.getSelectedFile(); ivFullFileName = dlg.getSelectedFile().Left( dlg.getSelectedFile().ReverseFind( '\\' ) ); /*CFileFind finder; if( finder.FindFile( ivFullFileName ) ) if( MMessageBox::showQuestion( "OVERWRITE", ivFullFileName ) != IDYES ) return;*/ this->ivPtArrangeFrame->storeChildPositions(); String songName = ivFileName.Left( ivFileName.ReverseFind( '.' ) ); String dir = ivFullFileName.Left( ivFullFileName.ReverseFind( '\\' ) ); MTreeNode* ptNode = ivPtSequencerControl->getSequencer()->save(); MFileHandling::getInstance()->saveMXLFile( dlg.getSelectedFile(), ptNode ); delete ptNode; updateWindowText(); } } void MainFrame::onExportAsWave() { if( ivPtSequencerControlWnd ) ivPtSequencerControlWnd->Export(); } void MainFrame::onCopy() { IClipBoardContext* pContext = MClipBoard::getInstance()->getContext(); if( pContext ) pContext->onCopy(); else MMessageBox::showError( "NO_WINDOW_SUPPORTING_COPY" ); } void MainFrame::onCut() { IClipBoardContext* pContext = MClipBoard::getInstance()->getContext(); if( pContext ) pContext->onCut(); else MMessageBox::showError( "NO_WINDOW_SUPPORTING_CUT" ); } void MainFrame::onPaste() { IClipBoardContext* pContext = MClipBoard::getInstance()->getContext(); if( pContext ) pContext->onPaste(); else MMessageBox::showError( "NO_WINDOW_SUPPORTING_PASTE" ); } void MainFrame::onDelete() { IClipBoardContext* pContext = MClipBoard::getInstance()->getContext(); if( pContext ) pContext->onDelete(); else MMessageBox::showError( "NO_WINDOW_SUPPORTING_DELETE" ); } void MainFrame::showMixer() { if(! ivPtMixerControl) { ivPtMixerControl = new MMixerFrame(); ivPtMixerControl->create( MRect( 0, 0, 100, 100 ), this ); ivPtMixerControl->setMixer( ivPtSequencerControl->getSequencer()->getMixer() ); ivPtMixerControl->updateGui(); } ivPtMixerControl->updateFromModel(); ivPtMixerControl->setVisible( true ); } void MainFrame::showFxRack() { if( ! ivPtFxRackFrame ) { ivPtFxRackFrame = new MFxRackFrame(); ivPtFxRackFrame->setFxRack( ivPtSequencerControl->getSequencer()->getMixer()->getFxRack() ); ivPtFxRackFrame->create( MRect( 0, 0, 100, 100 ), this ); ivPtFxRackFrame->setIcon( new MIcon( *getIcon() ) ); } ivPtFxRackFrame->setVisible( true ); } void MainFrame::onCreateSynth() { ivPtSequencerControl->getSong()->createDefaultSynth(); } void MainFrame::onCreateBeatBox() { ivPtSequencerControl->getSong()->createDefaultBeatBox(); } void MainFrame::onCreateAudiochannel() { ivPtSequencerControl->getSong()->createDefaultAudioChannel(); } void MainFrame::onReset() { ivPtSequencerControl->getSong()->resetAllInstruments(); } void MainFrame::onSettingsDialog() { ASSERT( ivPtSequencerControl && ivPtSequencerControl->getAudioEngine() ); Settings settingsDialog; settingsDialog.create( MRect( 0, 0, 400, 600 ), (MTopWnd*)getTopParent() ); if( settingsDialog.doModal() == MDialog::OK ) { if( ivPtArrangeFrame ) ivPtArrangeFrame->closeChildFrames(); initStreamingEngine(); } } void MainFrame::onAbout() { MAboutDialog dialog; dialog.setCopyright( MAppData::COPYRIGHT ); dialog.setVersion( MAppData::VERSION ); dialog.doModal(); } void MainFrame::onHelp() { if( ((LPARAM)ShellExecute( 0, "open", MAppData::APPDIR + "doc\\index.html", 0, 0, SW_SHOWNORMAL )) <= 32 ) MMessageBox::showError( "ERROR_STARTING_HELP" ); } void MainFrame::onPlay() { ivPtSequencerControlWnd->Play(); } void MainFrame::onActivate( bool active ) { if( active ) MClipBoard::getInstance()->setContext( ivPtArrangeFrame ); } void MainFrame::open( String fileName ) { MLogger::logMessage( "<mainframe::open filename=\"%s\"/>\n", fileName.getData() ); if( ivPtSequencerControl && (ivPtSequencerControl->getPlayState() == IPlayState::PLAYING || ivPtSequencerControl->getPlayState() == IPlayState::SESSION_PLAYING || ivPtSequencerControl->getPlayState() == IPlayState::SESSION_NOT_PLAYING ) ) { ivPtSequencerControl->stop(); } try { if( ivPtArrangeFrame ) ivPtArrangeFrame->closeChildFrames(); if( ! MFileHandling::getInstance()->openFile( fileName, ivPtSequencerControl->getSequencer() ) ) { MMessageBox::showError( "ERROR_LOADING_SONG", fileName ); } } catch(MException anException) { MMessageBox::showError( "ERROR_LOADING_SONG", fileName + "(" + anException.getExceptionDescripton() + ")" ); } } void MainFrame::onCommand( unsigned int id ) { switch( id ) { case ID_NEW_SONG: onNew(); break; case ID_OPEN_SONG: onOpen(); break; case ID_SAVE_SONG: onSave(); break; case ID_SAVE_SONG_AS: onSaveAs(); break; case ID_EXPORT_SONG: onExportAsWave(); break; case ID_EXIT: onClose(); break; case ID_COPY: onCopy(); break; case ID_PASTE: onPaste(); break; case ID_CUT: onCut(); break; case ID_DELETE: onDelete(); break; case ID_SHOW_MIXER: showMixer(); break; case ID_SHOW_FXRACK: showFxRack(); break; case ID_SETTINGS_SETTINGS: onSettingsDialog(); break; case ID_ABOUT_ABOUT: onAbout(); break; case ID_SHOW_HELP: onHelp(); break; case ID_CREATESYNTH: onCreateSynth(); break; case ID_CREATEBEATBOX: onCreateBeatBox(); break; case ID_INSTRUMENT_CREATEAUDIOCHANNEL: onCreateAudiochannel(); break; case ID_RESET: onReset(); break; case ID_QUIT: onClose(); break; default: MFrameWnd::onCommand( id ); break; } }
30.079618
111
0.686077
[ "render" ]
f38ead2f85d27cc1ad0ffa9bee61156fe8f3ff9a
1,675
cpp
C++
src/problems/vrptw/operators/intra_two_opt.cpp
gauravagrwal/vroom
c238bf6d0590ea384bcc9a3aa84ca9f4fdde1099
[ "BSD-2-Clause" ]
null
null
null
src/problems/vrptw/operators/intra_two_opt.cpp
gauravagrwal/vroom
c238bf6d0590ea384bcc9a3aa84ca9f4fdde1099
[ "BSD-2-Clause" ]
null
null
null
src/problems/vrptw/operators/intra_two_opt.cpp
gauravagrwal/vroom
c238bf6d0590ea384bcc9a3aa84ca9f4fdde1099
[ "BSD-2-Clause" ]
null
null
null
/* This file is part of VROOM. Copyright (c) 2015-2022, Julien Coupey. All rights reserved (see LICENSE). */ #include "problems/vrptw/operators/intra_two_opt.h" namespace vroom { namespace vrptw { IntraTwoOpt::IntraTwoOpt(const Input& input, const utils::SolutionState& sol_state, TWRoute& tw_s_route, Index s_vehicle, Index s_rank, Index t_rank) : cvrp::IntraTwoOpt(input, sol_state, static_cast<RawRoute&>(tw_s_route), s_vehicle, s_rank, t_rank), _tw_s_route(tw_s_route) { } bool IntraTwoOpt::is_valid() { bool valid = cvrp::IntraTwoOpt::is_valid(); if (valid) { auto rev_t = s_route.rbegin() + (s_route.size() - t_rank - 1); auto rev_s_next = s_route.rbegin() + (s_route.size() - s_rank); valid = _tw_s_route.is_valid_addition_for_tw(_input, rev_t, rev_s_next, s_rank, t_rank + 1); } return valid; } void IntraTwoOpt::apply() { std::vector<Index> reversed(s_route.rbegin() + (s_route.size() - t_rank - 1), s_route.rbegin() + (s_route.size() - s_rank)); _tw_s_route.replace(_input, reversed.begin(), reversed.end(), s_rank, t_rank + 1); } } // namespace vrptw } // namespace vroom
27.916667
79
0.47403
[ "vector" ]
f392f0d846a042672613dc610b70035f1c8b6e8f
2,170
cpp
C++
CesiumGeometry/test/TestBoundingSphere.cpp
JiangMuWen/cesium-native
1d9912307336c833b74b7e9b7bc715d0a4e6c7ec
[ "Apache-2.0" ]
154
2021-03-30T14:08:39.000Z
2022-03-30T00:01:43.000Z
CesiumGeometry/test/TestBoundingSphere.cpp
JiangMuWen/cesium-native
1d9912307336c833b74b7e9b7bc715d0a4e6c7ec
[ "Apache-2.0" ]
256
2021-03-30T18:12:28.000Z
2022-03-31T23:44:21.000Z
CesiumGeometry/test/TestBoundingSphere.cpp
JiangMuWen/cesium-native
1d9912307336c833b74b7e9b7bc715d0a4e6c7ec
[ "Apache-2.0" ]
66
2021-03-30T15:14:32.000Z
2022-03-31T13:38:41.000Z
#include "CesiumGeometry/BoundingSphere.h" #include "CesiumGeometry/Plane.h" #include <catch2/catch.hpp> #include <glm/mat3x3.hpp> using namespace CesiumGeometry; TEST_CASE("BoundingSphere::intersectPlane") { struct TestCase { BoundingSphere sphere; Plane plane; CullingResult expectedResult; }; auto testCase = GENERATE( // sphere on the positive side of a plane TestCase{ BoundingSphere(glm::dvec3(0.0), 0.5), Plane(glm::dvec3(-1.0, 0.0, 0.0), 1.0), CullingResult::Inside}, // sphere on the negative side of a plane TestCase{ BoundingSphere(glm::dvec3(0.0), 0.5), Plane(glm::dvec3(1.0, 0.0, 0.0), -1.0), CullingResult::Outside}, // sphere intersection a plane TestCase{ BoundingSphere(glm::dvec3(1.0, 0.0, 0.0), 0.5), Plane(glm::dvec3(1.0, 0.0, 0.0), -1.0), CullingResult::Intersecting}); CHECK( testCase.sphere.intersectPlane(testCase.plane) == testCase.expectedResult); } TEST_CASE("BoundingSphere::computeDistanceSquaredToPosition") { BoundingSphere bs(glm::dvec3(0.0), 1.0); glm::dvec3 position(-2.0, 1.0, 0.0); double expected = glm::dot(position, position) - 1.0; CHECK(bs.computeDistanceSquaredToPosition(position) == expected); } TEST_CASE("BoundingSphere::computeDistanceSquaredToPosition example") { auto anyOldSphereArray = []() { return std::vector<BoundingSphere>{ {glm::dvec3(1.0, 0.0, 0.0), 1.0}, {glm::dvec3(2.0, 0.0, 0.0), 1.0}}; }; auto anyOldCameraPosition = []() { return glm::dvec3(0.0, 0.0, 0.0); }; //! [distanceSquaredTo] // Sort bounding spheres from back to front glm::dvec3 cameraPosition = anyOldCameraPosition(); std::vector<BoundingSphere> spheres = anyOldSphereArray(); std::sort( spheres.begin(), spheres.end(), [&cameraPosition](auto& a, auto& b) { return a.computeDistanceSquaredToPosition(cameraPosition) > b.computeDistanceSquaredToPosition(cameraPosition); }); //! [distanceSquaredTo] CHECK(spheres[0].getCenter().x == 2.0); CHECK(spheres[1].getCenter().x == 1.0); }
31.449275
73
0.641475
[ "vector" ]
f398bdcdf7b22121aafc359575d9615018322ddd
45,498
cc
C++
CyraResLevel.cc
nmoehrle/scanalyze
f9c0f08c89586715df62f98d5997a79a5b527428
[ "TCL" ]
1
2018-11-29T12:46:18.000Z
2018-11-29T12:46:18.000Z
CyraResLevel.cc
dthul/scanalyze
f9c0f08c89586715df62f98d5997a79a5b527428
[ "TCL" ]
null
null
null
CyraResLevel.cc
dthul/scanalyze
f9c0f08c89586715df62f98d5997a79a5b527428
[ "TCL" ]
2
2020-10-18T06:00:03.000Z
2022-01-04T20:13:03.000Z
//############################################################ // // CyraResLevel.cc // // Lucas Pereira // Thu Jul 16 15:20:47 1998 // // Part of CyraScan.cc, // Store range scan information from a Cyra Cyrax Beta // time-of-flight laser range scanner. // //############################################################ #include "CyraResLevel.h" #include <tcl.h> #include <stdio.h> #include <iostream> #include <fstream> #include <stack> #include <stdlib.h> #include "defines.h" #include "TriMeshUtils.h" #include "KDindtree.h" #include "ColorUtils.h" #include "plvScene.h" #include "MeshTransport.h" #include "VertexFilter.h" #ifdef WIN32 #define random rand #endif // The maximum depth distance across which it will tesselate. // (Bigger than this, it assumes a noncontinuous surface) #define DEFAULT_CYRA_TESS_DEPTH 80; float CyraTessDepth = DEFAULT_CYRA_TESS_DEPTH; // Default to filtering on... #define DEFAULT_CYRA_FILTER_SPIKES TRUE; bool CyraFilterSpikes = DEFAULT_CYRA_FILTER_SPIKES; // Default to fill holes on... #define DEFAULT_CYRA_FILL_HOLES TRUE; bool CyraFillHoles = DEFAULT_CYRA_FILL_HOLES; ////////////////////////////////////////////////////////////////////// // CyraSample (One single data point) // Helper functions... ////////////////////////////////////////////////////////////////////// void CyraSample::zero(void) { vtx[0] = vtx[1] = vtx[2] = 0; nrm[0] = nrm[1] = nrm[2] = 0; intensity = 0; confidence = 0; } // interp 2 samples void CyraSample::interp(CyraSample &a, CyraSample &b) { for (int i = 0; i < 3; i++) { vtx[i] = 0.5 * (a.vtx[i] + b.vtx[i]); nrm[i] = 0.5 * (a.nrm[i] + b.nrm[i]); } intensity = 0.5 * (a.intensity + b.intensity); confidence = 0.5 * (a.confidence + b.confidence); } // interp 3 samples, weighted 1/4, 1/2, 1/4 void CyraSample::interp(CyraSample &a, CyraSample &b, CyraSample &c) { for (int i = 0; i < 3; i++) { vtx[i] = 0.25 * (a.vtx[i] + b.vtx[i] + b.vtx[i] + c.vtx[i]); nrm[i] = 0.25 * (a.nrm[i] + b.nrm[i] + b.nrm[i] + c.nrm[i]); } intensity = 0.25 * (a.intensity + b.intensity + b.intensity + c.intensity); confidence = 0.25 * (a.confidence + b.confidence + b.confidence + c.confidence); } // Interpolate arbitrary number of samples, weighted evenly... void CyraSample::interp(int nsamps, CyraSample *samps[]) { assert(nsamps > 0); this->zero(); float wt = 1.0 / nsamps; // add up the values of every sample... for (int samnum = 0; samnum < nsamps; samnum++) { for (int i = 0; i < 3; i++) { vtx[i] += samps[samnum]->vtx[i]; nrm[i] += samps[samnum]->nrm[i]; } intensity += samps[samnum]->intensity; confidence += samps[samnum]->confidence; } // divide by the appropriate weight... for (int i = 0; i < 3; i++) { vtx[i] /= wt; nrm[i] /= wt; } intensity /= wt; confidence /= wt; } bool CyraSample::isValid(void) { return ((vtx[2] > 0) ? TRUE : FALSE); } ////////////////////////////////////////////////////////////////////// // CyraResLevel (one resolution level for a cyra scan) ////////////////////////////////////////////////////////////////////// CyraResLevel::CyraResLevel(void) { // Clear arrays width = 0; height = 0; numpoints = 0; numtris = 0; points.clear(); tris.clear(); origin.set(0, 0, 0); isDirty_cache = true; cachedPoints.clear(); cachedNorms.clear(); cachedBoundary.clear(); kdtree = NULL; } CyraResLevel::~CyraResLevel(void) { // do nothing yet if (kdtree) delete kdtree; } // PUSH_TRI -- basically a macro used by the mesh-generation function // to look up the 3 vertices in vert_inds, and do tstrips if necessary inline void PUSH_TRI(int &ov2, int &ov3, vector<int> &tri_inds, const bool stripped, const vector<int> &vert_inds, const int v1, const int v2, const int v3) { // will next tri be odd or even? (even tris get flipped) static bool oddtri = true; if (stripped) { if (oddtri && (ov2 == v2 && ov3 == v1)) { // odd-numbered triangle tri_inds.push_back(vert_inds[v3]); oddtri = false; } else if (!oddtri && (ov2 == v1 && ov3 == v3)) { // even-numbered triangle -- listed backwards tri_inds.push_back(vert_inds[v2]); oddtri = true; } else { tri_inds.push_back(-1); tri_inds.push_back(vert_inds[v1]); tri_inds.push_back(vert_inds[v2]); tri_inds.push_back(vert_inds[v3]); oddtri = false; } ov2 = v2; ov3 = v3; } else { tri_inds.push_back(vert_inds[v1]); tri_inds.push_back(vert_inds[v2]); tri_inds.push_back(vert_inds[v3]); } } // Add the geometry for this reslevel to the list MeshTransport *CyraResLevel::mesh(bool perVertex, bool stripped, ColorSource color, int colorSize) { // Offset (index) for the next vertex; int vertoffset = 0; ////// Vertices ///// // The valid vertices need contiguous index numbers. So fill an // array vert_inds -- index numbers with a 1-1 correspondence // to the array of vertices. vector<int> vert_inds; vert_inds.reserve(points.size()); // Set the vert_inds array for (int i = 0; i < points.size(); i++) { vert_inds.push_back((points[i].confidence > 0) ? vertoffset++ : -1); } vector<Pnt3> *vtx = new vector<Pnt3>; vector<short> *nrm = new vector<short>; vector<int> *tri_inds = new vector<int>; // Add each valid vertex to vtx, nrm(?) FOR_EACH_VERT(vtx->push_back(v->vtx)); if (perVertex) { FOR_EACH_VERT(nrm->insert(nrm->end(), v->nrm, v->nrm + 3)); } else { FOR_EACH_TRI(pushNormalAsShorts( *nrm, ((Pnt3)cross(points[tv3].vtx - points[tv2].vtx, points[tv1].vtx - points[tv2].vtx)).normalize())); } ////// Triangles ///// // Now fill in the triangle array // Initialize the "old v2, v3" values used in tstripping int ov2 = -1; int ov3 = -1; // call the FOR_EACH_TRI macro, which defines tv1, tv2, tv3. FOR_EACH_TRI( PUSH_TRI(ov2, ov3, *tri_inds, stripped, vert_inds, tv1, tv2, tv3)); // Terminate the last tstrip if (stripped) { tri_inds->push_back(-1); } MeshTransport *mt = new MeshTransport; mt->setVtx(vtx, MeshTransport::steal); mt->setNrm(nrm, MeshTransport::steal); mt->setTris(tri_inds, MeshTransport::steal); if (color != RigidScan::colorNone) { vector<uchar> *colors = new vector<uchar>; int nColors = perVertex ? vtx->size() : num_tris(); colors->reserve(colorSize * nColors); if (colorMesh(*colors, perVertex, color, colorSize)) mt->setColor(colors, MeshTransport::steal); else delete colors; } return mt; } // Fill in the colors array. bool CyraResLevel::colorMesh(vector<uchar> &colors, bool perVertex, ColorSource source, int colorsize) { switch (source) { case RigidScan::colorConf: // ========= Color by Confidence ========= if (perVertex) { cerr << "adding per-vertex conf color..." << endl; // per-vertex confidence FOR_EACH_VERT( pushColor(colors, colorsize, (float)(v->confidence / CYRA_DEFAULT_CONFIDENCE))); } else { cerr << "adding per-face conf color..." << endl; // per-face confidence (take min of 3 confidences) FOR_EACH_TRI(pushColor(colors, colorsize, (float)(MIN(points[tv1].confidence, MIN(points[tv2].confidence, points[tv3].confidence)) / CYRA_DEFAULT_CONFIDENCE))); } break; case RigidScan::colorIntensity: // ========= Color by Intensity ========= if (perVertex) { // per-vertex intensity FOR_EACH_VERT(pushColor(colors, colorsize, (float)((v->intensity + 2048.0) / 4096))); } else { // per-face intensity (take min of 3 intensitys) FOR_EACH_TRI(pushColor(colors, colorsize, (float)((MIN(points[tv1].intensity, MIN(points[tv2].intensity, points[tv3].intensity)) + 2048.0) / 4096))); } case RigidScan::colorTrue: // ========== Color TrueColor ========== if (perVertex) { // per-vertex TrueColor // BUGBUG: For now, just color using intensity, because // I don't yet store colors for CyraScans. FOR_EACH_VERT(pushColor(colors, colorsize, (float)((v->intensity + 2048.0) / 4096))); } else { // per-face TrueColor (take avg of 3 TrueColors) FOR_EACH_TRI(pushColor(colors, colorsize, (float)((MIN(points[tv1].intensity, MIN(points[tv2].intensity, points[tv3].intensity)) + 2048.0) / 4096))); } case RigidScan::colorBoundary: { create_kdtree(); // BUGBUG, this is a little heavyhanded approach colors.reserve(colorsize * cachedBoundary.size()); for (bool c : cachedBoundary) pushConf(colors, colorsize, (uchar)(c ? 0 : 255)); } break; default: cerr << "Unhandled Color Mode. colorsource = " << source << endl; return false; } return true; } bool CyraResLevel::ReadPts(const string &inname) { // open the input .pts file const char *filename = inname.c_str(); FILE *inFile = fopen(filename, "r"); if (inFile == NULL) return FALSE; bool isOldPtsFormat = false; // old or new cyra .pts? // Read the 3-line .pts header fscanf(inFile, "%d\n", &width); fscanf(inFile, "%d\n", &height); float a, b, c; fscanf(inFile, "%f %f %f\n", &a, &b, &c); origin.set(a, b, c); cerr << "Reading " << width << "x" << height << " Cyra scan..."; // Read in the points, since this is the only data actually in // a .pts file.... CyraSample samp; // Figure out whether it's the old or new cyra format // old: X new: X // Y Y // 0 0 0 0 0 0 // x1 y1 z1 c1 nx1 ny1 nz1 1 0 0 // x2 y2 z2 c2 nx2 ny2 nz2 0 1 0 // x3 y3 z3 c3 nx3 ny3 nz3 0 0 1 // ... 1 0 0 0 // 0 1 0 0 // 0 0 1 0 // 0 0 0 1 // x1 y1 z1 c1 // x2 y2 z2 c2 // ... char buf[2000]; int n1, n2, n3; // Read first line after 0 0 0 fgets(buf, 2000, inFile); int nitems = sscanf(buf, "%g %g %g %d %d %d %d\n", &(samp.vtx[0]), &(samp.vtx[1]), &(samp.vtx[2]), &(samp.intensity), &n1, &n2, &n3); if (nitems == 7) { // was the x1 y1 z1 c1 nx1 ny1 nz1 line... old format isOldPtsFormat = true; cerr << " (old format) "; } else if (nitems == 3) { // was the new format isOldPtsFormat = false; cerr << " (new format) "; // NOTE: Skip (ignore) the 3+4 matrix lines for (int j = 0; j < 7; j++) { fgets(buf, 2000, inFile); } } // Now, our assertion is that first line of data is read into // buf... // First reserve space, so we don't waste time doing multi mallocs... points.reserve(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { // Read position, intensity, normals Pnt3 filenrm; // Whether isOldPtsFormat or not, just ignore the normals that // are in the .pts file, for now... Since the normals Cyra // generates // are generally bogus anyways. int nread = sscanf(buf, "%f %f %f %d\n", &(samp.vtx[0]), &(samp.vtx[1]), &(samp.vtx[2]), &(samp.intensity)); fgets(buf, 2000, inFile); if (nread != 4) { int lineno = ((isOldPtsFormat) ? 4 : 11) + x * height + y; cerr << "Error: Trouble reading Cyra input line " << lineno << "." << endl; return false; } samp.nrm[0] = 0; samp.nrm[1] = 0; samp.nrm[2] = 32767; // Convert to millimeters samp.vtx *= 1000.0; // Compute confidence if (samp.vtx[0] == 0. && samp.vtx[1] == 0. && samp.vtx[2] == 0. && samp.intensity == 0) { // then point is missing data samp.confidence = 0.0; } else { samp.confidence = CYRA_DEFAULT_CONFIDENCE; // count number of valid points numpoints++; // unweight specular highlights -- linearly // make the weight falloff to 0 between intensities // -800 and 2048 if (samp.intensity > -800) { float unweightfactor = (2048.0 - samp.intensity) / (2048.0 - (-800)); samp.confidence *= unweightfactor; } // also make the weight falloff between -1600 and -2048 if (samp.intensity < -1600) { float unweightfactor = (2048.0 + samp.intensity) / (2048.0 - 1600.0); samp.confidence *= unweightfactor; } } // Now put the vertex into the array points.push_back(samp); } } cerr << "done." << endl; // Now actually figure out the "correct" tesselation // first reserve space, so we don't waste time doing multi mallocs... tris.reserve((width - 1) * (height - 1)); // Grab the CyraTessDepth from TCL... char *CTDstring = Tcl_GetVar(g_tclInterp, "CyraTessDepth", TCL_GLOBAL_ONLY); if (CTDstring == NULL) { CyraTessDepth = DEFAULT_CYRA_TESS_DEPTH; } else { // String defined, get it...? sscanf(CTDstring, "%f", &CyraTessDepth); // If 0, then set to default if (CyraTessDepth == 0) { CyraTessDepth = DEFAULT_CYRA_TESS_DEPTH; } } // Grab the CyraFilterSpikes from TCL... char *CFSstring = Tcl_GetVar(g_tclInterp, "CyraFilterSpikes", TCL_GLOBAL_ONLY); if (CFSstring == NULL) { CyraFilterSpikes = DEFAULT_CYRA_FILTER_SPIKES; } else { // String defined, get it...? int CFSval; sscanf(CFSstring, "%d", &CFSval); CyraFilterSpikes = (CFSval == 0) ? FALSE : TRUE; } // Grab the CyraFillHoles from TCL... char *CFHstring = Tcl_GetVar(g_tclInterp, "CyraFillHoles", TCL_GLOBAL_ONLY); if (CFHstring == NULL) { CyraFillHoles = DEFAULT_CYRA_FILTER_SPIKES; } else { // String defined, get it...? int CFHval; sscanf(CFHstring, "%d", &CFHval); CyraFillHoles = (CFHval == 0) ? FALSE : TRUE; } ////////////// Filter out spikes? /////////// if (CyraFilterSpikes) { cerr << "Filtering out high-intensity spikes...."; for (int x = 0; x < width - 1; x++) { for (int y = 0; y < height - 1; y++) { CyraSample *v1 = &(point(x, y)); // Look for random single spikes of noise... float myZ = v1->vtx[2]; int myI = v1->intensity; float neighborZ = 0; float neighborI = 0; float neighborWt = 0; int neighborsDeeper = 0; int neighborsCloser = 0; // over 3x3 neighborhood... // within 300mm depth... for (int nex = MAX(0, x - 1); nex <= MIN(width - 1, x + 1); nex++) { for (int ney = MAX(0, y - 1); ney <= MIN(width - 1, y + 1); ney++) { CyraSample *ne = &point(nex, ney); if (ne->vtx[2] < myZ) neighborsDeeper++; else neighborsCloser++; if (ne->vtx[2] > myZ - 150 && ne->vtx[2] < myZ + 150 && (nex != x || ney != y) && ne->intensity < myI) { float neWt = myI - ne->intensity; neighborZ += ne->vtx[2] * neWt; neighborI += ne->intensity * neWt; neighborWt += neWt; } } } if (neighborWt != 0) { neighborZ /= neighborWt; neighborI /= neighborWt; if (neighborsDeeper <= 2 && neighborsCloser >= 5 && myI > neighborI + 20) { // This point seems to be farther away, and brighter, // than // most of it's neighbors... We think it's the funny // artifact... // cerr << "before dd: " << (myZ-neighborZ) << " " << // (myI-neighborI) // << " depths: " << myZ << " , " << neighborZ << " // ; intens: " // << myI << " , " << neighborI << endl; float posScale = neighborZ / myZ; v1->vtx[0] *= posScale; v1->vtx[1] *= posScale; v1->vtx[2] *= posScale; v1->intensity = neighborI; } } } // end of filtering spikes... } cerr << "Done! (filtering)\n"; } ////////////// Fill holes? /////////// if (CyraFillHoles) { cerr << "Filling Tiny Holes...."; for (int x = 0; x < width - 1; x++) { for (int y = 0; y < height - 1; y++) { CyraSample *v1 = &(point(x, y)); float myZ = v1->vtx[2]; float neighborsZ = 0; float neighborsWt = 0; int xstart = MAX(0, x - 1); int ystart = MAX(0, y - 1); int xend = MIN(width - 1, x + 1); int yend = MIN(height - 1, y + 1); // over 3x3 neighborhood... // find the mean... for (int nex = xstart; nex <= xend; nex++) { for (int ney = ystart; ney <= yend; ney++) { CyraSample *ne = &point(nex, ney); if (nex != x || ney != y) { neighborsZ += ne->vtx[2]; neighborsWt += 1.0; } } } neighborsZ /= neighborsWt; // Find the neighbor closest to the mean... // over 3x3 neighborhood... float closestZ = point(xstart, ystart).vtx[2]; float closestDZ2 = (neighborsZ - closestZ) * (neighborsZ - closestZ); for (int nex = xstart; nex <= xend; nex++) { for (int ney = ystart; ney <= yend; ney++) { CyraSample *ne = &point(nex, ney); float neDZ2 = (neighborsZ - ne->vtx[2]) * (neighborsZ - ne->vtx[2]); if (neDZ2 < closestDZ2) { closestDZ2 = neDZ2; closestZ = ne->vtx[2]; } } } // Set neighborsZ to be closestZ // (this way, if we have one outlier, we'll still grab from the // z depth of the main cluster...) neighborsZ = closestZ; // Make sure the neighbors are clustered closely together... // say, within 150mm of each other...? int neighborsClose = 0; float neighborX = 0; float neighborY = 0; float neighborZ = 0; float neighborI = 0; float neighborConf = 0; for (int nex = xstart; nex <= xend; nex++) { for (int ney = ystart; ney <= yend; ney++) { CyraSample *ne = &point(nex, ney); if ((nex != x || ney != y) && (ne->vtx[2] < neighborsZ + CyraTessDepth && ne->vtx[2] > neighborsZ - CyraTessDepth)) { neighborsClose++; neighborX += ne->vtx[0]; neighborY += ne->vtx[1]; neighborZ += ne->vtx[2]; neighborI += ne->intensity; neighborConf += ne->confidence; } } } // cerr <<" "<<neighborsClose<< ", nz " <<neighborsZ<< " , myz " // <<myZ<< endl; // Only fill holes of data off by more than 150mm... // e.g. make sure this point is far from the neighborhood, if (neighborsWt < 7 || neighborsClose < 7 || (neighborsZ < myZ + CyraTessDepth && neighborsZ > myZ - CyraTessDepth)) continue; // otherwise, modify the puppy.... v1->vtx[0] = neighborX / neighborsClose; v1->vtx[1] = neighborY / neighborsClose; v1->vtx[2] = neighborZ / neighborsClose; v1->intensity = neighborI / neighborsClose; v1->confidence = neighborConf / neighborsClose; } // end of filling holes... } cerr << "Done! (filling holes)\n"; } ////////////// Generate the Tesselation /////////// cerr << "Generating tesselation..."; for (int x = 0; x < width - 1; x++) { for (int y = 0; y < height - 1; y++) { // get pointers to the four vertices surrounding this // square: // 2 4 // 1 3 CyraSample *v1 = &(point(x, y)); CyraSample *v2 = &(point(x, y + 1)); CyraSample *v3 = &(point(x + 1, y)); CyraSample *v4 = &(point(x + 1, y + 1)); CyraTess tess = TESS0; // Set mask bit to be true if a vertex: // a) exists (has confidence) // b) is not an occlusion edge unsigned int mask = ((v4->confidence && !grazing(v3->vtx, v4->vtx, v2->vtx)) ? 8 : 0) + ((v3->confidence && !grazing(v1->vtx, v3->vtx, v4->vtx)) ? 4 : 0) + ((v2->confidence && !grazing(v4->vtx, v2->vtx, v1->vtx)) ? 2 : 0) + ((v1->confidence && !grazing(v2->vtx, v1->vtx, v3->vtx)) ? 1 : 0); switch (mask) { case 15: // verts: 1 2 3 4 tess = TESS14; numtris += 2; break; case 14: // verts: 2 3 4 tess = TESS4; numtris++; break; case 13: // verts: 1 3 4 tess = TESS3; numtris++; break; case 11: // verts 1 2 4 tess = TESS2; numtris++; break; case 7: // verts 1 2 3 tess = TESS1; numtris++; break; default: // two or less vertices tess = TESS0; break; } // Now put the tesselation into the array tris.push_back(tess); } } cerr << "Done! (tesselating)" << endl; CalcNormals(); cerr << "Loaded " << numpoints << " vertices, " << numtris << " triangles." << endl; return true; } bool CyraResLevel::WritePts(const string &outname) { CyraSample samp; // open the output .pts file const char *filename = outname.c_str(); FILE *outFile = fopen(filename, "w"); if (outFile == NULL) { cerr << "Error: couldn't open output file " << filename << endl; return FALSE; } // compute bounds, so we can crop to the smallest rectangle // that contains all the data. int lox = width - 1; int hix = 0; int loy = height - 1; int hiy = 0; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { samp = point(x, y); if (samp.confidence != 0) { lox = (x < lox) ? x : lox; hix = (x > hix) ? x : hix; loy = (y < loy) ? y : loy; hiy = (y > hiy) ? y : hiy; } } } if (lox > hix || loy > hiy) { cerr << "Error: no nonzero-points found. Aborting..." << endl; return FALSE; } // Write the 3-line .pts header fprintf(outFile, "%d\n", hix - lox + 1); fprintf(outFile, "%d\n", hiy - loy + 1); fprintf(outFile, "%f %f %f\n", origin[0], origin[1], origin[2]); cerr << "Writing " << (hix - lox + 1) << "x" << (hiy - loy + 1) << " Cyra scan..."; // Write out the points, since this is the only data actually in // a .pts file.... for (int x = lox; x <= hix; x++) { for (int y = loy; y <= hiy; y++) { samp = point(x, y); if (samp.confidence == 0) { fprintf(outFile, "0 0 0 0 0 0 0\n"); } else { // divide by 1000, since .pts files are always in meters fprintf(outFile, "%.5f %.5f %.5f %d 0 0 1\n", samp.vtx[0] / 1000.0, samp.vtx[1] / 1000.0, samp.vtx[2] / 1000.0, samp.intensity); } } } fclose(outFile); cerr << "Done." << endl; return TRUE; } // Recompute the normals void CyraResLevel::CalcNormals(void) { // Compute Normals Pnt3 hedge, vedge, norm; Pnt3 v1, v2, v3, v4; CyraTess tess; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (point(x, y).confidence > 0) { hedge.set(0, 0, 0); vedge.set(0, 0, 0); // Lower left corner if (x > 0 && y > 0) { v1 = point(x - 1, y - 1).vtx; v2 = point(x - 1, y).vtx; v3 = point(x, y - 1).vtx; v4 = point(x, y).vtx; tess = tri(x - 1, y - 1); switch (tess) { case TESS2: hedge += 0.5 * (v4 - v2); vedge += 0.5 * (v2 - v1); break; case TESS3: hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v4 - v3); break; case TESS4: case TESS14: hedge += 1.0 * (v4 - v2); vedge += 1.0 * (v4 - v3); break; case TESS23: hedge += 0.5 * (v4 - v2); hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v2 - v1); vedge += 0.5 * (v4 - v3); break; } } // Upper left corner if (x > 0 && y < height - 1) { v1 = point(x - 1, y).vtx; v2 = point(x - 1, y + 1).vtx; v3 = point(x, y).vtx; v4 = point(x, y + 1).vtx; tess = tri(x - 1, y); switch (tess) { case TESS1: hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v2 - v1); break; case TESS3: case TESS23: hedge += 1.0 * (v3 - v1); vedge += 1.0 * (v4 - v3); break; case TESS4: hedge += 0.5 * (v4 - v2); vedge += 0.5 * (v4 - v3); break; case TESS14: hedge += 0.5 * (v4 - v2); hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v2 - v1); vedge += 0.5 * (v4 - v3); break; } } // Lower right corner if (x < width - 1 && y > 0) { v1 = point(x, y - 1).vtx; v2 = point(x, y).vtx; v3 = point(x + 1, y - 1).vtx; v4 = point(x + 1, y).vtx; tess = tri(x, y - 1); switch (tess) { case TESS1: hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v2 - v1); break; case TESS2: case TESS23: hedge += 1.0 * (v4 - v2); vedge += 1.0 * (v2 - v1); break; case TESS4: hedge += 0.5 * (v4 - v2); vedge += 0.5 * (v4 - v3); break; case TESS14: hedge += 0.5 * (v4 - v2); hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v2 - v1); vedge += 0.5 * (v4 - v3); break; } } // Upper right corner if (x < width - 1 && y < height - 1) { v1 = point(x, y).vtx; v2 = point(x, y + 1).vtx; v3 = point(x + 1, y).vtx; v4 = point(x + 1, y + 1).vtx; tess = tri(x, y); switch (tess) { case TESS1: case TESS14: hedge += 1.0 * (v3 - v1); vedge += 1.0 * (v2 - v1); break; case TESS2: hedge += 0.5 * (v4 - v2); vedge += 0.5 * (v2 - v1); break; case TESS3: hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v4 - v3); break; case TESS23: hedge += 0.5 * (v4 - v2); hedge += 0.5 * (v3 - v1); vedge += 0.5 * (v2 - v1); vedge += 0.5 * (v4 - v3); break; } } // Now compute cross product, save normal norm = cross(hedge, vedge); norm.normalize(); norm *= 32767; point(x, y).nrm[0] = norm[0]; point(x, y).nrm[1] = norm[1]; point(x, y).nrm[2] = norm[2]; } } } } // detects grazing tris bool CyraResLevel::grazing(Pnt3 v1, Pnt3 v2, Pnt3 v3) { #if 0 // First compute (negative) norm, which should point pretty // much away from the origin. Compare this to the vector // from the origin.... Pnt3 edge1 = v3 - v2; Pnt3 edge2 = v2 - v1; Pnt3 norm = cross(edge1, edge2); norm.normalize(); // Treat v2 as a vector from 0,0,0 v2.normalize(); float cosdev = dot(norm, v2); //if (cosdev < .259) { // More than 75-degrees away from perpendicular if (cosdev < .017) { // more than 89-degrees away from perpendicular return true; } else { return false; } // #else // #ifdef USE_Z_AS_DEPTH // Check to see if depth difference is greater than our // typical occlusion distance (CyraTessDepthmm) if (v1[2] > v2[2] + CyraTessDepth || v1[2] > v3[2] + CyraTessDepth || v2[2] > v1[2] + CyraTessDepth || v2[2] > v3[2] + CyraTessDepth || v3[2] > v1[2] + CyraTessDepth || v3[2] > v2[2] + CyraTessDepth) { return true; } else { return false; } #else // Don't use Z as depth... compute distance from the center... float v1dist = sqrtf(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2]); float v2dist = sqrtf(v2[0] * v2[0] + v2[1] * v2[1] + v2[2] * v2[2]); float v3dist = sqrtf(v3[0] * v3[0] + v3[1] * v3[1] + v3[2] * v3[2]); if (v1dist > v2dist + CyraTessDepth || v1dist > v3dist + CyraTessDepth || v2dist > v1dist + CyraTessDepth || v2dist > v3dist + CyraTessDepth || v3dist > v1dist + CyraTessDepth || v3dist > v2dist + CyraTessDepth) { return true; } else { return false; } //#endif // USE_Z_AS_DEPTH #endif // 0 } int CyraResLevel::num_vertices(void) { return numpoints; } int CyraResLevel::num_tris(void) { return numtris; } void CyraResLevel::growBBox(Bbox &bbox) { FOR_EACH_VERT(bbox.add(v->vtx)); } void flip3shorts(short *p) { p[0] *= -1; p[1] *= -1; p[2] *= -1; } void CyraResLevel::flipNormals(void) { // Ok, to flip the normals, we: // 1. Reverse the order of the vertical scanlines (in memory) // 2. Reverse the order of the Triangle tesselation flags (in mem) // 3. Reverse the sign of the per-vertex normals ////// 1. Reverse the order of the vertical scanlines (in memory) CyraSample samp; for (int xx = 0; xx < width / 2; xx++) { for (int yy = 0; yy < height; yy++) { samp = point(xx, yy); point(xx, yy) = point(width - xx - 1, yy); point(width - xx - 1, yy) = samp; } } ////// 2. Reverse the order of the Triangle tesselation flags (in mem) // (This also requires changing TESS1 <-> TESS3, TESS2 <-> TESS4) CyraTess tess; // Note: only goes to width-1, but want to do middle col, too, so // the width-1+1 cancel out... for (int xx = 0; xx < (width) / 2; xx++) { for (int yy = 0; yy < height - 1; yy++) { tess = tri(xx, yy); // Set scanline xx to be mirror of width-xx-2 switch (tri(width - xx - 2, yy)) { case TESS0: tri(xx, yy) = TESS0; break; case TESS1: tri(xx, yy) = TESS3; break; case TESS2: tri(xx, yy) = TESS4; break; case TESS3: tri(xx, yy) = TESS1; break; case TESS4: tri(xx, yy) = TESS2; break; case TESS14: case TESS23: tri(xx, yy) = TESS14; break; } // Set scanline width-xx-2 to be mirror of xx switch (tess) { case TESS0: tri(width - xx - 2, yy) = TESS0; break; case TESS1: tri(width - xx - 2, yy) = TESS3; break; case TESS2: tri(width - xx - 2, yy) = TESS4; break; case TESS3: tri(width - xx - 2, yy) = TESS1; break; case TESS4: tri(width - xx - 2, yy) = TESS2; break; case TESS14: case TESS23: tri(width - xx - 2, yy) = TESS14; break; } } } ////// 3. Reverse the sign of the per-vertex normals FOR_EACH_VERT(flip3shorts(v->nrm)); } bool CyraResLevel::filtered_copy(CyraResLevel &original, const VertexFilter &filter) { width = original.width; height = original.height; numpoints = 0; numtris = 0; points.clear(); tris.clear(); origin = original.origin; CyraSample zero; zero.vtx.set(0, 0, 0); zero.nrm[0] = 0; zero.nrm[1] = 0; zero.nrm[2] = 32767; zero.confidence = 0; zero.intensity = 0; // Copy the vertices for (int i = 0; i < original.points.size(); i++) { if (filter.accept(original.points[i].vtx)) { points.push_back(original.points[i]); numpoints++; } else { points.push_back(zero); } } // Copy the triangles for (int xx = 0; xx < width - 1; xx++) { for (int yy = 0; yy < height - 1; yy++) { bool conf00 = (point(xx, yy).confidence > 0); bool conf01 = (point(xx, yy + 1).confidence > 0); bool conf10 = (point(xx + 1, yy).confidence > 0); bool conf11 = (point(xx + 1, yy + 1).confidence > 0); // Compute new tess, minus possible vertices CyraTess tess; switch (original.tri(xx, yy)) { case TESS0: tess = TESS0; break; case TESS1: if (conf00 && conf10 && conf01) tess = TESS1; else tess = TESS0; break; case TESS2: if (conf00 && conf01 && conf11) tess = TESS2; else tess = TESS0; break; case TESS3: if (conf00 && conf10 && conf11) tess = TESS3; else tess = TESS0; break; case TESS4: if (conf01 && conf10 && conf11) tess = TESS4; else tess = TESS0; break; case TESS14: case TESS23: if (conf00 && conf01 && conf10 && conf11) tess = TESS14; else if (conf00 && conf01 && conf10) tess = TESS1; else if (conf00 && conf01 && conf11) tess = TESS2; else if (conf00 && conf10 && conf11) tess = TESS3; else if (conf01 && conf10 && conf11) tess = TESS4; else tess = TESS0; break; default: cerr << "Unhandled tesselation flag " << original.tri(xx, yy) << " in clipping..." << endl; } // Push Tri flag, increment numtris tris.push_back(tess); if (tess == TESS14 || tess == TESS23) numtris += 2; else if (tess == TESS0) numtris += 0; else numtris++; } } return true; } bool CyraResLevel::filter_inplace(const VertexFilter &filter) { numpoints = 0; numtris = 0; CyraSample zero; zero.vtx.set(0, 0, 0); zero.nrm[0] = zero.nrm[1] = 0; zero.nrm[2] = 32767; zero.confidence = 0; zero.intensity = 0; // Filter the vertices FOR_EACH_VERT(*v = (filter.accept(v->vtx) && ++numpoints) ? *v : zero); // Copy the triangles for (int xx = 0; xx < width - 1; xx++) { for (int yy = 0; yy < height - 1; yy++) { bool conf00 = (point(xx, yy).confidence > 0); bool conf01 = (point(xx, yy + 1).confidence > 0); bool conf10 = (point(xx + 1, yy).confidence > 0); bool conf11 = (point(xx + 1, yy + 1).confidence > 0); // Compute new tess, minus possible vertices CyraTess tess; switch (tri(xx, yy)) { case TESS0: tess = TESS0; break; case TESS1: if (conf00 && conf10 && conf01) tess = TESS1; else tess = TESS0; break; case TESS2: if (conf00 && conf01 && conf11) tess = TESS2; else tess = TESS0; break; case TESS3: if (conf00 && conf10 && conf11) tess = TESS3; else tess = TESS0; break; case TESS4: if (conf01 && conf10 && conf11) tess = TESS4; else tess = TESS0; break; case TESS14: case TESS23: if (conf00 && conf01 && conf10 && conf11) tess = TESS14; else if (conf00 && conf01 && conf10) tess = TESS1; else if (conf00 && conf01 && conf11) tess = TESS2; else if (conf00 && conf10 && conf11) tess = TESS3; else if (conf01 && conf10 && conf11) tess = TESS4; else tess = TESS0; break; default: cerr << "Unhandled tesselation flag " << tri(xx, yy) << " in clipping..." << endl; } // Push Tri flag, increment numtris tri(xx, yy) = tess; if (tess == TESS14 || tess == TESS23) numtris += 2; else if (tess == TESS0) numtris += 0; else numtris++; } } isDirty_cache = true; return true; } void CyraResLevel::create_kdtree(void) { // If everything built, no-op. if ((!isDirty_cache) && (kdtree)) return; // otherwise, rebuild if (kdtree) delete kdtree; cachedPoints.clear(); cachedNorms.clear(); cachedBoundary.clear(); // re-assemble cachedPoints, norms, boundary cachedPoints.reserve(num_vertices()); cachedNorms.reserve(num_vertices() * 3); cachedBoundary.reserve(num_vertices()); FOR_EACH_VERT(cachedPoints.push_back(v->vtx)); FOR_EACH_VERT(cachedNorms.insert(cachedNorms.end(), v->nrm, v->nrm + 3)); FOR_EACH_VERT(cachedBoundary.push_back(( bool)(vx == 0 || vx == width - 1 || vy == 0 || vy == height - 1 || (tri(vx - 1, vy - 1) != TESS14 && tri(vx - 1, vy - 1) != TESS23 && tri(vx - 1, vy - 1) != TESS4) || (tri(vx - 1, vy) != TESS14 && tri(vx - 1, vy) != TESS23 && tri(vx - 1, vy) != TESS3) || (tri(vx, vy - 1) != TESS14 && tri(vx, vy - 1) != TESS23 && tri(vx, vy - 1) != TESS2) || (tri(vx, vy) != TESS14 && tri(vx, vy) != TESS23 && tri(vx, vy) != TESS1)))); kdtree = CreateKDindtree(cachedPoints.data(), cachedNorms.data(), cachedPoints.size()); isDirty_cache = false; } // for ICP... void CyraResLevel::subsample_points(float rate, vector<Pnt3> &p, vector<Pnt3> &n) { int nv = num_vertices(); int totalNum = (int)(rate * nv); if (totalNum > nv) return; p.clear(); p.reserve(totalNum); n.clear(); n.reserve(totalNum); int num = totalNum; int end = nv; for (int i = 0; i < end; i++) { if (random() % nv < num) { p.push_back(points[i].vtx); // save point pushNormalAsPnt3(n, points[i].nrm, 0); num--; } nv--; } assert(num == 0); if (p.size() != totalNum) { printf("Selected wrong number of points in the CyraResLevel subsample " "proc.\n"); } } bool CyraResLevel::closest_point(const Pnt3 &p, const Pnt3 &n, Pnt3 &cp, Pnt3 &cn, float thr, bool bdry_ok) { create_kdtree(); int ind, ans; ans = kdtree->search(&cachedPoints[0], &cachedNorms[0], p, n, ind, thr); if (ans) { if (!bdry_ok) { // disallow closest points that are on the mesh boundary if (cachedBoundary[ind]) return 0; } cp = cachedPoints[ind]; short *sp = &cachedNorms[ind * 3]; cn.set(sp[0] / 32767.0, sp[1] / 32767.0, sp[2] / 32767.0); } return ans; }
34.731298
80
0.435755
[ "mesh", "geometry", "vector" ]
f39927e4c610fc0dfb716f4721120bcf9194af2a
4,561
hpp
C++
include/nbla/dtypes.hpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
2,792
2017-06-26T13:05:44.000Z
2022-03-28T07:55:26.000Z
include/nbla/dtypes.hpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
138
2017-06-27T07:04:44.000Z
2022-02-28T01:37:15.000Z
include/nbla/dtypes.hpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
380
2017-06-26T13:23:52.000Z
2022-03-25T16:51:30.000Z
// Copyright 2018,2019,2020,2021 Sony 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. #ifndef NBLA_DTYPES_HPP_ #define NBLA_DTYPES_HPP_ #include <nbla/exception.hpp> namespace nbla { // Forward declaration struct Half; /** \addtogroup NNablaCoreGrp */ /*@{*/ /** ENUM for dtypes Compatible with numpy DTYPES. It allows us to use np.dtype in Python interface. */ enum class dtypes { BOOL = 0, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE, // // Following items are for compatibility with Numpy // CFLOAT, // CDOUBLE, // CLONGDOUBLE, // OBJECT = 17, // STRING, // UNICODE, // VOID, // Appended in numpy 1.6 // DATETIME, // TIMEDELTA, HALF = 23, // NTYPES, // NOTYPE, // CHAR, // USERDEF = 256, // NTYPES_ABI_COMPATIBLE = 21 }; /** A function to get dtype enum by dtype of C++. EX) dtypes dtype = get_dtype<T>::type; */ template <typename T> dtypes get_dtype() { NBLA_ERROR(error_code::type, "Unsupported dtype."); } #define GET_DTYPE_TEMPLATE_SPECIAL(type, Dtype) \ template <> inline dtypes get_dtype<type>() { return dtypes::Dtype; } GET_DTYPE_TEMPLATE_SPECIAL(unsigned char, UBYTE); GET_DTYPE_TEMPLATE_SPECIAL(char, BYTE); GET_DTYPE_TEMPLATE_SPECIAL(unsigned short, USHORT); GET_DTYPE_TEMPLATE_SPECIAL(short, SHORT); GET_DTYPE_TEMPLATE_SPECIAL(unsigned int, UINT); GET_DTYPE_TEMPLATE_SPECIAL(int, INT); GET_DTYPE_TEMPLATE_SPECIAL(unsigned long, ULONG); GET_DTYPE_TEMPLATE_SPECIAL(long, LONG); GET_DTYPE_TEMPLATE_SPECIAL(unsigned long long, ULONGLONG); GET_DTYPE_TEMPLATE_SPECIAL(long long, LONGLONG); GET_DTYPE_TEMPLATE_SPECIAL(float, FLOAT); GET_DTYPE_TEMPLATE_SPECIAL(double, DOUBLE); GET_DTYPE_TEMPLATE_SPECIAL(bool, BOOL); GET_DTYPE_TEMPLATE_SPECIAL(long double, LONGDOUBLE); GET_DTYPE_TEMPLATE_SPECIAL(nbla::Half, HALF); #undef GET_DTYPE_TEMPLATE_SPECIAL /// Convert dtypes to string inline string dtype_to_string(dtypes dtype) { #define GET_DTYPE_STRING(TYPE) \ case dtypes::TYPE: \ s = #TYPE; \ break; string s; switch (dtype) { GET_DTYPE_STRING(UBYTE); GET_DTYPE_STRING(BYTE); GET_DTYPE_STRING(USHORT); GET_DTYPE_STRING(SHORT); GET_DTYPE_STRING(UINT); GET_DTYPE_STRING(INT); GET_DTYPE_STRING(ULONG); GET_DTYPE_STRING(LONG); GET_DTYPE_STRING(ULONGLONG); GET_DTYPE_STRING(LONGLONG); GET_DTYPE_STRING(FLOAT); GET_DTYPE_STRING(DOUBLE); GET_DTYPE_STRING(BOOL); GET_DTYPE_STRING(LONGDOUBLE); GET_DTYPE_STRING(HALF); } if (s.empty()) { NBLA_ERROR(error_code::type, "Unknown dtype %d", int(dtype)); } return s; #undef GET_DTYPE_STRING } /** Figure out the size of given dtype. */ inline size_t sizeof_dtype(dtypes dtype) { //-- macro #define GET_DTYPE_SIZE(type, TYPE) \ case dtypes::TYPE: \ s = sizeof(type); \ break; size_t s = 0; //-- switch (dtype) { GET_DTYPE_SIZE(unsigned char, UBYTE); GET_DTYPE_SIZE(char, BYTE); GET_DTYPE_SIZE(unsigned short, USHORT); GET_DTYPE_SIZE(short, SHORT); GET_DTYPE_SIZE(unsigned int, UINT); GET_DTYPE_SIZE(int, INT); GET_DTYPE_SIZE(unsigned long, ULONG); GET_DTYPE_SIZE(long, LONG); GET_DTYPE_SIZE(unsigned long long, ULONGLONG); GET_DTYPE_SIZE(long long, LONGLONG); GET_DTYPE_SIZE(float, FLOAT); GET_DTYPE_SIZE(double, DOUBLE); GET_DTYPE_SIZE(bool, BOOL); GET_DTYPE_SIZE(long double, LONGDOUBLE); GET_DTYPE_SIZE(uint16_t, HALF); } if (s == 0) { NBLA_ERROR(error_code::type, "Unsupported type: %s", dtype_to_string(dtype).c_str()); } return s; #undef GET_DTYPE_SIZE #undef GET_DTYPE_SIZE_UNSUPPORTED } /*@}*/ } #endif
27.981595
80
0.658627
[ "object" ]
f39c42a108f61125b5a6ec2f8276d1f0bbc1c89b
7,709
cpp
C++
source/src/OddsPuzzle.cpp
jane8384/seven-monkeys
119cb7312f25d54e88f212a8710a512b893b046d
[ "MIT" ]
3
2017-11-16T01:54:09.000Z
2018-05-20T15:33:21.000Z
src/OddsPuzzle.cpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
null
null
null
src/OddsPuzzle.cpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
3
2017-09-18T11:44:41.000Z
2019-12-25T11:30:26.000Z
// // OddsPuzzle.cpp // SevenMonkeys // #include "OddsPuzzle.hpp" USING_NS_CC; USING_NS_SM; OddsPuzzle::OddsPuzzle() { CCLOG("// OddsPuzzle %x Constructor", (int)(long)this); } OddsPuzzle::~OddsPuzzle() { CCLOG("// OddsPuzzle %x Destructor", (int)(long)this); if (mvpPotLabel) { mvpPotLabel->removeFromParentAndCleanup(true); mvpPotLabel = nullptr; } } bool OddsPuzzle::init() { if (!PuzzleLayer::init()) { return false; } if (UserDefault::getInstance()->getIntegerForKey("mode") == EASY) { mvPokerActionInterval = 2.f; } else if (UserDefault::getInstance()->getIntegerForKey("mode") == NORMAL) { mvPokerActionInterval = 1.5f; } else { mvPokerActionInterval = 1.f; } this->scheduleUpdate(); return true; } void OddsPuzzle::update(float dt) { if (isRunningPuzzle() && !isWaitingPuzzle()) { deal(); setWaitingPuzzle(true); } if (mvIsRunningPokerActions && !isRunningPuzzle()) { this->unschedule(CC_SCHEDULE_SELECTOR(OddsPuzzle::runPokerActions)); } } void OddsPuzzle::deal() { mvBlind = 2; if (UserDefault::getInstance()->getIntegerForKey("mode") > NORMAL) { mvBlind = 3; } mvPot = randInt(1, (int)mtpPlayers.size()) * mvBlind; addPlayers(); addChips(); mvPrevAmount = 0; mvPrevAction = 0; mvCurrentPlayer = 1; mvIsRunningPokerActions = true; this->schedule(CC_SCHEDULE_SELECTOR(OddsPuzzle::runPokerActions), 1.0f); } void OddsPuzzle::addPlayers() { // std::vector<int> stacks { 1000, 2000, 2500, 5000 }; std::vector<int> stacks { 1000, 2000 }; mtpPlayers[0]->setHero(true); for (short i = 0; i < mtpPlayers.size(); ++i) { mtpPlayers[i]->setAmount(stacks[randInt((int32_t)stacks.size())]); auto spriteName = mtpPlayers[i]->isHero() ? "HeroSticker.png" : "VillainSticker" + std::to_string(i) + ".png"; auto sprite = Sprite::createWithSpriteFrameName(spriteName); sprite->setOpacity(0); sprite->setNormalizedPosition(mtpPlayers[i]->mPositions.sticker); this->addChild(sprite, kZOrderPuzzle::players); sprite->runAction(FadeIn::create(.25f * i)); } stacks.clear(); stacks.shrink_to_fit(); } void OddsPuzzle::addChips() { for (short i = 0; i < mtpPlayers.size(); ++i) { auto stack = Sprite::createWithSpriteFrameName("Stack" + std::to_string(mtpPlayers[i]->getAmount()) + ".png"); stack->setOpacity(0); stack->setNormalizedPosition(mtpPlayers[i]->mPositions.stack); this->addChild(stack, kZOrderPuzzle::stack); stack->runAction(FadeIn::create(.25f * i)); } // Pot auto pot = Sprite::createWithSpriteFrameName("Pot.png"); pot->setOpacity(0); pot->setNormalizedPosition(Vec2(.5f, .42f)); this->addChild(pot, kZOrderPuzzle::pot); pot->runAction(FadeIn::create(.25f)); // Marker auto potMarker = Sprite::createWithSpriteFrameName("ChipsMarker.png"); potMarker->setOpacity(0); potMarker->setNormalizedPosition(Vec2(.5f, .5f)); this->addChild(potMarker, kZOrderPuzzle::pot); potMarker->runAction(FadeIn::create(.25f)); // Label mvpPotLabel = Label::createWithTTF(std::to_string(mvPot), "fonts/OpenSans-ExtraBold.ttf", 11); mvpPotLabel->setOpacity(0); mvpPotLabel->setNormalizedPosition(Vec2(.5f, .518f)); this->addChild(mvpPotLabel, kZOrderPuzzle::pot); mvpPotLabel->runAction(FadeIn::create(.25f)); } void OddsPuzzle::runPokerActions(float dt) { if ( HARD > UserDefault::getInstance()->getIntegerForKey("mode") && dt == 1.0f) { // interval parameter will be updated without scheduling it again this->schedule(CC_SCHEDULE_SELECTOR(OddsPuzzle::runPokerActions), mvPokerActionInterval); } PokerAction *pokerAction = new PokerAction(); pokerAction->setBlind(mvBlind); int action = pokerAction->chooseAction(mvPrevAction, mvPrevAmount); auto fadeOut = FadeOut::create(.25f); cocos2d::Sprite* pokerActionSprite; if ( action == BET || action == RAISE || action == RERAISE || action == CALL) { Game::instance().getSoundManager().playChipsSound(); pokerActionSprite = Sprite::createWithSpriteFrameName("PokerActionWithValue" + std::to_string(action) + ".png"); auto amount = Label::createWithTTF(std::to_string(pokerAction->getAmount()), "fonts/OpenSans-ExtraBold.ttf", 11); amount->setNormalizedPosition(Vec2( mtpPlayers[mvCurrentPlayer]->mPositions.sticker.x + .025f, mtpPlayers[mvCurrentPlayer]->mPositions.sticker.y)); this->addChild(amount, kZOrderPuzzle::actions + 1); amount->runAction(Sequence::create( DelayTime::create(mvPokerActionInterval), fadeOut->clone(), RemoveSelf::create(true), nullptr)); } else { pokerActionSprite = Sprite::createWithSpriteFrameName("PokerAction" + std::to_string(action) + ".png"); } pokerActionSprite->setNormalizedPosition(mtpPlayers[mvCurrentPlayer]->mPositions.sticker); this->addChild(pokerActionSprite, kZOrderPuzzle::actions); pokerActionSprite->runAction(Sequence::create( DelayTime::create(mvPokerActionInterval), fadeOut, RemoveSelf::create(true), nullptr)); // Save the data for the next player mvPrevAction = action; mvPrevAmount = pokerAction->getAmount(); mvPot += pokerAction->getAmount(); mvpPotLabel->setString(std::to_string(mvPot)); CC_SAFE_DELETE(pokerAction); mvCurrentPlayer++; if (mvCurrentPlayer >= mtpPlayers.size()) { mvIsRunningPokerActions = false; this->unschedule(CC_SCHEDULE_SELECTOR(OddsPuzzle::runPokerActions)); addTokens(); scheduleHelpPlayer(); } } void OddsPuzzle::addTokens() { int odds = (int)((float)((mvPrevAmount / (float)(mvPot + mvPrevAmount)) * 100)); std::vector<int> randomTokens; randomTokens.push_back(odds); for (short i = 0; i < mtpTokens.size() - 1; ++i) { if (randBool() || odds > 90) { randomTokens.push_back(randInt(1, odds)); } else { randomTokens.push_back(randInt(odds, 90)); } } Rand::shuffle(randomTokens); for (short i = 0; i < mtpTokens.size(); ++i) { auto sprite = Sprite::createWithSpriteFrameName("EmptyToken.png"); sprite->setOpacity(0); sprite->setNormalizedPosition(mtpTokens[i]->getPosition()); this->addChild(sprite, kZOrderPuzzle::tokens, i); sprite->runAction(FadeIn::create(.25f * i)); int percent = randomTokens[i]; if (percent == odds) { mtRightAnswer = i; mtpTokens[i]->setCorrect(true); } auto label = Label::createWithTTF(std::to_string(percent) + "%", "fonts/OpenSans-ExtraBold.ttf", 11); label->setOpacity(0); label->setNormalizedPosition(Vec2(mtpTokens[i]->getPosition().x + .02, mtpTokens[i]->getPosition().y - .03f)); this->addChild(label, kZOrderPuzzle::tokens, kTagsPuzzle::labels); label->runAction(FadeIn::create(.25f)); } randomTokens.clear(); randomTokens.shrink_to_fit(); }
26.221088
121
0.604748
[ "vector" ]
f3ab0086e39a7abb07549bc9d3c346be4b660635
5,152
cpp
C++
src/lib/dhtclient/SKAsyncRetrieval.cpp
LevyForch/SilverKing
6ab063d0f1695675271eecba723f8f1a3b4f75a5
[ "Apache-2.0" ]
null
null
null
src/lib/dhtclient/SKAsyncRetrieval.cpp
LevyForch/SilverKing
6ab063d0f1695675271eecba723f8f1a3b4f75a5
[ "Apache-2.0" ]
85
2021-06-30T01:20:47.000Z
2021-09-14T01:09:41.000Z
src/lib/dhtclient/SKAsyncRetrieval.cpp
LevyForch/SilverKing
6ab063d0f1695675271eecba723f8f1a3b4f75a5
[ "Apache-2.0" ]
null
null
null
/** * * $Header: $ * $Change: $ * $DateTime: $ */ #include "SKAsyncRetrieval.h" #include "SKAsyncNSPerspective.h" #include "SKStoredValue.h" #include "SKClientException.h" #include "jace/Jace.h" using jace::java_new; using jace::java_cast; using namespace jace; #include "jace/proxy/java/lang/String.h" using jace::proxy::java::lang::String; #include "jace/proxy/java/lang/Object.h" using ::jace::proxy::java::lang::Object; #include "jace/proxy/java/lang/Throwable.h" using jace::proxy::java::lang::Throwable; #include "jace/proxy/java/util/Set.h" using jace::proxy::java::util::Set; #include "jace/proxy/java/util/List.h" using jace::proxy::java::util::List; #include "jace/proxy/java/util/Map.h" using jace::proxy::java::util::Map; #include "jace/proxy/java/util/HashSet.h" using jace::proxy::java::util::HashSet; #include "jace/proxy/java/util/HashMap.h" using jace::proxy::java::util::HashMap; #include "jace/proxy/java/util/Map_Entry.h" using jace::proxy::java::util::Map_Entry; #include "jace/proxy/java/util/Iterator.h" using jace::proxy::java::util::Iterator; #include "jace/proxy/com/ms/silverking/log/Log.h" using jace::proxy::com::ms::silverking::log::Log; #include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncRetrieval.h" using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncRetrieval; #include "jace/proxy/com/ms/silverking/cloud/dht/client/StoredValue.h" using jace::proxy::com::ms::silverking::cloud::dht::client::StoredValue; /* protected */ SKAsyncRetrieval::SKAsyncRetrieval(){}; /* public */ SKAsyncRetrieval::SKAsyncRetrieval(AsyncRetrieval * pAsyncRetrieval){ pImpl = pAsyncRetrieval; } void * SKAsyncRetrieval::getPImpl() { return pImpl; } SKAsyncRetrieval::~SKAsyncRetrieval() { if(pImpl ) { delete pImpl; pImpl = NULL; } }; SKMap<string,SKStoredValue * > * SKAsyncRetrieval::_getStoredValues(bool latest) { SKMap<string, SKStoredValue*> * valueMap = new SKMap<string, SKStoredValue * >(); AsyncRetrieval * pAsync = (AsyncRetrieval*)getPImpl(); Map storedValues ; try { storedValues = latest ? pAsync->getLatestStoredValues() : pAsync->getStoredValues(); } catch( Throwable &t ) { //throw SKClientException( &t, __FILE__, __LINE__ ); repackException(__FILE__, __LINE__ ); } if(storedValues.isNull()){ Log::fine( "No values found" ); return valueMap; } Set entrySet(storedValues.entrySet()); Log::fine("SKAsyncRetrieval getStoredValues "); for (Iterator it(entrySet.iterator()); it.hasNext();) { Map_Entry entry = java_cast<Map_Entry>(it.next()); String key = java_cast<String>(entry.getKey()); try { StoredValue * value = new StoredValue(java_cast<StoredValue>(entry.getValue())); SKStoredValue * sv = new SKStoredValue(value); /* cout << "\t\t key: " << key <<endl; cout << "\t\t StoredValue: " << sv->getValue() << endl; cout << "\t\t\t getStoredLength: " << sv->getStoredLength() << endl; cout << "\t\t\t getUncompressedLength: " << sv->getUncompressedLength() << endl; cout << "\t\t\t getVersion: " << sv->getVersion() << endl; cout << "\t\t\t getCreationTime: " << sv->getCreationTime() << endl; cout << "\t\t\t getCreatorIP: " << sv->getCreatorIP() << endl; cout << "\t\t\t getCreatorID: " << sv->getCreatorID() << endl; cout << "\t\t\t getUserData: " << sv->getUserData() << endl; cout << "\t\t\t getStorageType: " << sv->getStorageType() << endl; */ valueMap->insert(StrSVMap::value_type( key.toString(), sv ) ); } catch( Throwable &t ) { //throw SKClientException( &t, __FILE__, __LINE__ ); repackException(__FILE__, __LINE__ ); } valueMap->insert(StrSVMap::value_type(key.toString(), (SKStoredValue*) NULL)); } return valueMap; } SKMap<string,SKStoredValue * > * SKAsyncRetrieval::getLatestStoredValues(void) { return _getStoredValues(true); } SKMap<string,SKStoredValue * > * SKAsyncRetrieval::getStoredValues(void) { return _getStoredValues(false); } SKStoredValue * SKAsyncRetrieval::getStoredValue(string& key) { SKStoredValue *sv = NULL; try { AsyncRetrieval *pAsync = (AsyncRetrieval*)getPImpl(); StoredValue _sv = pAsync->getStoredValue( String(key) ); if (_sv.isNull()) { sv = NULL; } else { StoredValue *storedValue = new StoredValue(java_cast<StoredValue>(_sv)); sv = new SKStoredValue(storedValue); } } catch( Throwable &t ) { //throw SKClientException( &t, __FILE__, __LINE__ ); repackException(__FILE__, __LINE__ ); } return sv; } /* SKStoredValue * SKAsyncRetrieval::getStoredValue(string& key) { SKStoredValue * sv = NULL; try { AsyncRetrieval * pAsync = (AsyncRetrieval*)getPImpl(); StoredValue * storedValue = new StoredValue(java_cast<StoredValue>(pAsync->getStoredValue( String(key) ))); sv = new SKStoredValue(storedValue); } catch( Throwable &t ) { //throw SKClientException( &t, __FILE__, __LINE__ ); repackException(__FILE__, __LINE__ ); } return sv; } */
32.815287
112
0.663043
[ "object" ]
f3b1f5d3bebbea78a8d4c64a33c855d6d2fbc997
35,151
cpp
C++
Engine/Monkey/Demo/ImageGUIContext.cpp
zsb534923374/VulkanDemos
3bda2a8f29cfb69ffdb1bed5a53ffa1c4a2c1dc5
[ "MIT" ]
1
2019-10-12T15:07:38.000Z
2019-10-12T15:07:38.000Z
Engine/Monkey/Demo/ImageGUIContext.cpp
Guangehhhh/VulkanDemos
d3b9cc113aa3657689a0e7828892fb754f73361f
[ "MIT" ]
null
null
null
Engine/Monkey/Demo/ImageGUIContext.cpp
Guangehhhh/VulkanDemos
d3b9cc113aa3657689a0e7828892fb754f73361f
[ "MIT" ]
null
null
null
#include "Engine.h" #include "ImageGUIContext.h" #include "Demo/FileManager.h" #include "Application/GenericWindow.h" #include "Application/GenericApplication.h" static uint32_t g__glsl_shader_vert_spv[] = { 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015, 0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43, 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f, 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005, 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000, 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c, 0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074, 0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001, 0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b, 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015, 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047, 0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e, 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008, 0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002, 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017, 0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020, 0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015, 0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020, 0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020, 0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020, 0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020, 0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a, 0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014, 0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f, 0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021, 0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006, 0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, 0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012, 0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016, 0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018, 0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022, 0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008, 0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013, 0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024, 0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006, 0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b, 0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e, 0x0000002d,0x0000002c,0x000100fd,0x00010038 }; static uint32_t g__glsl_shader_frag_spv[] = { 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010, 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000, 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001, 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574, 0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e, 0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021, 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006, 0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003, 0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006, 0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001, 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020, 0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001, 0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000, 0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000, 0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018, 0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004, 0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d, 0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017, 0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a, 0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085, 0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd, 0x00010038 }; ImageGUIContext::ImageGUIContext() : m_VulkanDevice(nullptr) , m_VertexCount(0) , m_IndexCount(0) , m_Subpass(0) , m_DescriptorPool(VK_NULL_HANDLE) , m_DescriptorSetLayout(VK_NULL_HANDLE) , m_DescriptorSet(VK_NULL_HANDLE) , m_PipelineLayout(VK_NULL_HANDLE) , m_PipelineCache(VK_NULL_HANDLE) , m_Pipeline(VK_NULL_HANDLE) , m_LastRenderPass(VK_NULL_HANDLE) , m_FontMemory(VK_NULL_HANDLE) , m_FontImage(VK_NULL_HANDLE) , m_FontView(VK_NULL_HANDLE) , m_FontSampler(VK_NULL_HANDLE) , m_Visible(false) , m_Updated(false) , m_Scale(1.0f) , m_FontPath("") { } ImageGUIContext::~ImageGUIContext() { } void ImageGUIContext::Init(const std::string& font) { ImGui::CreateContext(); ImGui::StyleColorsLight(); float windowWidth = Engine::Get()->GetPlatformWindow()->GetWidth(); float windowHeight = Engine::Get()->GetPlatformWindow()->GetHeight(); float frameWidth = Engine::Get()->GetVulkanRHI()->GetSwapChain()->GetWidth(); float frameHeight = Engine::Get()->GetVulkanRHI()->GetSwapChain()->GetHeight(); m_Scale = frameWidth / windowWidth; m_FontPath = font; m_VulkanDevice = Engine::Get()->GetVulkanDevice(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)(windowWidth), (float)(windowHeight)); io.DisplayFramebufferScale = ImVec2(frameWidth / windowWidth, frameHeight / windowHeight); PrepareFontResources(); PreparePipelineResources(); } void ImageGUIContext::PreparePipeline(VkRenderPass renderPass, int32 subpass, VkSampleCountFlagBits sampleCount) { VkDevice device = m_VulkanDevice->GetInstanceHandle(); if (m_Pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, m_Pipeline, VULKAN_CPU_ALLOCATOR); m_Pipeline = VK_NULL_HANDLE; } VkPipelineInputAssemblyStateCreateInfo inputAssemblyState; ZeroVulkanStruct(inputAssemblyState, VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO); inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; VkPipelineRasterizationStateCreateInfo rasterizationState; ZeroVulkanStruct(rasterizationState, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO); rasterizationState.polygonMode = VK_POLYGON_MODE_FILL; rasterizationState.cullMode = VK_CULL_MODE_NONE; rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationState.lineWidth = 1.0f; VkPipelineColorBlendAttachmentState blendAttachmentState = {}; blendAttachmentState.blendEnable = VK_TRUE; blendAttachmentState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendStateCreateInfo colorBlendState; ZeroVulkanStruct(colorBlendState, VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO); colorBlendState.attachmentCount = 1; colorBlendState.pAttachments = &blendAttachmentState; VkPipelineDepthStencilStateCreateInfo depthStencilState; ZeroVulkanStruct(depthStencilState, VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO); VkPipelineViewportStateCreateInfo viewportState; ZeroVulkanStruct(viewportState, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO); viewportState.viewportCount = 1; viewportState.scissorCount = 1; VkPipelineMultisampleStateCreateInfo multisampleState; ZeroVulkanStruct(multisampleState, VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO); multisampleState.rasterizationSamples = sampleCount; std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState; ZeroVulkanStruct(dynamicState, VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO); dynamicState.pDynamicStates = dynamicStateEnables.data(); dynamicState.dynamicStateCount = 2; VkShaderModule vertModule = VK_NULL_HANDLE; VkShaderModule fragModule = VK_NULL_HANDLE; VkShaderModuleCreateInfo moduleCreateInfo; ZeroVulkanStruct(moduleCreateInfo, VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); moduleCreateInfo.codeSize = sizeof(g__glsl_shader_vert_spv); moduleCreateInfo.pCode = g__glsl_shader_vert_spv; VERIFYVULKANRESULT(vkCreateShaderModule(device, &moduleCreateInfo, VULKAN_CPU_ALLOCATOR, &vertModule)); moduleCreateInfo.codeSize = sizeof(g__glsl_shader_frag_spv); moduleCreateInfo.pCode = g__glsl_shader_frag_spv; VERIFYVULKANRESULT(vkCreateShaderModule(device, &moduleCreateInfo, VULKAN_CPU_ALLOCATOR, &fragModule)); VkPipelineShaderStageCreateInfo shaderStages[2] = {}; ZeroVulkanStruct(shaderStages[0], VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO); ZeroVulkanStruct(shaderStages[1], VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO); shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = vertModule; shaderStages[0].pName = "main"; shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = fragModule; shaderStages[1].pName = "main"; VkVertexInputBindingDescription vertexInputBinding = {}; vertexInputBinding.binding = 0; vertexInputBinding.stride = sizeof(ImDrawVert); vertexInputBinding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; VkVertexInputAttributeDescription vertexInputAttributes[3] = {}; vertexInputAttributes[0].location = 0; vertexInputAttributes[0].binding = 0; vertexInputAttributes[0].format = VK_FORMAT_R32G32_SFLOAT; vertexInputAttributes[0].offset = IM_OFFSETOF(ImDrawVert, pos); vertexInputAttributes[1].location = 1; vertexInputAttributes[1].binding = 0; vertexInputAttributes[1].format = VK_FORMAT_R32G32_SFLOAT; vertexInputAttributes[1].offset = IM_OFFSETOF(ImDrawVert, uv); vertexInputAttributes[2].location = 2; vertexInputAttributes[2].binding = 0; vertexInputAttributes[2].format = VK_FORMAT_R8G8B8A8_UNORM; vertexInputAttributes[2].offset = IM_OFFSETOF(ImDrawVert, col); VkPipelineVertexInputStateCreateInfo vertexInputState; ZeroVulkanStruct(vertexInputState, VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO); vertexInputState.vertexBindingDescriptionCount = 1; vertexInputState.pVertexBindingDescriptions = &vertexInputBinding; vertexInputState.vertexAttributeDescriptionCount = 3; vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes; VkGraphicsPipelineCreateInfo pipelineCreateInfo; ZeroVulkanStruct(pipelineCreateInfo, VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO); pipelineCreateInfo.flags = 0; pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pStages = shaderStages; pipelineCreateInfo.pVertexInputState = &vertexInputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.layout = m_PipelineLayout; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.subpass = subpass; VERIFYVULKANRESULT(vkCreateGraphicsPipelines(device, m_PipelineCache, 1, &pipelineCreateInfo, VULKAN_CPU_ALLOCATOR, &m_Pipeline)); vkDestroyShaderModule(device, vertModule, VULKAN_CPU_ALLOCATOR); vkDestroyShaderModule(device, fragModule, VULKAN_CPU_ALLOCATOR); m_LastRenderPass = renderPass; m_LastSubPass = subpass; } void ImageGUIContext::PreparePipelineResources() { VkDevice device = m_VulkanDevice->GetInstanceHandle(); VkPipelineCacheCreateInfo createInfo; ZeroVulkanStruct(createInfo, VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO); VERIFYVULKANRESULT(vkCreatePipelineCache(device, &createInfo, VULKAN_CPU_ALLOCATOR, &m_PipelineCache)); VkDescriptorPoolSize poolSize = {}; poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSize.descriptorCount = 1; VkDescriptorPoolCreateInfo descriptorPoolInfo; ZeroVulkanStruct(descriptorPoolInfo, VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO); descriptorPoolInfo.poolSizeCount = 1; descriptorPoolInfo.pPoolSizes = &poolSize; descriptorPoolInfo.maxSets = 2; VERIFYVULKANRESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, VULKAN_CPU_ALLOCATOR, &m_DescriptorPool)); VkDescriptorSetLayoutBinding setLayoutBinding = {}; setLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; setLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; setLayoutBinding.binding = 0; setLayoutBinding.descriptorCount = 1; setLayoutBinding.pImmutableSamplers = &m_FontSampler; VkDescriptorSetLayoutCreateInfo setLayoutCreateInfo; ZeroVulkanStruct(setLayoutCreateInfo, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO); setLayoutCreateInfo.bindingCount = 1; setLayoutCreateInfo.pBindings = &setLayoutBinding; VERIFYVULKANRESULT(vkCreateDescriptorSetLayout(device, &setLayoutCreateInfo, VULKAN_CPU_ALLOCATOR, &m_DescriptorSetLayout)); VkPushConstantRange pushConstantRange = {}; pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; pushConstantRange.offset = 0; pushConstantRange.size = sizeof(PushConstBlock); VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo; ZeroVulkanStruct(pipelineLayoutCreateInfo, VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO); pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &m_DescriptorSetLayout; pipelineLayoutCreateInfo.pushConstantRangeCount = 1; pipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange; VERIFYVULKANRESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, VULKAN_CPU_ALLOCATOR, &m_PipelineLayout)); VkDescriptorSetAllocateInfo setAllocateInfo; ZeroVulkanStruct(setAllocateInfo, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO); setAllocateInfo.descriptorPool = m_DescriptorPool; setAllocateInfo.descriptorSetCount = 1; setAllocateInfo.pSetLayouts = &m_DescriptorSetLayout; VERIFYVULKANRESULT(vkAllocateDescriptorSets(device, &setAllocateInfo, &m_DescriptorSet)); VkDescriptorImageInfo fontDescriptor = {}; fontDescriptor.sampler = m_FontSampler; fontDescriptor.imageView = m_FontView; fontDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkWriteDescriptorSet writeDescriptorSet; ZeroVulkanStruct(writeDescriptorSet, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET); writeDescriptorSet.dstSet = m_DescriptorSet; writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptorSet.dstBinding = 0; writeDescriptorSet.pImageInfo = &fontDescriptor; writeDescriptorSet.descriptorCount = 1; vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); } void ImageGUIContext::Destroy() { VkDevice device = m_VulkanDevice->GetInstanceHandle(); ImGui::DestroyContext(); m_VertexBuffer.Destroy(); m_IndexBuffer.Destroy(); vkDestroyDescriptorPool(device, m_DescriptorPool, VULKAN_CPU_ALLOCATOR); vkDestroyDescriptorSetLayout(device, m_DescriptorSetLayout, VULKAN_CPU_ALLOCATOR); vkDestroyPipelineLayout(device, m_PipelineLayout, VULKAN_CPU_ALLOCATOR); vkDestroyPipeline(device, m_Pipeline, VULKAN_CPU_ALLOCATOR); vkDestroyPipelineCache(device, m_PipelineCache, VULKAN_CPU_ALLOCATOR); vkFreeMemory(device, m_FontMemory, VULKAN_CPU_ALLOCATOR); vkDestroyImage(device, m_FontImage, VULKAN_CPU_ALLOCATOR); vkDestroyImageView(device, m_FontView, VULKAN_CPU_ALLOCATOR); vkDestroySampler(device, m_FontSampler, VULKAN_CPU_ALLOCATOR); } void ImageGUIContext::PrepareFontResources() { VkDevice device = m_VulkanDevice->GetInstanceHandle(); // font io ImGuiIO& io = ImGui::GetIO(); io.FontGlobalScale = m_Scale; // load font file uint8* dataPtr = nullptr; uint32 dataSize = 0; FileManager::ReadFile(m_FontPath, dataPtr, dataSize); io.Fonts->AddFontFromMemoryTTF(dataPtr, dataSize, 16.0f); // get font image data uint8* fontData = nullptr; int32 texWidth = 0; int32 texHeight = 0; io.Fonts->GetTexDataAsRGBA32(&fontData, &texWidth, &texHeight); VkDeviceSize uploadSize = texWidth * texHeight * 4 * sizeof(uint8); // mem alloc info uint32 memoryTypeIndex = 0; VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAllocInfo; ZeroVulkanStruct(memAllocInfo, VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO); // font image { VkImageCreateInfo imageCreateInfo; ZeroVulkanStruct(imageCreateInfo, VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO); imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; imageCreateInfo.extent.width = texWidth; imageCreateInfo.extent.height = texHeight; imageCreateInfo.extent.depth = 1; imageCreateInfo.mipLevels = 1; imageCreateInfo.arrayLayers = 1; imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VERIFYVULKANRESULT(vkCreateImage(device, &imageCreateInfo, VULKAN_CPU_ALLOCATOR, &m_FontImage)); } // font memory { vkGetImageMemoryRequirements(device, m_FontImage, &memReqs); m_VulkanDevice->GetMemoryManager().GetMemoryTypeFromProperties(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memoryTypeIndex); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = memoryTypeIndex; VERIFYVULKANRESULT(vkAllocateMemory(device, &memAllocInfo, VULKAN_CPU_ALLOCATOR, &m_FontMemory)); } // bind memory to image VERIFYVULKANRESULT(vkBindImageMemory(device, m_FontImage, m_FontMemory, 0)); // view info { VkImageViewCreateInfo viewCreateInfo; ZeroVulkanStruct(viewCreateInfo, VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO); viewCreateInfo.image = m_FontImage; viewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; viewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; viewCreateInfo.subresourceRange.levelCount = 1; viewCreateInfo.subresourceRange.layerCount = 1; VERIFYVULKANRESULT(vkCreateImageView(device, &viewCreateInfo, VULKAN_CPU_ALLOCATOR, &m_FontView)); } // sampler info { VkSamplerCreateInfo samplerInfo; ZeroVulkanStruct(samplerInfo, VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO); samplerInfo.maxAnisotropy = 1.0f; samplerInfo.minLod = -1000; samplerInfo.maxLod = 1000; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VERIFYVULKANRESULT(vkCreateSampler(device, &samplerInfo, VULKAN_CPU_ALLOCATOR, &m_FontSampler)); } // staging info VkBuffer stagingBuffer = VK_NULL_HANDLE; VkDeviceMemory stagingMemory = VK_NULL_HANDLE; // staging buffer { VkBufferCreateInfo bufferCreateInfo; ZeroVulkanStruct(bufferCreateInfo, VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO); bufferCreateInfo.size = uploadSize; bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VERIFYVULKANRESULT(vkCreateBuffer(device, &bufferCreateInfo, VULKAN_CPU_ALLOCATOR, &stagingBuffer)); } // staging memory { vkGetBufferMemoryRequirements(device, stagingBuffer, &memReqs); m_VulkanDevice->GetMemoryManager().GetMemoryTypeFromProperties(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memoryTypeIndex); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = memoryTypeIndex; VERIFYVULKANRESULT(vkAllocateMemory(device, &memAllocInfo, VULKAN_CPU_ALLOCATOR, &stagingMemory)); } // bind staging buffer to memory VERIFYVULKANRESULT(vkBindBufferMemory(device, stagingBuffer, stagingMemory, 0)); // copy data to staging memory { VkMappedMemoryRange flushRange; ZeroVulkanStruct(flushRange, VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE); flushRange.memory = stagingMemory; flushRange.size = uploadSize; void* mappedPtr = nullptr; VERIFYVULKANRESULT(vkMapMemory(device, stagingMemory, 0, uploadSize, 0, &mappedPtr)); std::memcpy(mappedPtr, fontData, uploadSize); vkFlushMappedMemoryRanges(device, 1, &flushRange); vkUnmapMemory(device, stagingMemory); } // prepare command VkCommandPool commandPool = VK_NULL_HANDLE; VkCommandBuffer cmdBuffer = VK_NULL_HANDLE; // command pool { VkCommandPoolCreateInfo cmdPoolInfo; ZeroVulkanStruct(cmdPoolInfo, VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO); cmdPoolInfo.queueFamilyIndex = m_VulkanDevice->GetTransferQueue()->GetFamilyIndex(); cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; VERIFYVULKANRESULT(vkCreateCommandPool(device, &cmdPoolInfo, VULKAN_CPU_ALLOCATOR, &commandPool)); } // command buffer { VkCommandBufferAllocateInfo cmdCreateInfo; ZeroVulkanStruct(cmdCreateInfo, VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO); cmdCreateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cmdCreateInfo.commandPool = commandPool; cmdCreateInfo.commandBufferCount = 1; VERIFYVULKANRESULT(vkAllocateCommandBuffers(device, &cmdCreateInfo, &cmdBuffer)); } // begin record { VkCommandBufferBeginInfo cmdBeginInfo; ZeroVulkanStruct(cmdBeginInfo, VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); VERIFYVULKANRESULT(vkBeginCommandBuffer(cmdBuffer, &cmdBeginInfo)); } { VkImageMemoryBarrier imageMemoryBarrier; ZeroVulkanStruct(imageMemoryBarrier, VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER); imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemoryBarrier.srcAccessMask = 0; imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; imageMemoryBarrier.image = m_FontImage; imageMemoryBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageMemoryBarrier.subresourceRange.levelCount = 1; imageMemoryBarrier.subresourceRange.layerCount = 1; vkCmdPipelineBarrier( cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier ); } // copy buffer to image { VkBufferImageCopy bufferCopyRegion = {}; bufferCopyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; bufferCopyRegion.imageSubresource.layerCount = 1; bufferCopyRegion.imageExtent.width = texWidth; bufferCopyRegion.imageExtent.height = texHeight; bufferCopyRegion.imageExtent.depth = 1; vkCmdCopyBufferToImage( cmdBuffer, stagingBuffer, m_FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bufferCopyRegion ); } // image barrier for shader read { VkImageMemoryBarrier imageMemoryBarrier; ZeroVulkanStruct(imageMemoryBarrier, VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER); imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageMemoryBarrier.image = m_FontImage; imageMemoryBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageMemoryBarrier.subresourceRange.levelCount = 1; imageMemoryBarrier.subresourceRange.layerCount = 1; vkCmdPipelineBarrier( cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier ); } { VERIFYVULKANRESULT(vkEndCommandBuffer(cmdBuffer)); } VkSubmitInfo submitInfo; ZeroVulkanStruct(submitInfo, VK_STRUCTURE_TYPE_SUBMIT_INFO); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &cmdBuffer; VkFence fence = VK_NULL_HANDLE; { VkFenceCreateInfo fenceCreateInfo; ZeroVulkanStruct(fenceCreateInfo, VK_STRUCTURE_TYPE_FENCE_CREATE_INFO); fenceCreateInfo.flags = 0; VERIFYVULKANRESULT(vkCreateFence(device, &fenceCreateInfo, VULKAN_CPU_ALLOCATOR, &fence)); } VERIFYVULKANRESULT(vkQueueSubmit(m_VulkanDevice->GetTransferQueue()->GetHandle(), 1, &submitInfo, fence)); VERIFYVULKANRESULT(vkWaitForFences(device, 1, &fence, VK_TRUE, MAX_uint64)); vkFreeCommandBuffers(device, commandPool, 1, &cmdBuffer); vkDestroyFence(device, fence, VULKAN_CPU_ALLOCATOR); vkDestroyCommandPool(device, commandPool, VULKAN_CPU_ALLOCATOR); vkDestroyBuffer(device, stagingBuffer, VULKAN_CPU_ALLOCATOR); vkFreeMemory(device, stagingMemory, VULKAN_CPU_ALLOCATOR); } void ImageGUIContext::Resize(uint32 width, uint32 height) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)(width), (float)(height)); } void ImageGUIContext::StartFrame() { const Vector2& mousePos = InputManager::GetMousePosition(); ImGuiIO& io = ImGui::GetIO(); io.MouseWheel += InputManager::GetMouseDelta(); io.MousePos = ImVec2(mousePos.x * io.DisplayFramebufferScale.x, mousePos.y * io.DisplayFramebufferScale.y); io.MouseDown[0] = InputManager::IsMouseDown(MouseType::MOUSE_BUTTON_LEFT); io.MouseDown[1] = InputManager::IsMouseDown(MouseType::MOUSE_BUTTON_RIGHT); io.MouseDown[2] = InputManager::IsMouseDown(MouseType::MOUSE_BUTTON_MIDDLE); io.KeyCtrl = InputManager::IsKeyDown(KeyboardType::KEY_LEFT_CONTROL) || InputManager::IsKeyDown(KeyboardType::KEY_RIGHT_CONTROL); io.KeyShift = InputManager::IsKeyDown(KeyboardType::KEY_LEFT_SHIFT) || InputManager::IsKeyDown(KeyboardType::KEY_RIGHT_SHIFT); io.KeyAlt = InputManager::IsKeyDown(KeyboardType::KEY_LEFT_ALT) || InputManager::IsKeyDown(KeyboardType::KEY_RIGHT_ALT); io.KeySuper = false; ImGui::NewFrame(); } void ImageGUIContext::EndFrame() { ImGui::Render(); } bool ImageGUIContext::Update() { ImDrawData* imDrawData = ImGui::GetDrawData(); bool updateCmdBuffers = false; if (!imDrawData) { return false; }; // Note: Alignment is done inside buffer creation VkDeviceSize vertexBufferSize = imDrawData->TotalVtxCount * sizeof(ImDrawVert); VkDeviceSize indexBufferSize = imDrawData->TotalIdxCount * sizeof(ImDrawIdx); // Update buffers only if vertex or index count has been changed compared to current buffer size if ((vertexBufferSize == 0) || (indexBufferSize == 0)) { return false; } // Vertex buffer if ((m_VertexBuffer.buffer == VK_NULL_HANDLE) || (m_VertexCount != imDrawData->TotalVtxCount)) { m_VertexCount = imDrawData->TotalVtxCount; m_VertexBuffer.Unmap(); m_VertexBuffer.Destroy(); CreateBuffer(m_VertexBuffer, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, vertexBufferSize); m_VertexBuffer.Map(); updateCmdBuffers = true; } // Index buffer if ((m_IndexBuffer.buffer == VK_NULL_HANDLE) || (m_IndexCount < imDrawData->TotalIdxCount)) { m_IndexCount = imDrawData->TotalIdxCount; m_IndexBuffer.Unmap(); m_IndexBuffer.Destroy(); CreateBuffer(m_IndexBuffer, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, indexBufferSize); m_IndexBuffer.Map(); updateCmdBuffers = true; } // Upload data ImDrawVert* vtxDst = (ImDrawVert*)m_VertexBuffer.mapped; ImDrawIdx* idxDst = (ImDrawIdx*)m_IndexBuffer.mapped; for (int n = 0; n < imDrawData->CmdListsCount; n++) { const ImDrawList* cmdList = imDrawData->CmdLists[n]; memcpy(vtxDst, cmdList->VtxBuffer.Data, cmdList->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idxDst, cmdList->IdxBuffer.Data, cmdList->IdxBuffer.Size * sizeof(ImDrawIdx)); vtxDst += cmdList->VtxBuffer.Size; idxDst += cmdList->IdxBuffer.Size; } m_VertexBuffer.Flush(); m_IndexBuffer.Flush(); return updateCmdBuffers || m_Updated; } void ImageGUIContext::CreateBuffer(UIBuffer& buffer, VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size) { VkDevice device = m_VulkanDevice->GetInstanceHandle(); VkBufferCreateInfo bufferCreateInfo; ZeroVulkanStruct(bufferCreateInfo, VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO); bufferCreateInfo.size = size; bufferCreateInfo.usage = usageFlags; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VERIFYVULKANRESULT(vkCreateBuffer(device, &bufferCreateInfo, VULKAN_CPU_ALLOCATOR, &buffer.buffer)); uint32 memoryTypeIndex = 0; VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAllocInfo; ZeroVulkanStruct(memAllocInfo, VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO); vkGetBufferMemoryRequirements(device, buffer.buffer, &memReqs); m_VulkanDevice->GetMemoryManager().GetMemoryTypeFromProperties(memReqs.memoryTypeBits, memoryPropertyFlags, &memoryTypeIndex); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = memoryTypeIndex; VERIFYVULKANRESULT(vkAllocateMemory(device, &memAllocInfo, VULKAN_CPU_ALLOCATOR, &buffer.memory)); VERIFYVULKANRESULT(vkBindBufferMemory(device, buffer.buffer, buffer.memory, 0)); buffer.device = device; buffer.size = memAllocInfo.allocationSize; buffer.alignment = memReqs.alignment; } void ImageGUIContext::BindDrawCmd(const VkCommandBuffer& commandBuffer, const VkRenderPass& renderPass, int32 subpass, VkSampleCountFlagBits sampleCount) { ImDrawData* imDrawData = ImGui::GetDrawData(); int32_t vertexOffset = 0; int32_t indexOffset = 0; if ((!imDrawData) || (imDrawData->CmdListsCount == 0)) { return; } VkDeviceSize vertexBufferSize = imDrawData->TotalVtxCount * sizeof(ImDrawVert); VkDeviceSize indexBufferSize = imDrawData->TotalIdxCount * sizeof(ImDrawIdx); if (vertexBufferSize == 0 || indexBufferSize == 0) { return; } if (m_LastRenderPass != renderPass || m_LastSubPass != subpass || m_LastSampleCount != sampleCount) { PreparePipeline(renderPass, subpass, sampleCount); } ImGuiIO& io = ImGui::GetIO(); VkDeviceSize offsets[1] = { 0 }; ImVec2 displayPos = imDrawData->DisplayPos; VkViewport viewport = {}; viewport.x = 0; viewport.y = 0; viewport.width = imDrawData->DisplaySize.x; viewport.height = imDrawData->DisplaySize.y; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; m_PushData.scale.x = 2 / io.DisplaySize.x; m_PushData.scale.y = 2 / io.DisplaySize.y; m_PushData.translate.x = -1.0f - displayPos.x * m_PushData.scale.x; m_PushData.translate.y = -1.0f - displayPos.y * m_PushData.scale.y; vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_Pipeline); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_PipelineLayout, 0, 1, &m_DescriptorSet, 0, nullptr); vkCmdPushConstants(commandBuffer, m_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(PushConstBlock), &m_PushData); vkCmdBindVertexBuffers(commandBuffer, 0, 1, &m_VertexBuffer.buffer, offsets); vkCmdBindIndexBuffer(commandBuffer, m_IndexBuffer.buffer, 0, VK_INDEX_TYPE_UINT16); for (int32_t i = 0; i < imDrawData->CmdListsCount; ++i) { const ImDrawList* cmdList = imDrawData->CmdLists[i]; for (int32_t j = 0; j < cmdList->CmdBuffer.Size; ++j) { const ImDrawCmd* pcmd = &cmdList->CmdBuffer[j]; if (pcmd->UserCallback) { pcmd->UserCallback(cmdList, pcmd); } else { VkRect2D scissorRect = {}; scissorRect.offset.x = (int32_t)(pcmd->ClipRect.x - displayPos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - displayPos.x) : 0; scissorRect.offset.y = (int32_t)(pcmd->ClipRect.y - displayPos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - displayPos.y) : 0; scissorRect.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x); scissorRect.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y); vkCmdSetScissor(commandBuffer, 0, 1, &scissorRect); vkCmdDrawIndexed(commandBuffer, pcmd->ElemCount, 1, indexOffset, vertexOffset, 0); } indexOffset += pcmd->ElemCount; } vertexOffset += cmdList->VtxBuffer.Size; } m_Updated = false; }
44.438685
153
0.808256
[ "render", "vector" ]
f3bd95e4b9a0230c5657f57d80a2db2334131a69
2,702
cpp
C++
euler017.cpp
Toxe/Project-Euler
b91cba62911a06341dd0c39584d9c6f3f3f88091
[ "MIT" ]
null
null
null
euler017.cpp
Toxe/Project-Euler
b91cba62911a06341dd0c39584d9c6f3f3f88091
[ "MIT" ]
null
null
null
euler017.cpp
Toxe/Project-Euler
b91cba62911a06341dd0c39584d9c6f3f3f88091
[ "MIT" ]
null
null
null
// Number letter counts #include <iostream> #include <string> #include <vector> const std::vector<std::string> num_tens{"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; const std::vector<std::string> num_one_to_nineteen{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thriteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; std::string tens(int n) { std::string s{num_tens[static_cast<std::string::size_type>((n / 10) - 2)]}; if (n % 10 > 0) s += " "; return s; } std::string one_to_nineteen(int n) { return num_one_to_nineteen[static_cast<std::string::size_type>(n - 1)]; } std::string hundreds(int n) { std::string s{one_to_nineteen(n / 100) + " " + "hundred"}; if (n % 100 > 0) s += " and "; return s; } std::string write(int n) { std::string s; if (n == 1000) return "one thousand"; if (n >= 100) { s += hundreds(n); n = n % 100; } if (n >= 20) { s += tens(n); n -= 10 * (n / 10); } if (n >= 1 && n <= 19) s += one_to_nineteen(n); return s; } int euler017() { int sum = 0; for (int i = 1; i <= 1000; ++i) { std::string s{write(i)}; sum += static_cast<int>(s.size() - static_cast<std::string::size_type>(std::count(s.begin(), s.end(), ' '))); } return sum; } int main() { std::cout << euler017() << std::endl; }
27.02
117
0.296447
[ "vector" ]
f3bea8748d4230a2456a2b22d7bfbd1c9216fcb5
6,892
cpp
C++
applications/fm-index/src/align.cpp
custom-computing-ic/dfe-snippets
8721e6272c25f77360e2de423d8ff5a9299ee5b2
[ "MIT" ]
17
2015-02-02T13:23:49.000Z
2021-02-09T11:04:40.000Z
applications/fm-index/src/align.cpp
custom-computing-ic/dfe-snippets
8721e6272c25f77360e2de423d8ff5a9299ee5b2
[ "MIT" ]
14
2015-07-02T10:13:05.000Z
2017-05-30T15:59:43.000Z
applications/fm-index/src/align.cpp
custom-computing-ic/dfe-snippets
8721e6272c25f77360e2de423d8ff5a9299ee5b2
[ "MIT" ]
8
2015-04-08T13:27:50.000Z
2016-12-16T14:38:52.000Z
/* align.cpp ----- James Arram 2014 */ /* * align source code file */ #include "align.hpp" // kernel input struct in_t { uint32_t id; uint8_t pck_sym[42]; uint8_t len; uint8_t is_pad; }; // kernel output struct out_t { uint32_t id; uint32_t low; uint32_t high; uint32_t pad; }; using namespace std; // exact match kernel latency uint32_t latency = 200; // get partition sizes void getPartSize(uint32_t *part_size, uint32_t items); // kernel write action void actionWrite(index_t *index, uint64_t index_bytes, max_engine_t **engine); // kernel align action void actionAlign(in_t **in, out_t **out, uint32_t *part_size, uint32_t high_init, max_engine_t **engine); //align reads void align(vector<read_t> &reads, index_t *index, uint64_t index_bytes, uint32_t high_init) { in_t *in[N_KRNL*N_DFE]; out_t *out[N_KRNL*N_DFE]; uint32_t part_size[N_KRNL*N_DFE]; max_file_t *maxfile = NULL; max_engine_t *engine[N_DFE]; max_group_t *group = NULL; struct timeval tv1, tv2; // load exact match kernel bitstream printf("\tloading exact match kernel bitstream ... "); fflush(stdout); gettimeofday(&tv1, NULL); maxfile = Em_init(); group = max_load_group(maxfile, MAXOS_EXCLUSIVE, "*", N_DFE); for (uint8_t i = 0; i < N_DFE; i++) engine[i] = max_lock_any(group); gettimeofday(&tv2, NULL); printf("OK [%.2f s]\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); // write index to DRAM memory printf("\ttransferring index to DRAM ... "); fflush(stdout); gettimeofday(&tv1, NULL); actionWrite(index, index_bytes, engine); gettimeofday(&tv2, NULL); printf("OK [%.2f s]\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); // generate kernel input getPartSize(part_size, reads.size()); uint32_t offset = 0; for (uint8_t i = 0; i < N_KRNL*N_DFE; i++) { in[i] = new in_t [part_size[i]+latency]; if (!in[i]) { printf("error: unable to allocate memory!\n"); exit(1); } memset(in[i], 0, part_size[i]+latency*sizeof(in_t)); #pragma omp parallel for num_threads(N_THREADS) for (uint32_t j = 0; j < part_size[i]; j++) { uint32_t id = j+offset; in[i][j].id = id; in[i][j].len = reads[id].len; memcpy(in[i][j].pck_sym, reads[id].pck_sym, CEIL(reads[id].len, 4)); in[i][j].is_pad = 0; } for (uint8_t j = 0; j < latency; j++) { if (j < latency - 1) in[i][part_size[i]+j].is_pad = 1; else in[i][part_size[i]+j].is_pad = 2; } offset += part_size[i]; } // exact align reads printf("\texact aligning reads ... "); fflush(stdout); gettimeofday(&tv1, NULL); for (uint8_t i = 0; i < N_KRNL*N_DFE; i++){ out[i] = new out_t [part_size[i]]; if (!out[i]) { printf("error: unable to allocate memory!\n"); exit(1); } memset(out[i], 0, part_size[i]*sizeof(out_t)); } actionAlign(in, out, part_size, high_init, engine); gettimeofday(&tv2, NULL); printf("OK [%.2f s]\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); // parse output printf("\tparsing results ... "); fflush(stdout); gettimeofday(&tv1, NULL); for (uint8_t i = 0; i < N_KRNL*N_DFE; i++) { #pragma omp parallel for num_threads(N_THREADS) for (uint32_t j = 0; j < part_size[i]; j++) { uint32_t id = out[i][j].id; if (out[i][j].low <= out[i][j].high) { reads[id].low = out[i][j].low; reads[id].high = out[i][j].high; reads[id].is_align = true; } } } gettimeofday(&tv2, NULL); printf("OK [%.2f s]\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); // cleanup for (int i = 0; i < N_DFE; i++) max_unlock(engine[i]); max_unload_group(group); max_file_free(maxfile); for (int i = 0; i < N_KRNL*N_DFE; i++) { delete[] in[i]; delete[] out[i]; } } // get partition size void getPartSize(uint32_t *part_size, uint32_t items) { for (uint8_t i = 0; i < N_KRNL*N_DFE; i++) { if (items%(N_KRNL*N_DFE)!=0) { part_size[i] = CEIL(items, N_KRNL*N_DFE); items-=1; } else part_size[i] = items/(N_KRNL*N_DFE); } } // kernel write action void actionWrite(index_t *index, uint64_t index_bytes, max_engine_t **engine) { Em_Write_actions_t *em_write[N_DFE]; for (size_t i = 0; i < T_SIZE; i++) { for (int j = 0; j < N_DFE; j++) { em_write[j] = new Em_Write_actions_t; em_write[j]->param_nBytes = index_bytes/T_SIZE; em_write[j]->param_offset = i*(index_bytes/T_SIZE); em_write[j]->instream_indexToMger = (uint64_t*)&index[i*(index_bytes/T_SIZE/BURST_BYTES)]; } #pragma omp parallel for num_threads(N_DFE) for (int j = 0; j < N_DFE; j++) { Em_Write_run(engine[j], em_write[j]); delete em_write[j]; } } } // kernel align action void actionAlign(in_t **in, out_t **out, uint32_t *part_size, uint32_t high_init, max_engine_t **engine) { uint64_t n_bytes_in[N_KRNL*N_DFE]; uint64_t n_bytes_out[N_KRNL*N_DFE]; for (uint8_t i = 0; i < N_KRNL*N_DFE; i++) { n_bytes_in[i] = (part_size[i]+latency)*sizeof(in_t); n_bytes_out[i] = part_size[i]*sizeof(out_t); } Em_Align_actions_t *em_align[N_DFE]; for (uint8_t i = 0; i < N_DFE; i++) { em_align[i] = new Em_Align_actions_t; em_align[i]->param_offset = latency; em_align[i]->param_highInit = high_init; em_align[i]->param_nBytesInput = &n_bytes_in[i*N_KRNL]; em_align[i]->param_nBytesOutput = &n_bytes_out[i*N_KRNL]; #if N_KRNL > 0 em_align[i]->instream_readIn0 = (uint64_t*)in[i*N_KRNL]; em_align[i]->outstream_alignOut0 = (uint64_t*)out[i*N_KRNL]; #endif #if N_KRNL > 1 em_align[i]->instream_readIn1 = (uint64_t*)in[(i*N_KRNL)+1]; em_align[i]->outstream_alignOut1 = (uint64_t*)out[(i*N_KRNL)+1]; #endif #if N_KRNL > 2 em_align[i]->instream_readIn2 = (uint64_t*)in[(i*N_KRNL)+2]; em_align[i]->outstream_alignOut2 = (uint64_t*)out[(i*N_KRNL)+2]; #endif #if N_KRNL > 3 em_align[i]->instream_readIn3 = (uint64_t*)in[(i*N_KRNL)+3]; em_align[i]->outstream_alignOut3 = (uint64_t*)out[(i*N_KRNL)+3]; #endif #if N_KRNL > 4 em_align[i]->instream_readIn4 = (uint64_t*)in[(i*N_KRNL)+4]; em_align[i]->outstream_alignOut4 = (uint64_t*)out[(i*N_KRNL)+4]; #endif #if N_KRNL > 5 em_align[i]->instream_readIn5 = (uint64_t*)in[(i*N_KRNL)+5]; em_align[i]->outstream_alignOut5 = (uint64_t*)out[(i*N_KRNL)+5]; #endif } #pragma omp parallel for num_threads(N_DFE) for (uint32_t i = 0; i < N_DFE; i++) { Em_Align_run(engine[i], em_align[i]); delete em_align[i]; } }
29.965217
82
0.615061
[ "vector" ]
f3c00a76410b4f8e911694926ffcb21d66d712fc
2,505
cxx
C++
sprokit/src/bindings/python/sprokit/pipeline_util/export.cxx
aaron-bray/kwiver
be55ec5a511ba5b9f2af94b268ac5f9a657accc4
[ "BSD-3-Clause" ]
null
null
null
sprokit/src/bindings/python/sprokit/pipeline_util/export.cxx
aaron-bray/kwiver
be55ec5a511ba5b9f2af94b268ac5f9a657accc4
[ "BSD-3-Clause" ]
null
null
null
sprokit/src/bindings/python/sprokit/pipeline_util/export.cxx
aaron-bray/kwiver
be55ec5a511ba5b9f2af94b268ac5f9a657accc4
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2011-2012 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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 <sprokit/pipeline/pipeline.h> #include <sprokit/pipeline_util/export_dot.h> #include <sprokit/pipeline_util/export_dot_exception.h> #include <sprokit/python/util/pystream.h> #include <sprokit/python/util/python_gil.h> #include <pybind11/pybind11.h> #include <string> /** * \file export.cxx * * \brief Python bindings for exporting functions. */ using namespace pybind11; void export_dot(object const& stream, sprokit::pipeline_t const pipe, std::string const& graph_name); PYBIND11_MODULE(export_, m) { m.def("export_dot", &export_dot , arg("stream"), arg("pipeline"), arg("name") , "Writes the pipeline to the stream in dot format."); } void export_dot(object const& stream, sprokit::pipeline_t const pipe, std::string const& graph_name) { sprokit::python::python_gil const gil; (void)gil; sprokit::python::pyostream ostr(stream); return sprokit::export_dot(ostr, pipe, graph_name); }
35.28169
101
0.751697
[ "object" ]
f3c86078f3b0d8d1873965d01801039e924daf41
1,952
hpp
C++
scene/hittables/hittable_list.hpp
loochek/armasa-path-tracer
307f57f10d54e418b1048b462425133531800e9c
[ "MIT" ]
1
2021-10-06T11:00:58.000Z
2021-10-06T11:00:58.000Z
scene/hittables/hittable_list.hpp
loochek/armasa-path-tracer
307f57f10d54e418b1048b462425133531800e9c
[ "MIT" ]
1
2021-10-11T10:29:26.000Z
2021-10-11T10:29:26.000Z
scene/hittables/hittable_list.hpp
JakMobius/armasa-path-tracer
b57dda3863b51135fc3de91393ecc42fd756081c
[ "MIT" ]
null
null
null
#pragma once class HittableList; struct BVHNode; #include <vector> #include "hittable.hpp" #include "../scene_renderer.hpp" #include "../buffer_chunk.hpp" extern const int HittableListType; class HittableList : public Hittable { std::vector<Hittable*> children; public: HittableList(): children() { set_index_buffer_stride(12); } void add_children(Hittable* hittable) { children.push_back(hittable); // Two fields + children indices set_index_buffer_stride(12 + children.size()); }; void register_hittables(SceneRenderer* renderer) override { for(auto child : children) renderer->enqueue_hittable_render(child); } void register_materials(SceneRenderer* renderer) override { for(auto child : children) child->register_materials(renderer); } void render(SceneRenderer* renderer, BufferChunk* chunk) override { int children_count = (int)children.size(); chunk->write_index(HittableListType | (children_count << 3)); for(int i = 0; i < children_count; i++) { int children_index = renderer->get_hittable_index(children[i]); chunk->write_index(children_index); } AABB aabb = get_bounding_box(); chunk->align(); chunk->write_vector(aabb.lower); chunk->write_vector(aabb.upper); } void update_aabb() override { if(children.empty()) { bounding_box.lower = {0, 0, 0}; bounding_box.upper = {0, 0, 0}; } else { bounding_box = children[0]->get_bounding_box(); for(int i = 1; i < (int)children.size(); i++) { bounding_box.extend(children[i]->get_bounding_box()); } } } void flatten(std::vector<Hittable*>* storage) override { for(auto child : children) child->flatten(storage); } std::vector<Hittable*>& get_children() { return children; } };
28.289855
76
0.624488
[ "render", "vector" ]
f3cbbf9262d0a8e04f92ceec981050096ecc08c0
3,780
cpp
C++
libraries/shared/src/Profile.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
libraries/shared/src/Profile.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
libraries/shared/src/Profile.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
// // Created by Ryan Huffman on 2016-12-14 // Copyright 2013-2016 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Profile.h" Q_LOGGING_CATEGORY(trace_app, "trace.app") Q_LOGGING_CATEGORY(trace_app_detail, "trace.app.detail") Q_LOGGING_CATEGORY(trace_metadata, "trace.metadata") Q_LOGGING_CATEGORY(trace_network, "trace.network") Q_LOGGING_CATEGORY(trace_parse, "trace.parse") Q_LOGGING_CATEGORY(trace_render, "trace.render") Q_LOGGING_CATEGORY(trace_render_detail, "trace.render.detail") Q_LOGGING_CATEGORY(trace_render_gpu, "trace.render.gpu") Q_LOGGING_CATEGORY(trace_resource, "trace.resource") Q_LOGGING_CATEGORY(trace_resource_network, "trace.resource.network") Q_LOGGING_CATEGORY(trace_resource_parse, "trace.resource.parse") Q_LOGGING_CATEGORY(trace_script, "trace.script") Q_LOGGING_CATEGORY(trace_script_entities, "trace.script.entities") Q_LOGGING_CATEGORY(trace_simulation, "trace.simulation") Q_LOGGING_CATEGORY(trace_simulation_detail, "trace.simulation.detail") Q_LOGGING_CATEGORY(trace_simulation_animation, "trace.simulation.animation") Q_LOGGING_CATEGORY(trace_simulation_animation_detail, "trace.simulation.animation.detail") Q_LOGGING_CATEGORY(trace_simulation_physics, "trace.simulation.physics") Q_LOGGING_CATEGORY(trace_simulation_physics_detail, "trace.simulation.physics.detail") Q_LOGGING_CATEGORY(trace_startup, "trace.startup") Q_LOGGING_CATEGORY(trace_workload, "trace.workload") #if defined(NSIGHT_FOUND) #include "nvToolsExt.h" #define NSIGHT_TRACING #endif static bool tracingEnabled() { return DependencyManager::isSet<tracing::Tracer>() && DependencyManager::get<tracing::Tracer>()->isEnabled(); } Duration::Duration(const QLoggingCategory& category, const QString& name, uint32_t argbColor, uint64_t payload, const QVariantMap& baseArgs) : _name(name), _category(category) { if (tracingEnabled() && category.isDebugEnabled()) { QVariantMap args = baseArgs; args["nv_payload"] = QVariant::fromValue(payload); tracing::traceEvent(_category, _name, tracing::DurationBegin, "", args); #if defined(NSIGHT_TRACING) nvtxEventAttributes_t eventAttrib { 0 }; eventAttrib.version = NVTX_VERSION; eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; eventAttrib.colorType = NVTX_COLOR_ARGB; eventAttrib.color = argbColor; eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; eventAttrib.message.ascii = name.toUtf8().data(); eventAttrib.payload.llValue = payload; eventAttrib.payloadType = NVTX_PAYLOAD_TYPE_UNSIGNED_INT64; nvtxRangePushEx(&eventAttrib); #endif } } Duration::~Duration() { if (tracingEnabled() && _category.isDebugEnabled()) { tracing::traceEvent(_category, _name, tracing::DurationEnd); #ifdef NSIGHT_TRACING nvtxRangePop(); #endif } } // FIXME uint64_t Duration::beginRange(const QLoggingCategory& category, const char* name, uint32_t argbColor) { #ifdef NSIGHT_TRACING if (tracingEnabled() && category.isDebugEnabled()) { nvtxEventAttributes_t eventAttrib = { 0 }; eventAttrib.version = NVTX_VERSION; eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; eventAttrib.colorType = NVTX_COLOR_ARGB; eventAttrib.color = argbColor; eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; eventAttrib.message.ascii = name; return nvtxRangeStartEx(&eventAttrib); } #endif return 0; } // FIXME void Duration::endRange(const QLoggingCategory& category, uint64_t rangeId) { #ifdef NSIGHT_TRACING if (tracingEnabled() && category.isDebugEnabled()) { nvtxRangeEnd(rangeId); } #endif }
38.181818
177
0.758201
[ "render" ]
f3d2567e509a46765f0215f915befefecad325ba
8,084
cc
C++
chainerx_cc/chainerx/routines/misc.cc
zaltoprofen/chainer
3b03f9afc80fd67f65d5e0395ef199e9506b6ee1
[ "MIT" ]
2
2019-08-12T21:48:04.000Z
2020-08-27T18:04:20.000Z
chainerx_cc/chainerx/routines/misc.cc
zaltoprofen/chainer
3b03f9afc80fd67f65d5e0395ef199e9506b6ee1
[ "MIT" ]
null
null
null
chainerx_cc/chainerx/routines/misc.cc
zaltoprofen/chainer
3b03f9afc80fd67f65d5e0395ef199e9506b6ee1
[ "MIT" ]
null
null
null
#include "chainerx/routines/misc.h" #include <utility> #include <absl/types/optional.h> #include "chainerx/array.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward_builder.h" #include "chainerx/backward_context.h" #include "chainerx/dtype.h" #include "chainerx/error.h" #include "chainerx/graph.h" #include "chainerx/kernels/misc.h" #include "chainerx/macro.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/logic.h" #include "chainerx/routines/routines_util.h" #include "chainerx/routines/type_util.h" #include "chainerx/scalar.h" namespace chainerx { namespace { void CheckComparisonDtypes(DtypeKind kind1, DtypeKind kind2) { if ((kind1 == DtypeKind::kBool) != (kind2 == DtypeKind::kBool)) { throw DtypeError{"Comparison of bool and non-bool dtypes is not supported."}; } } void CheckComparisonDtypes(const Array& x1, const Array& x2) { return CheckComparisonDtypes(GetKind(x1.dtype()), GetKind(x2.dtype())); } void CheckComparisonDtypes(const Array& x1, Scalar x2) { return CheckComparisonDtypes(GetKind(x1.dtype()), x2.kind()); } // Calculates: x1 < x2 ? pos : neg // Can only differentiate with respect to neg. Array IfLessElse(const Array& x1, Scalar x2, Scalar pos, const Array& neg) { CheckComparisonDtypes(x1, x2); Array out = Empty(x1.shape(), ResultType(pos, neg), x1.device()); // TODO(niboshi): Create mask array and reuse in backprop. { NoBackpropModeScope scope{}; x1.device().backend().CallKernel<IfLessElseASSAKernel>(x1, x2, pos, neg, out); } BackwardBuilder bb{"if_less_else", neg, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([x1 = x1.AsGradStopped(), x2](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); bctx.input_grad() = IfLessElse(x1, x2, Scalar{0, GetKind(gout.dtype())}, gout).AsType(x1.dtype(), false); }); } bb.Finalize(); return out; } // Calculates: x1 > x2 ? pos : neg // Can only differentiate with respect to neg. Array IfGreaterElse(const Array& x1, Scalar x2, Scalar pos, const Array& neg) { CheckComparisonDtypes(x1, x2); Array out = Empty(x1.shape(), ResultType(pos, neg), x1.device()); // TODO(niboshi): Create mask array and reuse in backprop. { NoBackpropModeScope scope{}; x1.device().backend().CallKernel<IfGreaterElseASSAKernel>(x1, x2, pos, neg, out); } BackwardBuilder bb{"if_greater_else", neg, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([x1 = x1.AsGradStopped(), x2](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); bctx.input_grad() = IfGreaterElse(x1, x2, Scalar{0, GetKind(gout.dtype())}, gout).AsType(x1.dtype(), false); }); } bb.Finalize(); return out; } void IfGreaterElseImpl(const Array& x1, const Array& x2, const Array& pos, const Array& neg, const Array& out) { CheckComparisonDtypes(x1, x2); CheckEqual(x1.shape(), x2.shape()); { NoBackpropModeScope scope{}; x1.device().backend().CallKernel<IfGreaterElseAAAAKernel>(x1, x2, pos, neg, out); } { BackwardBuilder bb{"if_greater_else", {pos, neg}, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { // TODO(imanishi): Remove redundantly comparison x1 > x2 twice. Array mask = Greater(x1, x2); bt.Define([mask = std::move(mask), pos_dtype = pos.dtype()](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); bctx.input_grad() = gout.AsType(pos_dtype, false) * mask; }); } if (BackwardBuilder::Target bt = bb.CreateTarget(1)) { // TODO(imanishi): Remove redundantly comparison x1 > x2 twice. Array not_mask = Less(x1, x2); bt.Define([not_mask = std::move(not_mask), neg_dtype = neg.dtype()](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); bctx.input_grad() = gout.AsType(neg_dtype, false) * not_mask; }); } bb.Finalize(); } } void MinimumImpl(const Array& x1, const Array& x2, const Array& out) { IfGreaterElseImpl(x1, x2, x2, x1, out); } void MaximumImpl(const Array& x1, const Array& x2, const Array& out) { IfGreaterElseImpl(x1, x2, x1, x2, out); } } // namespace Array Sqrt(const Array& x) { Dtype dtype = internal::GetMathResultDtype(x.dtype()); Array out = Empty(x.shape(), dtype, x.device()); { NoBackpropModeScope scope{}; x.device().backend().CallKernel<SqrtKernel>(x, out); } BackwardBuilder bb{"sqrt", x, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([out_tok = bb.RetainOutput(0)](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); const Array& out = bctx.GetRetainedOutput(out_tok); bctx.input_grad() = gout / (2 * out); }); } bb.Finalize(); return out; } Array Square(const Array& x) { if (x.dtype() == Dtype::kBool) { throw DtypeError{"Square operation don't support Boolean type"}; } Array out = EmptyLike(x, x.device()); { NoBackpropModeScope scope{}; x.device().backend().CallKernel<SquareKernel>(x, out); } BackwardBuilder bb{"square", x, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([x_tok = bb.RetainInput(0)](BackwardContext& bctx) { const Array& x = bctx.GetRetainedInput(x_tok); bctx.input_grad() = *bctx.output_grad() * (2 * x); }); } bb.Finalize(); return out; } Array Absolute(const Array& x) { Array x_flip_1 = IfGreaterElse(x, 0.0, 0.0, -x); Array x_flip_2 = IfLessElse(x, 0.0, 0.0, x); Array out = x_flip_1 + x_flip_2; return out; } Array Fabs(const Array& x) { Dtype dtype = internal::GetMathResultDtype(x.dtype()); Array out = Empty(x.shape(), dtype, x.device()); { NoBackpropModeScope scope{}; x.device().backend().CallKernel<FabsKernel>(x, out); } BackwardBuilder bb{"fabs", x, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([inp_tok = bb.RetainInput(0)](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); const Array& inp = bctx.GetRetainedInput(inp_tok); bctx.input_grad() = gout * Sign(inp); }); } bb.Finalize(); return out; } Array Sign(const Array& x) { Array out = Empty(x.shape(), x.dtype(), x.device()); { NoBackpropModeScope scope{}; x.device().backend().CallKernel<SignKernel>(x, out); } return out; } Array Maximum(const Array& x1, Scalar x2) { if (x1.dtype() == Dtype::kBool && x2.kind() == DtypeKind::kBool) { return LogicalOr(x1, x2); } // TODO(niboshi): IfLessElse redundantly casts x1 twice. return IfLessElse(x1, x2, x2, x1); // x1 < x2 ? x2 : x1 } Array Maximum(Scalar x1, const Array& x2) { return Maximum(x2, x1); } Array Maximum(const Array& x1, const Array& x2) { if (x1.dtype() == Dtype::kBool && x2.dtype() == Dtype::kBool) { return LogicalOr(x1, x2); } Dtype dtype = ResultType(x1, x2); return internal::BroadcastBinary(&MaximumImpl, x1, x2, dtype); // x1 > x2 ? x1 : x2 } Array Minimum(const Array& x1, Scalar x2) { if (x1.dtype() == Dtype::kBool && x2.kind() == DtypeKind::kBool) { return LogicalAnd(x1, x2); } // TODO(niboshi): IfGreaterElse redundantly casts x1 twice. return IfGreaterElse(x1, x2, x2, x1); // x1 > x2 ? x2 : x1 } Array Minimum(Scalar x1, const Array& x2) { return Minimum(x2, x1); } Array Minimum(const Array& x1, const Array& x2) { if (x1.dtype() == Dtype::kBool && x2.dtype() == Dtype::kBool) { return LogicalAnd(x1, x2); } Dtype dtype = ResultType(x1, x2); return internal::BroadcastBinary(&MinimumImpl, x1, x2, dtype); // x1 > x2 ? x2 : x1 } } // namespace chainerx
33.824268
136
0.623577
[ "shape" ]
f3d628e4293e756d0ac8dd507bef99fd29797499
895
hpp
C++
include/eve/memory/is_aligned.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/memory/is_aligned.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/memory/is_aligned.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <cstdint> #include <eve/memory/power_of_2.hpp> namespace eve { template<std::size_t Alignment, typename T> constexpr bool is_aligned(T value) noexcept { static_assert(is_power_of_2(Alignment), "[eve] Alignment must be a power of 2"); return (value & (Alignment - 1)) == 0; } template<std::size_t Alignment, typename T> constexpr bool is_aligned(T *ptr) noexcept { static_assert(is_power_of_2(Alignment), "[eve] Alignment must be a power of 2"); return is_aligned<Alignment>(reinterpret_cast<std::uintptr_t>(ptr)); } }
29.833333
100
0.550838
[ "vector" ]
f3dca7710558313e3c97d4f288465db58d300729
1,749
cpp
C++
labs/lab03/bubble_sort.cpp
Ligh7bringer/SET10108-practicals
b0120978181f0bb7ae7d7395e57ea4b1d452d978
[ "MIT" ]
null
null
null
labs/lab03/bubble_sort.cpp
Ligh7bringer/SET10108-practicals
b0120978181f0bb7ae7d7395e57ea4b1d452d978
[ "MIT" ]
null
null
null
labs/lab03/bubble_sort.cpp
Ligh7bringer/SET10108-practicals
b0120978181f0bb7ae7d7395e57ea4b1d452d978
[ "MIT" ]
null
null
null
#include <iostream> #include <omp.h> #include <vector> #include <random> #include <chrono> #include <fstream> std::vector<unsigned int> generate_values(size_t size) { // create random engine std::random_device r; std::default_random_engine e(r()); // generate numbers std::vector<unsigned int> data; for(size_t i = 0; i < size; ++i) data.push_back(e()); return data; } void bubble_sort(std::vector<unsigned int>& values) { for(auto count = values.size(); count >= 2; --count) { for(size_t i = 0; i < count - 1; ++i) { if(values[i] > values[i+1]) { auto temp = values[i]; values[i] = values[i+1]; values[i+1] = temp; } } } } int main() { // create results file std::ofstream results("bubble.csv", std::ofstream::out); for(size_t size = 8; size <= 16; ++size) { // show data size results << pow(2, size) << ", "; // gather 100 results for(size_t i = 0; i < 100; ++i) { // generate a vector of random values std::cout << "Generating " << i << " for " << pow(2, size) << " values " << std::endl; auto data = generate_values(static_cast<size_t>(pow(2, size))); // sort and time std::cout << "Sorting..." << std::endl; auto start = std::chrono::system_clock::now(); bubble_sort(data); auto end = std::chrono::system_clock::now(); auto total = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); // output time results << total << ","; } results << std::endl; } results.close(); return 0; }
30.155172
100
0.523156
[ "vector" ]
f3e1942767f055cf3d1beb1a43b2fe93240534de
13,211
cpp
C++
source/blender/collada/GeometryExporter.cpp
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/blender/collada/GeometryExporter.cpp
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/blender/collada/GeometryExporter.cpp
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/* * $Id: GeometryExporter.cpp 40382 2011-09-20 06:25:15Z campbellbarton $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * 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 the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed, * Nathan Letwory * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/collada/GeometryExporter.cpp * \ingroup collada */ #include <sstream> #include "COLLADASWPrimitves.h" #include "COLLADASWSource.h" #include "COLLADASWVertices.h" #include "COLLADABUUtils.h" #include "GeometryExporter.h" #include "DNA_meshdata_types.h" #include "BKE_customdata.h" #include "BKE_material.h" #include "collada_internal.h" // TODO: optimize UV sets by making indexed list with duplicates removed GeometryExporter::GeometryExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryGeometries(sw), export_settings(export_settings) {} void GeometryExporter::exportGeom(Scene *sce) { openLibrary(); mScene = sce; GeometryFunctor gf; gf.forEachMeshObjectInScene<GeometryExporter>(sce, *this, this->export_settings->selected); closeLibrary(); } void GeometryExporter::operator()(Object *ob) { // XXX don't use DerivedMesh, Mesh instead? #if 0 DerivedMesh *dm = mesh_get_derived_final(mScene, ob, CD_MASK_BAREMESH); #endif Mesh *me = (Mesh*)ob->data; std::string geom_id = get_geometry_id(ob); std::vector<Normal> nor; std::vector<Face> norind; // Skip if linked geometry was already exported from another reference if (exportedGeometry.find(geom_id) != exportedGeometry.end()) return; exportedGeometry.insert(geom_id); bool has_color = (bool)CustomData_has_layer(&me->fdata, CD_MCOL); create_normals(nor, norind, me); // openMesh(geoId, geoName, meshId) openMesh(geom_id); // writes <source> for vertex coords createVertsSource(geom_id, me); // writes <source> for normal coords createNormalsSource(geom_id, me, nor); bool has_uvs = (bool)CustomData_has_layer(&me->fdata, CD_MTFACE); // writes <source> for uv coords if mesh has uv coords if (has_uvs) createTexcoordsSource(geom_id, me); if (has_color) createVertexColorSource(geom_id, me); // <vertices> COLLADASW::Vertices verts(mSW); verts.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX)); COLLADASW::InputList &input_list = verts.getInputList(); COLLADASW::Input input(COLLADASW::InputSemantic::POSITION, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::POSITION)); input_list.push_back(input); verts.add(); // XXX slow if (ob->totcol) { for(int a = 0; a < ob->totcol; a++) { createPolylist(a, has_uvs, has_color, ob, geom_id, norind); } } else { createPolylist(0, has_uvs, has_color, ob, geom_id, norind); } closeMesh(); if (me->flag & ME_TWOSIDED) { mSW->appendTextBlock("<extra><technique profile=\"MAYA\"><double_sided>1</double_sided></technique></extra>"); } closeGeometry(); #if 0 dm->release(dm); #endif } // powerful because it handles both cases when there is material and when there's not void GeometryExporter::createPolylist(short material_index, bool has_uvs, bool has_color, Object *ob, std::string& geom_id, std::vector<Face>& norind) { Mesh *me = (Mesh*)ob->data; MFace *mfaces = me->mface; int totfaces = me->totface; // <vcount> int i; int faces_in_polylist = 0; std::vector<unsigned long> vcount_list; // count faces with this material for (i = 0; i < totfaces; i++) { MFace *f = &mfaces[i]; if (f->mat_nr == material_index) { faces_in_polylist++; if (f->v4 == 0) { vcount_list.push_back(3); } else { vcount_list.push_back(4); } } } // no faces using this material if (faces_in_polylist == 0) { fprintf(stderr, "%s: no faces use material %d\n", id_name(ob).c_str(), material_index); return; } Material *ma = ob->totcol ? give_current_material(ob, material_index + 1) : NULL; COLLADASW::Polylist polylist(mSW); // sets count attribute in <polylist> polylist.setCount(faces_in_polylist); // sets material name if (ma) { std::ostringstream ostr; ostr << translate_id(id_name(ma)) << material_index+1; polylist.setMaterial(ostr.str()); } COLLADASW::InputList &til = polylist.getInputList(); // creates <input> in <polylist> for vertices COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0); // creates <input> in <polylist> for normals COLLADASW::Input input2(COLLADASW::InputSemantic::NORMAL, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL), 1); til.push_back(input1); til.push_back(input2); // if mesh has uv coords writes <input> for TEXCOORD int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE); for (i = 0; i < num_layers; i++) { // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i); COLLADASW::Input input3(COLLADASW::InputSemantic::TEXCOORD, makeUrl(makeTexcoordSourceId(geom_id, i)), 2, // offset always 2, this is only until we have optimized UV sets i // set number equals UV layer index ); til.push_back(input3); } if (has_color) { COLLADASW::Input input4(COLLADASW::InputSemantic::COLOR, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::COLOR), has_uvs ? 3 : 2); til.push_back(input4); } // sets <vcount> polylist.setVCountList(vcount_list); // performs the actual writing polylist.prepareToAppendValues(); // <p> int texindex = 0; for (i = 0; i < totfaces; i++) { MFace *f = &mfaces[i]; if (f->mat_nr == material_index) { unsigned int *v = &f->v1; unsigned int *n = &norind[i].v1; for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) { polylist.appendValues(v[j]); polylist.appendValues(n[j]); if (has_uvs) polylist.appendValues(texindex + j); if (has_color) polylist.appendValues(texindex + j); } } texindex += 3; if (f->v4 != 0) texindex++; } polylist.finish(); } // creates <source> for positions void GeometryExporter::createVertsSource(std::string geom_id, Mesh *me) { #if 0 int totverts = dm->getNumVerts(dm); MVert *verts = dm->getVertArray(dm); #endif int totverts = me->totvert; MVert *verts = me->mvert; COLLADASW::FloatSourceF source(mSW); source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION)); source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION) + ARRAY_ID_SUFFIX); source.setAccessorCount(totverts); source.setAccessorStride(3); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); param.push_back("X"); param.push_back("Y"); param.push_back("Z"); /*main function, it creates <source id = "">, <float_array id = "" count = ""> */ source.prepareToAppendValues(); //appends data to <float_array> int i = 0; for (i = 0; i < totverts; i++) { source.appendValues(verts[i].co[0], verts[i].co[1], verts[i].co[2]); } source.finish(); } void GeometryExporter::createVertexColorSource(std::string geom_id, Mesh *me) { if (!CustomData_has_layer(&me->fdata, CD_MCOL)) return; MFace *f; int totcolor = 0, i, j; for (i = 0, f = me->mface; i < me->totface; i++, f++) totcolor += f->v4 ? 4 : 3; COLLADASW::FloatSourceF source(mSW); source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR)); source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR) + ARRAY_ID_SUFFIX); source.setAccessorCount(totcolor); source.setAccessorStride(3); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); param.push_back("R"); param.push_back("G"); param.push_back("B"); source.prepareToAppendValues(); int index = CustomData_get_active_layer_index(&me->fdata, CD_MCOL); MCol *mcol = (MCol*)me->fdata.layers[index].data; MCol *c = mcol; for (i = 0, f = me->mface; i < me->totface; i++, c += 4, f++) for (j = 0; j < (f->v4 ? 4 : 3); j++) source.appendValues(c[j].b / 255.0f, c[j].g / 255.0f, c[j].r / 255.0f); source.finish(); } std::string GeometryExporter::makeTexcoordSourceId(std::string& geom_id, int layer_index) { char suffix[20]; sprintf(suffix, "-%d", layer_index); return getIdBySemantics(geom_id, COLLADASW::InputSemantic::TEXCOORD) + suffix; } //creates <source> for texcoords void GeometryExporter::createTexcoordsSource(std::string geom_id, Mesh *me) { #if 0 int totfaces = dm->getNumFaces(dm); MFace *mfaces = dm->getFaceArray(dm); #endif int totfaces = me->totface; MFace *mfaces = me->mface; int totuv = 0; int i; // count totuv for (i = 0; i < totfaces; i++) { MFace *f = &mfaces[i]; if (f->v4 == 0) { totuv+=3; } else { totuv+=4; } } int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE); // write <source> for each layer // each <source> will get id like meshName + "map-channel-1" for (int a = 0; a < num_layers; a++) { MTFace *tface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, a); // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, a); COLLADASW::FloatSourceF source(mSW); std::string layer_id = makeTexcoordSourceId(geom_id, a); source.setId(layer_id); source.setArrayId(layer_id + ARRAY_ID_SUFFIX); source.setAccessorCount(totuv); source.setAccessorStride(2); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); param.push_back("S"); param.push_back("T"); source.prepareToAppendValues(); for (i = 0; i < totfaces; i++) { MFace *f = &mfaces[i]; for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) { source.appendValues(tface[i].uv[j][0], tface[i].uv[j][1]); } } source.finish(); } } //creates <source> for normals void GeometryExporter::createNormalsSource(std::string geom_id, Mesh *me, std::vector<Normal>& nor) { #if 0 int totverts = dm->getNumVerts(dm); MVert *verts = dm->getVertArray(dm); #endif COLLADASW::FloatSourceF source(mSW); source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL)); source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL) + ARRAY_ID_SUFFIX); source.setAccessorCount((unsigned long)nor.size()); source.setAccessorStride(3); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); param.push_back("X"); param.push_back("Y"); param.push_back("Z"); source.prepareToAppendValues(); std::vector<Normal>::iterator it; for (it = nor.begin(); it != nor.end(); it++) { Normal& n = *it; source.appendValues(n.x, n.y, n.z); } source.finish(); } void GeometryExporter::create_normals(std::vector<Normal> &nor, std::vector<Face> &ind, Mesh *me) { int i, j, v; MVert *vert = me->mvert; std::map<unsigned int, unsigned int> nshar; for (i = 0; i < me->totface; i++) { MFace *fa = &me->mface[i]; Face f; unsigned int *nn = &f.v1; unsigned int *vv = &fa->v1; memset(&f, 0, sizeof(f)); v = fa->v4 == 0 ? 3 : 4; if (!(fa->flag & ME_SMOOTH)) { Normal n; if (v == 4) normal_quad_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co, vert[fa->v4].co); else normal_tri_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co); nor.push_back(n); } for (j = 0; j < v; j++) { if (fa->flag & ME_SMOOTH) { if (nshar.find(*vv) != nshar.end()) *nn = nshar[*vv]; else { Normal n = { vert[*vv].no[0]/32767.0, vert[*vv].no[1]/32767.0, vert[*vv].no[2]/32767.0 }; nor.push_back(n); *nn = (unsigned int)nor.size() - 1; nshar[*vv] = *nn; } vv++; } else { *nn = (unsigned int)nor.size() - 1; } nn++; } ind.push_back(f); } } std::string GeometryExporter::getIdBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix) { return geom_id + getSuffixBySemantic(type) + other_suffix; } COLLADASW::URI GeometryExporter::getUrlBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix) { std::string id(getIdBySemantics(geom_id, type, other_suffix)); return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id); } COLLADASW::URI GeometryExporter::makeUrl(std::string id) { return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id); } /* int GeometryExporter::getTriCount(MFace *faces, int totface) { int i; int tris = 0; for (i = 0; i < totface; i++) { // if quad if (faces[i].v4 != 0) tris += 2; else tris++; } return tris; }*/
26.851626
174
0.679055
[ "mesh", "geometry", "object", "vector" ]
f3e1f5bc906c9aac08c92e5faef262c56437348b
802
cpp
C++
test/container_view.cpp
romariorios/coruja
275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af
[ "BSL-1.0" ]
13
2017-10-24T07:13:28.000Z
2020-10-07T02:51:31.000Z
test/container_view.cpp
romariorios/coruja
275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af
[ "BSL-1.0" ]
1
2019-10-30T21:50:44.000Z
2019-11-06T19:35:23.000Z
test/container_view.cpp
romariorios/coruja
275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af
[ "BSL-1.0" ]
5
2018-09-19T20:29:07.000Z
2020-03-20T18:12:09.000Z
#include "check_equal.hpp" #include <coruja/container/view/container.hpp> #include <coruja/container/vector.hpp> #include <range/v3/range_concepts.hpp> #include <string> using namespace coruja; using svector = vector<std::string>; int main() { static_assert(std::is_same<view::container<svector>::observed_t, svector::observed_t>::value, ""); static_assert(std::is_same<view::container<svector>::for_each_connection_t, svector::for_each_connection_t>::value, ""); static_assert(std::is_same<view::container<svector>::before_erase_connection_t, svector::before_erase_connection_t>::value, ""); static_assert(ranges::Range<view::container<svector>>::value, ""); { view::container<svector>(); } //TODO }
27.655172
83
0.670823
[ "vector" ]
f3ea419b6851ca9c2d109294c5fd742d12307450
3,854
cc
C++
dmlab2d/system/tile/lua/tile_set.cc
RacingTadpole/lab2d
2261b939ebd574505346accd09ce5b9e30398998
[ "Apache-2.0" ]
null
null
null
dmlab2d/system/tile/lua/tile_set.cc
RacingTadpole/lab2d
2261b939ebd574505346accd09ce5b9e30398998
[ "Apache-2.0" ]
null
null
null
dmlab2d/system/tile/lua/tile_set.cc
RacingTadpole/lab2d
2261b939ebd574505346accd09ce5b9e30398998
[ "Apache-2.0" ]
1
2021-12-08T11:28:00.000Z
2021-12-08T11:28:00.000Z
// Copyright (C) 2019 The DMLab2D 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 // // https://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 "dmlab2d/system/tile/lua/tile_set.h" #include <memory> #include <utility> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "dmlab2d/lua/read.h" #include "dmlab2d/lua/ref.h" #include "dmlab2d/lua/table_ref.h" #include "dmlab2d/system/math/lua/math2d.h" #include "dmlab2d/system/math/math2d.h" #include "dmlab2d/system/tensor/lua/tensor.h" #include "dmlab2d/system/tile/tile_set.h" namespace deepmind::lab2d { void LuaTileSet::Register(lua_State* L) { const Class::Reg methods[] = { {"setSprite", &Class::Member<&LuaTileSet::SetSprite>}, {"shape", &Class::Member<&LuaTileSet::SpriteShape>}, {"names", &Class::Member<&LuaTileSet::SpriteNames>}, }; Class::Register(L, methods); } lua::NResultsOr LuaTileSet::SpriteNames(lua_State* L) { lua::Push(L, sprite_names_); return 1; } lua::NResultsOr LuaTileSet::SpriteShape(lua_State* L) { Push(L, tile_set_.sprite_shape()); return 1; } lua::NResultsOr LuaTileSet::SetSprite(lua_State* L) { lua::TableRef table; if (!IsFound(lua::Read(L, 2, &table))) { return "Arg 1 must be a kwarg table!"; } absl::string_view name; if (!IsFound(table.LookUp("name", &name))) { return "'name' must be a string"; } tensor::LuaTensor<unsigned char>* image; if (!IsFound(table.LookUp("image", &image))) { return "'image' - Must supply ByteTensor(h, w, 3 or 4) or " " ByteTensor(count, h, w, 3 or 4)!"; } const auto& image_view = image->tensor_view(); int sprites_set = 0; for (std::size_t sprite_id = 0; sprite_id < sprite_names_.size(); ++sprite_id) { absl::string_view suffix = sprite_names_[sprite_id]; if (absl::StartsWith(suffix, name)) { suffix.remove_prefix(name.size()); if (suffix.empty() || suffix[0] == '.') { tensor::TensorView<unsigned char> facing = image_view; if (facing.shape().size() == 4) { facing.Select(0, sprites_set); } if (!tile_set_.SetSprite(sprite_id, facing)) { return absl::StrFormat( "Error occured when setting sprite '%s%s' to %s", name, suffix, absl::FormatStreamed(facing)); } ++sprites_set; } } } if (image_view.shape().size() == 4 && sprites_set != image_view.shape()[0]) { return absl::StrFormat( "Mismatch count of sprites with prefix '%s'; Required: %d, Actual: %d.", name, image_view.shape()[0], sprites_set); } lua::Push(L, sprites_set); return 1; } lua::NResultsOr LuaTileSet::Create(lua_State* L) { lua::TableRef table; if (!IsFound(lua::Read(L, 1, &table))) { return "[tile.set] - Arg 1 must be a table."; } math::Size2d sprite_shape; std::vector<std::string> sprite_names; if (!IsFound(table.LookUp("names", &sprite_names))) { return "[tile.set] - 'names' must be an array of strings."; } if (!IsFound(table.LookUp("shape", &sprite_shape))) { return "[tile.set] - 'shape' must be a table containing height and width."; } lua_pop(L, 1); CreateObject(L, std::move(sprite_names), TileSet(sprite_names.size(), sprite_shape)); return 1; } } // namespace deepmind::lab2d
31.333333
80
0.656201
[ "shape", "vector" ]
f3eeb1b094b64fb9de0f642cf94a5d6efb52edef
5,872
cpp
C++
src/FleeManager.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
12
2022-03-23T05:14:53.000Z
2022-03-30T12:12:58.000Z
src/FleeManager.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
24
2022-03-23T13:56:37.000Z
2022-03-31T18:23:32.000Z
src/FleeManager.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
3
2022-03-24T21:47:10.000Z
2022-03-31T06:21:46.000Z
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version. */ #include "FleeManager.h" #include "Playerbots.h" #include "ServerFacade.h" FleeManager::FleeManager(Player* bot, float maxAllowedDistance, float followAngle, bool forceMaxDistance, WorldPosition startPosition) : bot(bot), maxAllowedDistance(maxAllowedDistance), followAngle(followAngle), forceMaxDistance(forceMaxDistance), startPosition(startPosition ? startPosition : WorldPosition(bot)) { } void FleeManager::calculateDistanceToCreatures(FleePoint *point) { point->minDistance = -1.0f; point->sumDistance = 0.0f; PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); GuidVector units = *botAI->GetAiObjectContext()->GetValue<GuidVector>("possible targets no los"); for (GuidVector::iterator i = units.begin(); i != units.end(); ++i) { Unit* unit = botAI->GetUnit(*i); if (!unit) continue; float d = sServerFacade->GetDistance2d(unit, point->x, point->y); point->sumDistance += d; if (point->minDistance < 0 || point->minDistance > d) point->minDistance = d; } } bool intersectsOri(float angle, std::vector<float>& angles, float angleIncrement) { for (std::vector<float>::iterator i = angles.begin(); i != angles.end(); ++i) { float ori = *i; if (abs(angle - ori) < angleIncrement) return true; } return false; } void FleeManager::calculatePossibleDestinations(std::vector<FleePoint*> &points) { PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); Unit* target = *botAI->GetAiObjectContext()->GetValue<Unit*>("current target"); float botPosX = startPosition.getX(); float botPosY = startPosition.getY(); float botPosZ = startPosition.getZ(); FleePoint start(botAI, botPosX, botPosY, botPosZ); calculateDistanceToCreatures(&start); std::vector<float> enemyOri; GuidVector units = *botAI->GetAiObjectContext()->GetValue<GuidVector>("possible targets no los"); for (GuidVector::iterator i = units.begin(); i != units.end(); ++i) { Unit* unit = botAI->GetUnit(*i); if (!unit) continue; float ori = bot->GetAngle(unit); enemyOri.push_back(ori); } float distIncrement = std::max(sPlayerbotAIConfig->followDistance, (maxAllowedDistance - sPlayerbotAIConfig->tooCloseDistance) / 10.0f); for (float dist = maxAllowedDistance; dist >= sPlayerbotAIConfig->tooCloseDistance ; dist -= distIncrement) { float angleIncrement = std::max(M_PI / 20, M_PI / 4 / (1.0 + dist - sPlayerbotAIConfig->tooCloseDistance)); for (float add = 0.0f; add < M_PI / 4 + angleIncrement; add += angleIncrement) { for (float angle = add; angle < add + 2 * static_cast<float>(M_PI) + angleIncrement; angle += static_cast<float>(M_PI) / 4) { if (intersectsOri(angle, enemyOri, angleIncrement)) continue; float x = botPosX + cos(angle) * maxAllowedDistance, y = botPosY + sin(angle) * maxAllowedDistance, z = botPosZ + CONTACT_DISTANCE; if (forceMaxDistance && sServerFacade->IsDistanceLessThan(sServerFacade->GetDistance2d(bot, x, y), maxAllowedDistance - sPlayerbotAIConfig->tooCloseDistance)) continue; bot->UpdateAllowedPositionZ(x, y, z); Map* map = startPosition.getMap(); if (map && map->IsInWater(bot->GetPhaseMask(), x, y, z, bot->GetCollisionHeight())) continue; if (!bot->IsWithinLOS(x, y, z) || (target && !target->IsWithinLOS(x, y, z))) continue; FleePoint* point = new FleePoint(botAI, x, y, z); calculateDistanceToCreatures(point); if (sServerFacade->IsDistanceGreaterOrEqualThan(point->minDistance - start.minDistance, sPlayerbotAIConfig->followDistance)) points.push_back(point); else delete point; } } } } void FleeManager::cleanup(std::vector<FleePoint*> &points) { for (std::vector<FleePoint*>::iterator i = points.begin(); i != points.end(); i++) { delete *i; } points.clear(); } bool FleeManager::isBetterThan(FleePoint* point, FleePoint* other) { return point->sumDistance - other->sumDistance > 0; } FleePoint* FleeManager::selectOptimalDestination(std::vector<FleePoint*> &points) { FleePoint* best = nullptr; for (std::vector<FleePoint*>::iterator i = points.begin(); i != points.end(); i++) { FleePoint* point = *i; if (!best || isBetterThan(point, best)) best = point; } return best; } bool FleeManager::CalculateDestination(float* rx, float* ry, float* rz) { std::vector<FleePoint*> points; calculatePossibleDestinations(points); FleePoint* point = selectOptimalDestination(points); if (!point) { cleanup(points); return false; } *rx = point->x; *ry = point->y; *rz = point->z; cleanup(points); return true; } bool FleeManager::isUseful() { PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); GuidVector units = *botAI->GetAiObjectContext()->GetValue<GuidVector>("possible targets no los"); for (GuidVector::iterator i = units.begin(); i != units.end(); ++i) { Creature* creature = botAI->GetCreature(*i); if (!creature) continue; if (startPosition.sqDistance(WorldPosition(creature)) < creature->GetAttackDistance(bot) * creature->GetAttackDistance(bot)) return true; // float d = sServerFacade->GetDistance2d(unit, bot); // if (sServerFacade->IsDistanceLessThan(d, sPlayerbotAIConfig->aggroDistance)) return true; } return false; }
34.139535
205
0.643903
[ "vector" ]
f3f3f9a9ea7f7266f64cd15d1c46e021c517ca76
11,426
cpp
C++
VolumeAnalytics/volumeanalytics.cpp
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
VolumeAnalytics/volumeanalytics.cpp
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
VolumeAnalytics/volumeanalytics.cpp
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
#include "volumeanalytics.h" #include "histogramprocessor.h" #include <stdio.h> #include <ipp.h> #include <iostream> #include "src/plugins/Application/ZeissViewer/SegmentationInterface/ZeissSegmentationInterface.hpp" #include "src/plugins/Application/ZeissViewer/SeparationInterface/ZeissSeparationInterface.hpp" namespace imt { namespace volume { // Type of interpolation, the following values are possible : // IPPI_INTER_NN - nearest neighbor interpolation, // IPPI_INTER_LINEAR - trilinear interpolation, // IPPI_INTER_CUBIC - tricubic interpolation, // IPPI_INTER_CUBIC2P_BSPLINE - B - spline, // IPPI_INTER_CUBIC2P_CATMULLROM - Catmull - Rom spline, // IPPI_INTER_CUBIC2P_B05C03 - special two - parameters filter(1 / 2, 3 / 10). void VolumeAnalytics::resizeVolume_Uint16C1(unsigned short *inputVolume, int iWidth, int iHeight, int iDepth, unsigned short *outputVolume, int oWidth, int oHeight, int oDepth, double resizeRatio) { IpprVolume inputVolumeSize, outputVolumeSize; int srcStep = iWidth * sizeof(unsigned short); int srcPlaneStep = iWidth * iHeight * sizeof(unsigned short); IpprCuboid srcVoi; int dstStep = oWidth * sizeof(unsigned short); int dstPlaneStep = oWidth * oHeight * sizeof(unsigned short); IpprCuboid dstVoi; double xFactor = resizeRatio, yFactor = resizeRatio, zFactor = resizeRatio; double xShift = 0, yShift = 0, zShift = 0; int interpolation = IPPI_INTER_LINEAR;//IPPI_INTER_CUBIC2P_B05C03;// // Type of interpolation, the following values are possible : // IPPI_INTER_NN - nearest neighbor interpolation, // IPPI_INTER_LINEAR - trilinear interpolation, // IPPI_INTER_CUBIC - tricubic interpolation, // IPPI_INTER_CUBIC2P_BSPLINE - B - spline, // IPPI_INTER_CUBIC2P_CATMULLROM - Catmull - Rom spline, // IPPI_INTER_CUBIC2P_B05C03 - special two - parameters filter(1 / 2, 3 / 10). inputVolumeSize.width = iWidth; inputVolumeSize.height = iHeight; inputVolumeSize.depth = iDepth; srcVoi.x = 0; srcVoi.y = 0; srcVoi.z = 0; srcVoi.width = iWidth; srcVoi.height = iHeight; srcVoi.depth = iDepth; dstVoi.x = 0; dstVoi.y = 0; dstVoi.z = 0; dstVoi.width = oWidth; dstVoi.height = oHeight; dstVoi.depth = oDepth; Ipp8u *computationBuffer; int bufferSize = 0; ipprResizeGetBufSize(srcVoi, dstVoi, 1, interpolation, &bufferSize); computationBuffer = new Ipp8u[bufferSize]; ipprResize_16u_C1V(inputVolume, inputVolumeSize, srcStep, srcPlaneStep, srcVoi, outputVolume, dstStep, dstPlaneStep, dstVoi, xFactor, yFactor, zFactor, xShift, yShift, zShift, interpolation, computationBuffer); delete[] computationBuffer; } void VolumeAnalytics::resizeVolume_Uint16C1_MT(unsigned short *inputVolume, int iWidth, int iHeight, int iDepth, unsigned short *outputVolume, int oWidth, int oHeight, int oDepth, double resizeRatio) { int bandWidth = 32; int numBands = oDepth % 32 == 0 ? oDepth / bandWidth : oDepth / bandWidth + 1; int extension = (1.0 / resizeRatio) + 1; if (numBands > 1) { double progress = 0; #pragma omp parallel for for (int bb = 0; bb < numBands; bb++) { IpprVolume inputVolumeSize, outputVolumeSize; int srcStep = iWidth * sizeof(unsigned short); int srcPlaneStep = iWidth * iHeight * sizeof(unsigned short); IpprCuboid srcVoi; int dstStep = oWidth * sizeof(unsigned short); int dstPlaneStep = oWidth * oHeight * sizeof(unsigned short); IpprCuboid dstVoi; double xFactor = resizeRatio, yFactor = resizeRatio, zFactor = resizeRatio; double xShift = 0, yShift = 0, zShift = 0; int interpolation = IPPI_INTER_LINEAR; int sourceBand = (int)(bandWidth / resizeRatio + 1); if (bb == 0 || bb == numBands - 1) { sourceBand += extension; } else { sourceBand += 2 * extension; } double destStartLine = bandWidth * bb; int destBandWidth = bandWidth; double sourceStartLine = destStartLine / resizeRatio; if (bb == numBands - 1) { destBandWidth = oDepth - bandWidth * bb; } dstVoi.x = 0; dstVoi.y = 0; dstVoi.z = 0; dstVoi.width = oWidth; dstVoi.height = oHeight; dstVoi.depth = destBandWidth; size_t sourceDataShift = 0; size_t destDataShift = 0; double sourceLineZ = bandWidth * bb / resizeRatio; int sourceStartZ = (int)(sourceLineZ - extension); if (bb == 0) sourceStartZ = 0; if (bb == numBands - 1) { sourceBand = iDepth - sourceStartZ; } srcVoi.x = 0; srcVoi.y = 0; srcVoi.z = 0; srcVoi.width = iWidth; srcVoi.height = iHeight; srcVoi.depth = sourceBand; inputVolumeSize.width = iWidth; inputVolumeSize.height = iHeight; inputVolumeSize.depth = sourceBand; sourceDataShift = (size_t)sourceStartZ * (size_t)iWidth * (size_t)iHeight; destDataShift = (size_t)bandWidth * (size_t)bb * (size_t)oWidth * (size_t)oHeight; Ipp8u *computationBuffer; zShift = -destStartLine + sourceStartZ * resizeRatio; int bufferSize = 0; ipprResizeGetBufSize(srcVoi, dstVoi, 1, interpolation, &bufferSize); computationBuffer = new Ipp8u[bufferSize]; ipprResize_16u_C1V(inputVolume + sourceDataShift, inputVolumeSize, srcStep, srcPlaneStep, srcVoi, outputVolume + destDataShift, dstStep, dstPlaneStep, dstVoi, xFactor, yFactor, zFactor, xShift, yShift, zShift, interpolation, computationBuffer); delete[] computationBuffer; } } else { resizeVolume_Uint16C1(inputVolume, iWidth, iHeight, iDepth, outputVolume, oWidth, oHeight, oDepth, resizeRatio); } } VolumeAnalytics::VolumeAnalytics() { } void VolumeAnalytics::readVolumeData(std::string& path, VolumeData& volume) { FILE *file2 = fopen(path.c_str(), "rb"); char buffer[1024]; fread(buffer, 1, 1024, file2); int *bf = (int*)buffer; int headerSize = *bf; bf++; int mirrorZ = *bf; bf++; int numBitsPerVoxel = *bf; bf++; int volumeSizeX = *bf; bf++; int volumeSizeY = *bf; bf++; int volumeSizeZ = *bf; bf++; double *fbf = (double*)bf; double voxelSizeX = *fbf; fbf++; double voxelSizeY = *fbf; fbf++; double voxelSizeZ = *fbf; fbf++; double resultBitDepthMinVal = *fbf; fbf++; double resultBitDepthmaxVal = *fbf; fbf++; double tubePosX = *fbf; fbf++; double tubePosY = *fbf; fbf++; double tubePosZ = *fbf; fbf++; bf = (int*)fbf; int tubeCurrent = *bf; bf++; int tubeVoltage = *bf; bf++; fbf = (double*)bf; double rtPosX = *fbf; fbf++; double rtPosY = *fbf; fbf++; double rtPosZ = *fbf; fbf++; double detectorIntegrationTime = *fbf; //int mili seconds fbf++; double detectorGain = *fbf; fbf++; double detectorXPos = *fbf; fbf++; double detectorYPos = *fbf; fbf++; double detectorZPos = *fbf; fbf++; float *sbf = (float*)fbf; float detectorPixelWidth = *sbf; sbf++; float detectorPixelHeight = *sbf; sbf++; bf = (int*)sbf; int imageBitDepth = *bf; bf++; int detectorWidth = *bf; bf++; int detectorHeight = *bf; bf++; int detectorImageWidth = *bf; bf++; int detectorImageHeight = *bf; bf++; unsigned int* ubf = (unsigned int*)bf; int numberOfProjections = *ubf; ubf++; bf = (int*)ubf; int roiX = *bf; bf++; int roiY = *bf; bf++; int roiWidth = *bf; bf++; int roiHeight = *bf; bf++; fbf = (double*)bf; double noiseSuppressionFilter = *fbf; fbf++; double voxelreductionFactor = *fbf; fbf++; sbf = (float*)fbf; float gain = *sbf; sbf++; float binningMode = *sbf; sbf++; char prefilterData[128]; memcpy(prefilterData, sbf, 128); fbf = (double*)(sbf + 32); double volumeStartPosX = *fbf; fbf++; double volumeStartPosY = *fbf; fbf++; double volumeStartPosZ = *fbf; fbf++; sbf = (float*)fbf; float minValue = *sbf; sbf++; float maxValue = *sbf; sbf++; float volumeDefinitionAngle = *sbf; sbf++; bool *bbf = (bool*)sbf; bool volumeMerge = *bbf; volume._Width = volumeSizeX; volume._Height = volumeSizeY; volume._Depth = volumeSizeZ; volume._VoxelSizeX = voxelSizeX; volume._VoxelSizeY = voxelSizeY; volume._VoxelSizeZ = voxelSizeZ; int64_t size = volume._Width * volume._Height * volume._Depth; volume._VolumeBuffer = new unsigned short[size]; fread(volume._VolumeBuffer, 2, size, file2); fclose(file2); } unsigned short VolumeAnalytics::computeIsoThreshold(VolumeAnalytics::VolumeData& volume) { unsigned short isoThreshold = 0; HistogramProcessor histogramFilter; std::vector<int64_t> histogram(USHRT_MAX, 0); int64_t volumeSize = volume._Width * volume._Height * volume._Depth; for (int64_t vv = 0; vv < volumeSize; vv++) { int grayValue = volume._VolumeBuffer[vv]; histogram[grayValue]++; } isoThreshold = histogramFilter.ISO50Threshold(histogram); Volume vol; vol.size[0] = volume._Width; vol.size[1] = volume._Height; vol.size[2] = volume._Depth; vol.voxel_size[0] = volume._VoxelSizeX; vol.voxel_size[1] = volume._VoxelSizeY; vol.voxel_size[2] = volume._VoxelSizeZ; vol.data = (uint16_t*)volume._VolumeBuffer; ZeissSegmentationInterface segmenter; SegmentationParameter param; param.max_memory = static_cast<size_t>(2048) * 1024 * 1024; param.output_material_index = false; segmenter.setParameter(param); segmenter.setInputVolume(vol); Materials materials = segmenter.getMaterialRegions(); isoThreshold = materials.regions[materials.first_material_index].lower_bound; return isoThreshold; } void VolumeAnalytics::generateMesh(const VolumeData& volume, int isoThreshold, SurfaceMesh& surfaceMesh) { } void VolumeAnalytics::reduceVolume(const VolumeData& inputVolume, VolumeData& targetVolume, double reductionCoeff)//each side is reduced by this coefficient { if (reductionCoeff >= 1.0) { std::cout << "failed volume reduction , reduction coefficient should be less than 1 " << std::endl; return ; } targetVolume._Width = inputVolume._Width * reductionCoeff; targetVolume._Height = inputVolume._Height * reductionCoeff; targetVolume._Depth = inputVolume._Depth * reductionCoeff; targetVolume._VolumeBuffer = (new unsigned short[targetVolume._Width * targetVolume._Height * targetVolume._Depth]); targetVolume._VoxelSizeX = targetVolume._VoxelSizeX / reductionCoeff; targetVolume._VoxelSizeY = targetVolume._VoxelSizeY / reductionCoeff; targetVolume._VoxelSizeZ = targetVolume._VoxelSizeZ / reductionCoeff; memset(targetVolume._VolumeBuffer, 0, (size_t)targetVolume._Width * (size_t)targetVolume._Height * (size_t)targetVolume._Depth * sizeof(unsigned short)); resizeVolume_Uint16C1_MT((unsigned short*)inputVolume._VolumeBuffer, inputVolume._Width, inputVolume._Height, inputVolume._Depth, (unsigned short*)targetVolume._VolumeBuffer, targetVolume._Width, targetVolume._Height, targetVolume._Depth, reductionCoeff); } } }
20.330961
158
0.666025
[ "vector" ]
f3f4bc194aee8c51d622d86fc4132bf52253f5b0
16,896
cpp
C++
core/tests/src/TestMacrosTests.cpp
ishiko-cpp/tests
0b499e6fec22677c3727b39fe6a4d680011a75ce
[ "MIT" ]
null
null
null
core/tests/src/TestMacrosTests.cpp
ishiko-cpp/tests
0b499e6fec22677c3727b39fe6a4d680011a75ce
[ "MIT" ]
null
null
null
core/tests/src/TestMacrosTests.cpp
ishiko-cpp/tests
0b499e6fec22677c3727b39fe6a4d680011a75ce
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/tests/blob/main/LICENSE.txt */ #include "TestMacrosTests.h" #include "Ishiko/Tests/Core/TestMacros.hpp" #include "Ishiko/Tests/Core/TestProgressObserver.h" #include <Ishiko/Text.h> #include <sstream> using namespace Ishiko::Tests; using namespace Ishiko::Text; TestMacrosTests::TestMacrosTests(const TestNumber& number, const TestEnvironment& environment) : TestSequence(number, "Test macros tests", environment) { append<HeapAllocationErrorsTest>("ISHIKO_PASS test 1", PassMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL test 1", FailMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF test 1", FailIfMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF test 2", FailIfMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_NOT test 1", FailIfNotMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_NOT test 2", FailIfNotMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_EQ test 1", FailIfEqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_EQ test 2", FailIfEqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_NEQ test 1", FailIfNeqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_NEQ test 2", FailIfNeqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_STR_EQ test 1", FailIfStrEqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_STR_EQ test 2", FailIfStrEqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_STR_NEQ test 1", FailIfStrNeqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_STR_NEQ test 2", FailIfStrNeqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_NOT_CONTAIN test 1", FailIfNotContainMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_FAIL_IF_NOT_CONTAIN test 2", FailIfNotContainMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_ABORT test 1", AbortMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF test 1", AbortIfMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF test 2", AbortIfMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_NOT test 1", AbortIfNotMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_NOT test 2", AbortIfNotMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_EQ test 1", AbortIfEqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_EQ test 2", AbortIfEqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_NEQ test 1", AbortIfNeqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_NEQ test 2", AbortIfNeqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_STR_EQ test 1", AbortIfStrEqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_STR_EQ test 2", AbortIfStrEqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_STR_NEQ test 1", AbortIfStrNeqMacroTest1); append<HeapAllocationErrorsTest>("ISHIKO_ABORT_IF_STR_NEQ test 2", AbortIfStrNeqMacroTest2); append<HeapAllocationErrorsTest>("ISHIKO_SKIP test 1", SkipMacroTest1); } void TestMacrosTests::PassMacroTest1(Test& test) { Test myTest(TestNumber(), "PassMacroTest1", [](Test& test) { ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_PASS(); } void TestMacrosTests::FailMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailMacroTest1", [&canary](Test& test) { ISHIKO_FAIL(); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF(false); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF(true); canary = true; ISHIKO_PASS(); }); std::stringstream progressOutput; std::shared_ptr<TestProgressObserver> observer = std::make_shared<TestProgressObserver>(progressOutput); myTest.observers().add(observer); myTest.run(); std::vector<std::string> progressOutputLines = ASCII::GetLines(progressOutput.str()); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_ABORT_IF_NEQ(progressOutputLines.size(), 3); ISHIKO_FAIL_IF_NOT_CONTAIN(progressOutputLines[1], "ISHIKO_FAIL_IF(true) failed with actual value (true)"); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfNotMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfNotMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF_NOT(true); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfNotMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfNotMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF_NOT(false); canary = true; ISHIKO_PASS(); }); std::stringstream progressOutput; std::shared_ptr<TestProgressObserver> observer = std::make_shared<TestProgressObserver>(progressOutput); myTest.observers().add(observer); myTest.run(); std::vector<std::string> progressOutputLines = ASCII::GetLines(progressOutput.str()); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_ABORT_IF_NEQ(progressOutputLines.size(), 3); ISHIKO_FAIL_IF_NOT_CONTAIN(progressOutputLines[1], "ISHIKO_FAIL_IF_NOT(false) failed with actual value (false)"); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfEqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfEqMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF_EQ(0, 1); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfEqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfEqMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF_EQ(0, 0); canary = true; ISHIKO_PASS(); }); std::stringstream progressOutput; std::shared_ptr<TestProgressObserver> observer = std::make_shared<TestProgressObserver>(progressOutput); myTest.observers().add(observer); myTest.run(); std::vector<std::string> progressOutputLines = ASCII::GetLines(progressOutput.str()); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_ABORT_IF_NEQ(progressOutputLines.size(), 3); ISHIKO_FAIL_IF_NOT_CONTAIN(progressOutputLines[1], "ISHIKO_FAIL_IF_EQ(0, 0) failed with actual values (0, 0)"); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfNeqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfNeqMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF_NEQ(0, 0); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfNeqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfNeqMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF_NEQ(0, 1); canary = true; ISHIKO_PASS(); }); std::stringstream progressOutput; std::shared_ptr<TestProgressObserver> observer = std::make_shared<TestProgressObserver>(progressOutput); myTest.observers().add(observer); myTest.run(); std::vector<std::string> progressOutputLines = ASCII::GetLines(progressOutput.str()); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_ABORT_IF_NEQ(progressOutputLines.size(), 3); ISHIKO_FAIL_IF_NOT_CONTAIN(progressOutputLines[1], "ISHIKO_FAIL_IF_NEQ(0, 1) failed with actual values (0, 1)"); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfStrEqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfStrEqMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF_STR_EQ("a", "b"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfStrEqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfStrEqMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF_STR_EQ("a", "a"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfStrNeqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfStrNeqMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF_STR_NEQ("a", "a"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfStrNeqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfStrNeqMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF_STR_NEQ("a", "b"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfNotContainMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfNotContainMacroTest1", [&canary](Test& test) { ISHIKO_FAIL_IF_NOT_CONTAIN("abc", "b"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::FailIfNotContainMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "FailIfNotContainMacroTest2", [&canary](Test& test) { ISHIKO_FAIL_IF_NOT_CONTAIN("abc", "d"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortMacroTest1", [&canary](Test& test) { ISHIKO_ABORT(); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfMacroTest1", [&canary](Test& test) { ISHIKO_ABORT_IF(false); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfMacroTest2", [&canary](Test& test) { ISHIKO_ABORT_IF(true); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfNotMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfNotMacroTest1", [&canary](Test& test) { ISHIKO_ABORT_IF_NOT(true); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfNotMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfNotMacroTest2", [&canary](Test& test) { ISHIKO_ABORT_IF_NOT(false); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfEqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfEqMacroTest1", [&canary](Test& test) { ISHIKO_ABORT_IF_EQ(0, 1); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfEqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfEqMacroTest2", [&canary](Test& test) { ISHIKO_ABORT_IF_EQ(0, 0); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfNeqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfNeqMacroTest1", [&canary](Test& test) { ISHIKO_ABORT_IF_NEQ(0, 0); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfNeqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfNeqMacroTest2", [&canary](Test& test) { ISHIKO_ABORT_IF_NEQ(0, 1); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfStrEqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfStrEqMacroTest1", [&canary](Test& test) { ISHIKO_ABORT_IF_STR_EQ("a", "b"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfStrEqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfStrEqMacroTest2", [&canary](Test& test) { ISHIKO_ABORT_IF_STR_EQ("a", "a"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfStrNeqMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfStrNeqMacroTest1", [&canary](Test& test) { ISHIKO_ABORT_IF_STR_NEQ("a", "a"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::passed); ISHIKO_FAIL_IF_NOT(canary); ISHIKO_PASS(); } void TestMacrosTests::AbortIfStrNeqMacroTest2(Test& test) { bool canary = false; Test myTest(TestNumber(), "AbortIfStrNeqMacroTest2", [&canary](Test& test) { ISHIKO_ABORT_IF_STR_NEQ("a", "b"); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::failed); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); } void TestMacrosTests::SkipMacroTest1(Test& test) { bool canary = false; Test myTest(TestNumber(), "TestMacrosTests_SkipMacroTest1", [&canary](Test& test) { ISHIKO_SKIP(); canary = true; ISHIKO_PASS(); }); myTest.run(); ISHIKO_FAIL_IF_NEQ(myTest.result(), TestResult::skipped); ISHIKO_FAIL_IF(canary); ISHIKO_PASS(); }
25.953917
117
0.668205
[ "vector" ]
f3fca5b29f779dabeddaf0eeac66add4c7160df1
100,372
cpp
C++
test/slce.cpp
Fadis/slce
27c39928ce2a15186a4be84a182238f64a1cadc8
[ "MIT" ]
11
2019-05-06T16:28:04.000Z
2019-06-19T23:54:40.000Z
test/slce.cpp
Fadis/slce
27c39928ce2a15186a4be84a182238f64a1cadc8
[ "MIT" ]
1
2021-02-05T04:23:17.000Z
2021-02-17T06:36:41.000Z
test/slce.cpp
Fadis/slce
27c39928ce2a15186a4be84a182238f64a1cadc8
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Naomasa Matsubayashi * * 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. */ #define BOOST_TEST_MAIN #include <vector> #include <boost/test/included/unit_test.hpp> #include <slce/slce.hpp> struct base {}; struct inherited : public base {}; struct other {}; struct non_copyable { non_copyable( const non_copyable& ) = delete; non_copyable &operator=( const non_copyable& ) = delete; }; struct copyable { copyable( const copyable& ) = default; copyable &operator=( const copyable& ) = default; }; struct movable { movable( const movable& ) = delete; movable( movable&& ) = default; movable &operator=( const movable& ) = delete; movable &operator=( movable&& ) = default; }; struct partially_castable_t1 {}; struct partially_castable_t2 { partially_castable_t2( const partially_castable_t1& ) {} partially_castable_t2( partially_castable_t1&& ) {} partially_castable_t2 &operator=( const partially_castable_t1& ) { return *this; }; partially_castable_t2 &operator=( partially_castable_t1&& ) { return *this; }; operator partially_castable_t1() const { return partially_castable_t1(); } }; using fully_castable_t1 = inherited; using fully_castable_t2 = base; using default_constructible = base; struct constructible_with_int { constructible_with_int( int ) {} }; using destructible = base; class non_destructible { ~non_destructible() {} }; struct bool_like { bool_like( bool ) {} bool_like( bool_like&& ) {} bool_like &operator=( bool_like&& ) { return *this; } bool operator!() const { return false; } operator bool() const { return true; } }; bool operator&&( const bool_like&, bool ) { return true; } bool operator||( const bool_like&, bool ) { return true; } bool operator&&( bool, const bool_like& ) { return true; } bool operator||( bool, const bool_like& ) { return true; } bool operator&&( const bool_like&, const bool_like& ) { return true; } bool operator||( const bool_like&, const bool_like& ) { return true; } bool operator==( const bool_like&, bool ) { return true; } bool operator!=( const bool_like&, bool ) { return true; } bool operator==( bool, const bool_like& ) { return true; } bool operator!=( bool, const bool_like& ) { return true; } bool operator==( const bool_like&, const bool_like& ) { return true; } bool operator!=( const bool_like&, const bool_like& ) { return true; } bool operator&&( const volatile bool_like&, bool ) { return true; } bool operator||( const volatile bool_like&, bool ) { return true; } bool operator&&( bool, const volatile bool_like& ) { return true; } bool operator||( bool, const volatile bool_like& ) { return true; } bool operator&&( const volatile bool_like&, const volatile bool_like& ) { return true; } bool operator||( const volatile bool_like&, const volatile bool_like& ) { return true; } bool operator&&( const bool_like&, const volatile bool_like& ) { return true; } bool operator||( const bool_like&, const volatile bool_like& ) { return true; } bool operator&&( const volatile bool_like&, const bool_like& ) { return true; } bool operator||( const volatile bool_like&, const bool_like& ) { return true; } bool operator==( const volatile bool_like&, bool ) { return true; } bool operator!=( const volatile bool_like&, bool ) { return true; } bool operator==( bool, const volatile bool_like& ) { return true; } bool operator!=( bool, const volatile bool_like& ) { return true; } bool operator==( const volatile bool_like&, const volatile bool_like& ) { return true; } bool operator!=( const volatile bool_like&, const volatile bool_like& ) { return true; } bool operator==( const bool_like&, const volatile bool_like& ) { return true; } bool operator!=( const bool_like&, const volatile bool_like& ) { return true; } bool operator==( const volatile bool_like&, const bool_like& ) { return true; } bool operator!=( const volatile bool_like&, const bool_like& ) { return true; } using incomparable = base; struct comparable {}; struct comparable_inconvertible {}; struct comparable_convertible : public comparable {}; struct partially_comparable {}; bool operator&&( const comparable&, const comparable& ) { return true; } bool operator&&( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator&&( const comparable&, const comparable_inconvertible& ) { return true; } bool operator&&( const comparable_inconvertible&, const comparable& ) { return true; } bool operator&&( const comparable&, const partially_comparable& ) { return true; } bool operator&&( const partially_comparable&, const comparable& ) { return true; } bool operator||( const comparable&, const comparable& ) { return true; } bool operator||( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator||( const comparable&, const comparable_inconvertible& ) { return true; } bool operator||( const comparable_inconvertible&, const comparable& ) { return true; } bool operator||( const comparable&, const partially_comparable& ) { return true; } bool operator||( const partially_comparable&, const comparable& ) { return true; } bool operator==( const comparable&, const comparable& ) { return true; } bool operator==( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator==( const comparable&, const comparable_inconvertible& ) { return true; } bool operator==( const comparable_inconvertible&, const comparable& ) { return true; } bool operator==( const comparable&, const partially_comparable& ) { return true; } bool operator==( const partially_comparable&, const comparable& ) { return true; } bool operator!=( const comparable&, const comparable& ) { return true; } bool operator!=( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator!=( const comparable&, const comparable_inconvertible& ) { return true; } bool operator!=( const comparable_inconvertible&, const comparable& ) { return true; } bool operator!=( const comparable&, const partially_comparable& ) { return true; } bool operator!=( const partially_comparable&, const comparable& ) { return true; } bool operator<( const comparable&, const comparable& ) { return true; } bool operator<( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator<( const comparable&, const comparable_inconvertible& ) { return true; } bool operator<( const comparable_inconvertible&, const comparable& ) { return true; } bool operator<( const comparable&, const partially_comparable& ) { return true; } bool operator<( const partially_comparable&, const comparable& ) { return true; } bool operator>( const comparable&, const comparable& ) { return true; } bool operator>( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator>( const comparable&, const comparable_inconvertible& ) { return true; } bool operator>( const comparable_inconvertible&, const comparable& ) { return true; } bool operator>( const comparable&, const partially_comparable& ) { return true; } bool operator>( const partially_comparable&, const comparable& ) { return true; } bool operator<=( const comparable&, const comparable& ) { return true; } bool operator<=( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator<=( const comparable&, const comparable_inconvertible& ) { return true; } bool operator<=( const comparable_inconvertible&, const comparable& ) { return true; } bool operator<=( const comparable&, const partially_comparable& ) { return true; } bool operator<=( const partially_comparable&, const comparable& ) { return true; } bool operator>=( const comparable&, const comparable& ) { return true; } bool operator>=( const comparable_inconvertible&, const comparable_inconvertible& ) { return true; } bool operator>=( const comparable&, const comparable_inconvertible& ) { return true; } bool operator>=( const comparable_inconvertible&, const comparable& ) { return true; } bool operator>=( const comparable&, const partially_comparable& ) { return true; } bool operator>=( const partially_comparable&, const comparable& ) { return true; } bool operator&&( const volatile comparable&, const volatile comparable& ) { return true; } bool operator&&( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator&&( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator&&( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator&&( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator&&( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator||( const volatile comparable&, const volatile comparable& ) { return true; } bool operator||( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator||( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator||( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator||( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator||( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator==( const volatile comparable&, const volatile comparable& ) { return true; } bool operator==( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator==( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator==( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator==( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator==( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator!=( const volatile comparable&, const volatile comparable& ) { return true; } bool operator!=( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator!=( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator!=( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator!=( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator!=( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator<( const volatile comparable&, const volatile comparable& ) { return true; } bool operator<( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator<( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator<( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator<( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator<( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator>( const volatile comparable&, const volatile comparable& ) { return true; } bool operator>( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator>( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator>( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator>( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator>( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator<=( const volatile comparable&, const volatile comparable& ) { return true; } bool operator<=( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator<=( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator<=( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator<=( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator<=( const volatile partially_comparable&, const volatile comparable& ) { return true; } bool operator>=( const volatile comparable&, const volatile comparable& ) { return true; } bool operator>=( const volatile comparable_inconvertible&, const volatile comparable_inconvertible& ) { return true; } bool operator>=( const volatile comparable&, const volatile comparable_inconvertible& ) { return true; } bool operator>=( const volatile comparable_inconvertible&, const volatile comparable& ) { return true; } bool operator>=( const volatile comparable&, const volatile partially_comparable& ) { return true; } bool operator>=( const volatile partially_comparable&, const volatile comparable& ) { return true; } struct callable { int operator()( int a, int b ) { return a + b; }; }; struct predicate { bool operator()( const base&, const other& ) { return true; }; }; struct relation { bool operator()( const base&, const base& ) { return true; }; bool operator()( const other&, const other& ) { return true; }; bool operator()( const base&, const other& ) { return true; }; bool operator()( const other&, const base& ) { return true; }; }; struct implicit_input_iterator { using value_type = int; int operator*() const { return 0; } implicit_input_iterator &operator++() { return *this; } void operator++(int) {} }; bool operator==( const implicit_input_iterator&, const implicit_input_iterator& ) { return true; } bool operator!=( const implicit_input_iterator&, const implicit_input_iterator& ) { return false; } int operator-( const implicit_input_iterator&, const implicit_input_iterator& ) { return 0; } struct explicit_input_iterator { using value_type = int; using difference_type = int; using pointer = int*; using reference = int; int operator*() const { return 0; } explicit_input_iterator &operator++() { return *this; } void operator++(int) {} }; bool operator==( const explicit_input_iterator&, const explicit_input_iterator& ) { return true; } bool operator!=( const explicit_input_iterator&, const explicit_input_iterator& ) { return false; } int operator-( const explicit_input_iterator&, const explicit_input_iterator& ) { return 0; } using implicit_non_output_iterator = implicit_input_iterator; using explicit_non_output_iterator = explicit_input_iterator; struct implicit_forward_iterator { using value_type = int; int &operator*() const { static int value = 0; return value; } implicit_forward_iterator &operator++() { return *this; } implicit_forward_iterator operator++(int) { return *this; } }; bool operator==( const implicit_forward_iterator&, const implicit_forward_iterator& ) { return true; } bool operator!=( const implicit_forward_iterator&, const implicit_forward_iterator& ) { return false; } int operator-( const implicit_forward_iterator&, const implicit_forward_iterator& ) { return 0; } struct explicit_forward_iterator { using value_type = int; using difference_type = int; using pointer = int*; using reference = int&; int &operator*() const { static int value = 0; return value; } explicit_forward_iterator &operator++() { return *this; } explicit_forward_iterator operator++(int) { return *this; } }; using implicit_output_iterator = implicit_forward_iterator; using explicit_output_iterator = explicit_forward_iterator; bool operator==( const explicit_forward_iterator&, const explicit_forward_iterator& ) { return true; } bool operator!=( const explicit_forward_iterator&, const explicit_forward_iterator& ) { return false; } int operator-( const explicit_forward_iterator&, const explicit_forward_iterator& ) { return 0; } struct implicit_bidirectional_iterator { using value_type = int; int &operator*() const { static int value = 0; return value; } implicit_bidirectional_iterator &operator++() { return *this; } implicit_bidirectional_iterator operator++(int) { return *this; } implicit_bidirectional_iterator &operator--() { return *this; } implicit_bidirectional_iterator operator--(int) { return *this; } }; bool operator==( const implicit_bidirectional_iterator&, const implicit_bidirectional_iterator& ) { return true; } bool operator!=( const implicit_bidirectional_iterator&, const implicit_bidirectional_iterator& ) { return false; } int operator-( const implicit_bidirectional_iterator&, const implicit_bidirectional_iterator& ) { return 0; } struct explicit_bidirectional_iterator { using value_type = int; using difference_type = int; using pointer = int*; using reference = int&; int &operator*() const { static int value = 0; return value; } explicit_bidirectional_iterator &operator++() { return *this; } explicit_bidirectional_iterator operator++(int) { return *this; } explicit_bidirectional_iterator &operator--() { return *this; } explicit_bidirectional_iterator operator--(int) { return *this; } }; bool operator==( const explicit_bidirectional_iterator&, const explicit_bidirectional_iterator& ) { return true; } bool operator!=( const explicit_bidirectional_iterator&, const explicit_bidirectional_iterator& ) { return false; } int operator-( const explicit_bidirectional_iterator&, const explicit_bidirectional_iterator& ) { return 0; } struct implicit_random_access_iterator { using value_type = int; int &operator*() const { static int value = 0; return value; } int &operator[](int) const { static int value = 0; return value; } implicit_random_access_iterator &operator++() { return *this; } implicit_random_access_iterator operator++(int) { return *this; } implicit_random_access_iterator &operator+=(int) { return *this; } implicit_random_access_iterator &operator--() { return *this; } implicit_random_access_iterator operator--(int) { return *this; } implicit_random_access_iterator &operator-=(int) { return *this; } }; bool operator==( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return true; } bool operator!=( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return false; } bool operator<( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return false; } bool operator>( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return false; } bool operator<=( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return true; } bool operator>=( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return true; } int operator-( const implicit_random_access_iterator&, const implicit_random_access_iterator& ) { return 0; } implicit_random_access_iterator operator+( int, const implicit_random_access_iterator &a ) { return a; } implicit_random_access_iterator operator+( const implicit_random_access_iterator &a, int ) { return a; } implicit_random_access_iterator operator-( const implicit_random_access_iterator &a, int ) { return a; } struct explicit_random_access_iterator { using value_type = int; using difference_type = int; using pointer = int*; using reference = int&; int &operator*() const { static int value = 0; return value; } int &operator[](int) const { static int value = 0; return value; } explicit_random_access_iterator &operator++() { return *this; } explicit_random_access_iterator operator++(int) { return *this; } explicit_random_access_iterator &operator+=(int) { return *this; } explicit_random_access_iterator &operator--() { return *this; } explicit_random_access_iterator operator--(int) { return *this; } explicit_random_access_iterator &operator-=(int) { return *this; } }; bool operator==( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return true; } bool operator!=( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return false; } bool operator<( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return false; } bool operator>( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return false; } bool operator<=( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return true; } bool operator>=( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return true; } int operator-( const explicit_random_access_iterator&, const explicit_random_access_iterator& ) { return 0; } explicit_random_access_iterator operator+( int, const explicit_random_access_iterator &a ) { return a; } explicit_random_access_iterator operator+( const explicit_random_access_iterator &a, int ) { return a; } explicit_random_access_iterator operator-( const explicit_random_access_iterator &a, int ) { return a; } template< typename T > struct sentinel {}; template< typename T > bool operator==( const sentinel< T >&, const sentinel< T >& ) { return true; } template< typename T > bool operator==( const sentinel< T >&, const T& ) { return true; } template< typename T > bool operator==( const T&, const sentinel< T >& ) { return true; } template< typename T > bool operator!=( const sentinel< T >&, const sentinel< T >& ) { return false; } template< typename T > bool operator!=( const sentinel< T >&, const T& ) { return false; } template< typename T > bool operator!=( const T&, const sentinel< T >& ) { return false; } template< typename T > struct sized_sentinel {}; template< typename T > bool operator==( const sized_sentinel< T >&, const sized_sentinel< T >& ) { return true; } template< typename T > bool operator==( const sized_sentinel< T >&, const T& ) { return true; } template< typename T > bool operator==( const T&, const sized_sentinel< T >& ) { return true; } template< typename T > bool operator!=( const sized_sentinel< T >&, const sized_sentinel< T >& ) { return false; } template< typename T > bool operator!=( const sized_sentinel< T >&, const T& ) { return false; } template< typename T > bool operator!=( const T&, const sized_sentinel< T >& ) { return false; } template< typename T > auto operator-( const T &i, const sized_sentinel< T >& ) { return i - i; } template< typename T > auto operator-( const sized_sentinel< T >&, const T &i ) { return i - i; } BOOST_AUTO_TEST_CASE(Same) { BOOST_CHECK_EQUAL( ( slce::is_same< base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_same< base, inherited >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< inherited, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< other, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< const base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< volatile base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_same< int*, base >::value ), false ); } BOOST_AUTO_TEST_CASE(DerivedFrom) { BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, inherited >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, const base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, volatile base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< inherited, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< other, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< const base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< volatile base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_derived_from< int*, base >::value ), false ); } BOOST_AUTO_TEST_CASE(ConvertibleTo) { BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, inherited >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, const base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, volatile base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< inherited, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< other, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< const base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< volatile base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base&, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_convertible_to< int*, base >::value ), false ); } BOOST_AUTO_TEST_CASE(CommonReference) { BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, inherited >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, const base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, volatile base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, base& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< inherited, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< other, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< const base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< volatile base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base&, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common_reference< int*, base >::value ), false ); } BOOST_AUTO_TEST_CASE(Common) { BOOST_CHECK_EQUAL( ( slce::is_common< base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< base, inherited >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, const base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< base, volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, base& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< inherited, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< other, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< const base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< volatile base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< base&, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_common< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_common< int*, base >::value ), false ); } BOOST_AUTO_TEST_CASE(Integral) { BOOST_CHECK_EQUAL( ( slce::is_integral< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< inherited >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_integral< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_integral< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_integral< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< unsigned int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_integral< const unsigned int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_integral< volatile unsigned int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_integral< unsigned int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_integral< unsigned int* >::value ), false ); } BOOST_AUTO_TEST_CASE(SignedIntegral) { BOOST_CHECK_EQUAL( ( slce::is_signed_integral< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< inherited >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< unsigned int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< const unsigned int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< volatile unsigned int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< unsigned int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_signed_integral< unsigned int* >::value ), false ); } BOOST_AUTO_TEST_CASE(UnsignedIntegral) { BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< inherited >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< unsigned int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< const unsigned int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< volatile unsigned int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< unsigned int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_unsigned_integral< unsigned int* >::value ), false ); } BOOST_AUTO_TEST_CASE(Assignable) { BOOST_CHECK_EQUAL( ( slce::is_assignable< base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< const base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< volatile base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base&, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_assignable< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< int*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< non_copyable&, non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< copyable&, copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_assignable< movable&, movable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_assignable< partially_castable_t2&, partially_castable_t1 >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_assignable< fully_castable_t2&, fully_castable_t1 >::value ), true ); } BOOST_AUTO_TEST_CASE(Swappable) { BOOST_CHECK_EQUAL( ( slce::is_swappable< base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable< volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable< base& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< base* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable< copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable< movable >::value ), true ); } BOOST_AUTO_TEST_CASE(SwappableWith) { BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, base& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, volatile int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< const base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< volatile base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base&, base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< base*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< const int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< volatile int, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< int&, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< int*, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< non_copyable, non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< copyable, copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< movable, movable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< partially_castable_t2, partially_castable_t1 >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_swappable_with< fully_castable_t2, fully_castable_t1 >::value ), false ); } BOOST_AUTO_TEST_CASE(Destructible) { BOOST_CHECK_EQUAL( ( slce::is_destructible< destructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< const destructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< volatile destructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< destructible& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< destructible* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< non_destructible >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_destructible< const non_destructible >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_destructible< volatile non_destructible >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_destructible< non_destructible& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< non_destructible* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< constructible_with_int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< const constructible_with_int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< volatile constructible_with_int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< constructible_with_int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_destructible< constructible_with_int* >::value ), true ); } BOOST_AUTO_TEST_CASE(Constructible) { BOOST_CHECK_EQUAL( ( slce::is_constructible< default_constructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< const default_constructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< volatile default_constructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< default_constructible& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< default_constructible* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< default_constructible, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< const default_constructible, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< volatile default_constructible, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< default_constructible&, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< default_constructible*, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< const int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< volatile int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< int&, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< int*, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< constructible_with_int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< const constructible_with_int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< volatile constructible_with_int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< constructible_with_int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< constructible_with_int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< constructible_with_int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< const constructible_with_int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< volatile constructible_with_int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_constructible< constructible_with_int&, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_constructible< constructible_with_int*, int >::value ), false ); } BOOST_AUTO_TEST_CASE(DefaultConstructible) { BOOST_CHECK_EQUAL( ( slce::is_default_constructible< default_constructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< const default_constructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< volatile default_constructible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< default_constructible& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< default_constructible* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< constructible_with_int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< const constructible_with_int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< volatile constructible_with_int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< constructible_with_int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_default_constructible< constructible_with_int* >::value ), true ); } BOOST_AUTO_TEST_CASE(CopyConstructible) { BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< const copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< volatile copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< copyable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< const non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< volatile non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< non_copyable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< non_copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< const movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< volatile movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< movable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copy_constructible< movable* >::value ), true ); } BOOST_AUTO_TEST_CASE(MoveConstructible) { BOOST_CHECK_EQUAL( ( slce::is_move_constructible< copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< const copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< volatile copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< copyable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< int* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< const non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< volatile non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< non_copyable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< non_copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< movable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< const movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< volatile movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< movable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_move_constructible< movable* >::value ), true ); } BOOST_AUTO_TEST_CASE(Boolean) { BOOST_CHECK_EQUAL( ( slce::is_boolean< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< volatile base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< base* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< bool >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< const bool >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< volatile bool >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< bool& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< bool* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< bool_like >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< const bool_like >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< volatile bool_like >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_boolean< bool_like& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_boolean< bool_like* >::value ), false ); } BOOST_AUTO_TEST_CASE(EqualityComparable) { BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< const comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< volatile comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< comparable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< comparable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< comparable_inconvertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< const comparable_inconvertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< volatile comparable_inconvertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< comparable_inconvertible& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< comparable_inconvertible* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< partially_comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< const partially_comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< volatile partially_comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< partially_comparable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< partially_comparable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(EqualityComparableWith) { BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, const comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, volatile comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, comparable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, comparable* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< const comparable, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< volatile comparable, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable&, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable*, comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, comparable_inconvertible >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable_inconvertible, comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, comparable_convertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable_convertible, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< incomparable, incomparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< comparable, incomparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< incomparable, comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int, const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int, volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int, int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< const int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< volatile int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int&, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_equality_comparable_with< int*, int >::value ), false ); } BOOST_AUTO_TEST_CASE(StrictTotallyOrdered) { BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< const comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< volatile comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< comparable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< comparable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< comparable_inconvertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< const comparable_inconvertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< volatile comparable_inconvertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< comparable_inconvertible& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< comparable_inconvertible* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< partially_comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< const partially_comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< volatile partially_comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< partially_comparable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< partially_comparable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(StrictTotallyOrderedWith) { BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, const comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, volatile comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, comparable& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, comparable* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< const comparable, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< volatile comparable, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable&, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable*, comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, comparable_inconvertible >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable_inconvertible, comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, comparable_convertible >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable_convertible, comparable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< incomparable, incomparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< comparable, incomparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< incomparable, comparable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int, const int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int, volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int, int& >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int, int* >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< const int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< volatile int, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int&, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_strict_totally_ordered_with< int*, int >::value ), false ); } BOOST_AUTO_TEST_CASE(Movable) { BOOST_CHECK_EQUAL( ( slce::is_movable< base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< volatile base >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_movable< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< base* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< const copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< volatile copyable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_movable< copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< movable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< const movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< volatile movable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_movable< movable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< movable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< const non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< volatile non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< non_copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< non_copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_movable< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_movable< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(Copyable) { BOOST_CHECK_EQUAL( ( slce::is_copyable< base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< volatile base >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_copyable< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< base* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< copyable >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< const copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< volatile copyable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_copyable< copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< const movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< volatile movable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_copyable< movable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< movable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< const non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< volatile non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< non_copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< non_copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_copyable< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_copyable< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(Semiregular) { BOOST_CHECK_EQUAL( ( slce::is_semiregular< base >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< volatile base >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_semiregular< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< base* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< const copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< volatile copyable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_semiregular< copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< const movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< volatile movable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_semiregular< movable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< movable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< const non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< volatile non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< non_copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< non_copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_semiregular< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(Regular) { BOOST_CHECK_EQUAL( ( slce::is_regular< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< const base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< volatile base >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_regular< base& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< base* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular< copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< const copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< volatile copyable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_regular< copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular< movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< const movable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< volatile movable >::value ), false ); // BOOST_CHECK_EQUAL( ( slce::is_regular< movable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< movable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular< non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< const non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< volatile non_copyable >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< non_copyable& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< non_copyable* >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular< int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular< const int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< volatile int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular< int& >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(Invocable) { #ifdef __cpp_lib_invoke BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)() >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)(), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)( int ), int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_invocable< callable, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< callable, int, int >::value ), true ); #else BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)() >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)(), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< void(*)( int ), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< callable, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_invocable< callable, int, int >::value ), false ); #endif } BOOST_AUTO_TEST_CASE(RegularInvocable) { #ifdef __cpp_lib_invoke BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)() >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)(), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)( int ), int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< callable, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< callable, int, int >::value ), true ); #else BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)() >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)(), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< void(*)( int ), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< callable, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_regular_invocable< callable, int, int >::value ), false ); #endif } BOOST_AUTO_TEST_CASE(Predicate) { #ifdef __cpp_lib_invoke BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)() >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)(), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)( int ), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< bool(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< bool(*)( int ), int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_predicate< callable, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< callable, int, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< predicate, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< predicate, base, other >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_predicate< relation, base, other >::value ), true ); #else BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)() >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)(), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< void(*)( int ), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< bool(*)( int ) >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< bool(*)( int ), int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< callable, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< callable, int, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< predicate, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< predicate, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_predicate< relation, base, other >::value ), false ); #endif } BOOST_AUTO_TEST_CASE(Relation) { #ifdef __cpp_lib_invoke BOOST_CHECK_EQUAL( ( slce::is_relation< callable, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_relation< predicate, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_relation< relation, base, other >::value ), true ); #else BOOST_CHECK_EQUAL( ( slce::is_relation< callable, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_relation< predicate, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_relation< relation, base, other >::value ), false ); #endif } BOOST_AUTO_TEST_CASE(StrictWeakOrder) { #ifdef __cpp_lib_invoke BOOST_CHECK_EQUAL( ( slce::is_strict_weak_order< callable, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_weak_order< predicate, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_weak_order< relation, base, other >::value ), true ); #else BOOST_CHECK_EQUAL( ( slce::is_strict_weak_order< callable, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_weak_order< predicate, base, other >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_strict_weak_order< relation, base, other >::value ), false ); #endif } BOOST_AUTO_TEST_CASE(Cpp17Iterator) { BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_iterator< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Cpp17InputIterator) { BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_input_iterator< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Cpp17ForwardIterator) { BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_forward_iterator< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Cpp17BidirectionalIterator) { BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< explicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< implicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_bidirectional_iterator< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Cpp17RandomAccessIterator) { BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< explicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< implicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< explicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< implicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::detail::is_cpp17_random_access_iterator< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Readable) { BOOST_CHECK_EQUAL( ( slce::is_readable< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_readable< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_readable< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_readable< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_readable< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_readable< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_readable< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Writable) { BOOST_CHECK_EQUAL( ( slce::is_writable< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_writable< explicit_forward_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_writable< implicit_forward_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_writable< explicit_bidirectional_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_writable< implicit_bidirectional_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_writable< explicit_random_access_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_writable< implicit_random_access_iterator, int >::value ), true ); } BOOST_AUTO_TEST_CASE(WeaklyIncrementable) { BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_weakly_incrementable< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Incrementable) { BOOST_CHECK_EQUAL( ( slce::is_incrementable< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_incrementable< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_incrementable< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_incrementable< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_incrementable< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_incrementable< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_incrementable< implicit_random_access_iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(Iterator) { BOOST_CHECK_EQUAL( ( slce::is_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< explicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< implicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_iterator< sentinel< explicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< sentinel< implicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< sentinel< explicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< sentinel< implicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< sentinel< explicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< sentinel< implicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_iterator< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(Sentinel) { BOOST_CHECK_EQUAL( ( slce::is_sentinel< base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< explicit_input_iterator, explicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< implicit_input_iterator, implicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< explicit_forward_iterator, explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< implicit_forward_iterator, implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< explicit_bidirectional_iterator, explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< implicit_bidirectional_iterator, implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< explicit_random_access_iterator, explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< implicit_random_access_iterator, implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< explicit_forward_iterator >, explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< implicit_forward_iterator >, implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< explicit_bidirectional_iterator >, explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< implicit_bidirectional_iterator >, implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< explicit_random_access_iterator >, explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< implicit_random_access_iterator >, implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sentinel< sentinel< int* >, int* >::value ), true ); } BOOST_AUTO_TEST_CASE(SizedSentinel) { BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< base, base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< explicit_input_iterator, explicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< implicit_input_iterator, implicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< explicit_forward_iterator, explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< implicit_forward_iterator, implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< explicit_bidirectional_iterator, explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< implicit_bidirectional_iterator, implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< explicit_random_access_iterator, explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< implicit_random_access_iterator, implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sentinel< explicit_forward_iterator >, explicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sentinel< implicit_forward_iterator >, implicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sentinel< explicit_bidirectional_iterator >, explicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sentinel< implicit_bidirectional_iterator >, implicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sentinel< explicit_random_access_iterator >, explicit_random_access_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sentinel< implicit_random_access_iterator >, implicit_random_access_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< explicit_forward_iterator >, explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< implicit_forward_iterator >, implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< explicit_bidirectional_iterator >, explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< implicit_bidirectional_iterator >, implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< explicit_random_access_iterator >, explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< implicit_random_access_iterator >, implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_sized_sentinel< sized_sentinel< int* >, int* >::value ), true ); } BOOST_AUTO_TEST_CASE(InputIterator) { BOOST_CHECK_EQUAL( ( slce::is_input_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< explicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< implicit_input_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< sentinel< explicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< sentinel< implicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< sentinel< explicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< sentinel< implicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< sentinel< explicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< sentinel< implicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_input_iterator< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(OutputIterator) { BOOST_CHECK_EQUAL( ( slce::is_output_iterator< base, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< explicit_output_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< implicit_output_iterator, int >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< explicit_non_output_iterator, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< implicit_non_output_iterator, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< sentinel< explicit_output_iterator >, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< sentinel< implicit_output_iterator >, int >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_output_iterator< int*, int >::value ), true ); } BOOST_AUTO_TEST_CASE(ForwardIterator) { BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< explicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< implicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< explicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< implicit_forward_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< sentinel< explicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< sentinel< implicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< sentinel< explicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< sentinel< implicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< sentinel< explicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< sentinel< implicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_forward_iterator< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(BidirectionalIterator) { BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< explicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< implicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< explicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< implicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< explicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< implicit_bidirectional_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< sentinel< explicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< sentinel< implicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< sentinel< explicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< sentinel< implicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< sentinel< explicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< sentinel< implicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_bidirectional_iterator< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(RandomAccessIterator) { BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< explicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< implicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< explicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< implicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< explicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< implicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< explicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< implicit_random_access_iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< sentinel< explicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< sentinel< implicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< sentinel< explicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< sentinel< implicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< sentinel< explicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< sentinel< implicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_random_access_iterator< int* >::value ), true ); } BOOST_AUTO_TEST_CASE(ContiguousIterator) { BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< base >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< explicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< implicit_input_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< explicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< implicit_forward_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< explicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< implicit_bidirectional_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< explicit_random_access_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< implicit_random_access_iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< sentinel< explicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< sentinel< implicit_forward_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< sentinel< explicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< sentinel< implicit_bidirectional_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< sentinel< explicit_random_access_iterator > >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< sentinel< implicit_random_access_iterator > >::value ), false ); #ifdef __cpp_lib_ranges BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< int* >::value ), true ); #else BOOST_CHECK_EQUAL( ( slce::is_contiguous_iterator< int* >::value ), false ); #endif } BOOST_AUTO_TEST_CASE(IndirectlyMovable) { BOOST_CHECK_EQUAL( ( slce::is_indirectly_movable< typename std::vector< non_copyable >::iterator, typename std::vector< non_copyable >::iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_movable< typename std::vector< movable >::iterator, typename std::vector< movable >::iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_movable< typename std::vector< copyable >::iterator, typename std::vector< copyable >::iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(IndirectlyCopyable) { BOOST_CHECK_EQUAL( ( slce::is_indirectly_copyable< typename std::vector< non_copyable >::iterator, typename std::vector< non_copyable >::iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_copyable< typename std::vector< movable >::iterator, typename std::vector< movable >::iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_copyable< typename std::vector< copyable >::iterator, typename std::vector< copyable >::iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(IndirectlyCopyableStorable) { BOOST_CHECK_EQUAL( ( slce::is_indirectly_copyable_storable< typename std::vector< non_copyable >::iterator, typename std::vector< non_copyable >::iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_copyable_storable< typename std::vector< movable >::iterator, typename std::vector< movable >::iterator >::value ), false ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_copyable_storable< typename std::vector< copyable >::iterator, typename std::vector< copyable >::iterator >::value ), true ); } BOOST_AUTO_TEST_CASE(IndirectlySwappable) { BOOST_CHECK_EQUAL( ( slce::is_indirectly_swappable< typename std::vector< non_copyable >::iterator, typename std::vector< non_copyable >::iterator >::value ), false ); #ifdef __cpp_lib_ranges BOOST_CHECK_EQUAL( ( slce::is_indirectly_swappable< typename std::vector< movable >::iterator, typename std::vector< movable >::iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_swappable< typename std::vector< copyable >::iterator, typename std::vector< copyable >::iterator >::value ), true ); BOOST_CHECK_EQUAL( ( slce::is_indirectly_swappable< typename std::vector< base >::iterator, typename std::vector< base >::iterator >::value ), true ); #endif }
69.654407
177
0.73658
[ "vector" ]
f3fda30e65b692b880ee1afc47ff0578eaba3a48
4,669
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/statusbar/policy/BatteryController.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/statusbar/policy/BatteryController.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/statusbar/policy/BatteryController.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/systemui/statusbar/policy/BatteryController.h" #include "elastos/droid/systemui/statusbar/policy/CBatteryControllerBroadcastReceiver.h" #include "Elastos.Droid.Os.h" #include "Elastos.CoreLibrary.IO.h" #include "Elastos.CoreLibrary.Utility.h" #include <elastos/utility/logging/Logger.h> using Elastos::Droid::Content::CIntentFilter; using Elastos::Droid::Content::IBroadcastReceiver; using Elastos::Droid::Content::IIntentFilter; using Elastos::Droid::Os::IBatteryManager; using Elastos::Utility::CArrayList; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace SystemUI { namespace StatusBar { namespace Policy { const String BatteryController::TAG("BatteryController"); const Boolean BatteryController::DEBUG = Logger::IsLoggable(TAG, Logger::___DEBUG); CAR_INTERFACE_IMPL(BatteryController, Object, IBatteryController) BatteryController::BatteryController( /* [in] */ IContext* context) { CArrayList::New((IArrayList**)&mChangeCallbacks); AutoPtr<IInterface> obj; context->GetSystemService(IContext::POWER_SERVICE, (IInterface**)&obj); mPowerManager = IPowerManager::Probe(obj); AutoPtr<IIntentFilter> filter; CIntentFilter::New((IIntentFilter**)&filter); filter->AddAction(IIntent::ACTION_BATTERY_CHANGED); filter->AddAction(IPowerManager::ACTION_POWER_SAVE_MODE_CHANGED); filter->AddAction(IPowerManager::ACTION_POWER_SAVE_MODE_CHANGING); AutoPtr<IBroadcastReceiver> b; CBatteryControllerBroadcastReceiver::New(this, (IBroadcastReceiver**)&b); AutoPtr<IIntent> intent; context->RegisterReceiver(b, filter, (IIntent**)&intent); UpdatePowerSave(); } ECode BatteryController::Dump( /* [in] */ IFileDescriptor* fd, /* [in] */ IPrintWriter* pw, /* [in] */ ArrayOf<String>* args) { pw->Println(String("BatteryController state:")); pw->Print(String(" mLevel=")); pw->Println(mLevel); pw->Print(String(" mPluggedIn=")); pw->Println(mPluggedIn); pw->Print(String(" mCharging=")); pw->Println(mCharging); pw->Print(String(" mCharged=")); pw->Println(mCharged); pw->Print(String(" mPowerSave=")); pw->Println(mPowerSave); return NOERROR; } ECode BatteryController::AddStateChangedCallback( /* [in] */ IBatteryStateChangeCallback* cb) { mChangeCallbacks->Add(cb); cb->OnBatteryLevelChanged(mLevel, mPluggedIn, mCharging); return NOERROR; } ECode BatteryController::RemoveStateChangedCallback( /* [in] */ IBatteryStateChangeCallback* cb) { mChangeCallbacks->Remove(cb); return NOERROR; } ECode BatteryController::IsPowerSave( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mPowerSave; return NOERROR; } void BatteryController::UpdatePowerSave() { Boolean tmp = FALSE; SetPowerSave((mPowerManager->IsPowerSaveMode(&tmp), tmp)); } void BatteryController::SetPowerSave( /* [in] */ Boolean powerSave) { if (powerSave == mPowerSave) return; mPowerSave = powerSave; if (DEBUG) Logger::D(TAG, "Power save is %s", (mPowerSave ? "on" : "off")); FirePowerSaveChanged(); } void BatteryController::FireBatteryLevelChanged() { Int32 N = 0; mChangeCallbacks->GetSize(&N); for (Int32 i = 0; i < N; i++) { AutoPtr<IInterface> obj; mChangeCallbacks->Get(i, (IInterface**)&obj); IBatteryStateChangeCallback::Probe(obj)->OnBatteryLevelChanged(mLevel, mPluggedIn, mCharging); } } void BatteryController::FirePowerSaveChanged() { Int32 N = 0; mChangeCallbacks->GetSize(&N); for (Int32 i = 0; i < N; i++) { AutoPtr<IInterface> obj; mChangeCallbacks->Get(i, (IInterface**)&obj); IBatteryStateChangeCallback::Probe(obj)->OnPowerSaveChanged(); } } } // namespace Policy } // namespace StatusBar } // namespace SystemUI } // namespace Droid } // namespace Elastos
31.979452
102
0.689227
[ "object" ]
6d0013a50b89289f9d6d19295f4abaede10e4b5b
7,205
cc
C++
content/shell/browser/shell_devtools_manager_delegate.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
content/shell/browser/shell_devtools_manager_delegate.cc
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
content/shell/browser/shell_devtools_manager_delegate.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2013 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 "content/shell/browser/shell_devtools_manager_delegate.h" #include <stdint.h> #include <vector> #include "base/atomicops.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_agent_host_client_channel.h" #include "content/public/browser/devtools_socket_factory.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/common/user_agent.h" #include "content/shell/browser/shell.h" #include "content/shell/common/shell_content_client.h" #include "content/shell/common/shell_switches.h" #include "content/shell/grit/shell_resources.h" #include "net/base/net_errors.h" #include "net/log/net_log_source.h" #include "net/socket/tcp_server_socket.h" #include "ui/base/resource/resource_bundle.h" #if !defined(OS_ANDROID) #include "content/public/browser/devtools_frontend_host.h" #endif #if defined(OS_ANDROID) #include "content/public/browser/android/devtools_auth.h" #include "net/socket/unix_domain_server_socket_posix.h" #endif namespace content { namespace { const int kBackLog = 10; base::subtle::Atomic32 g_last_used_port; #if defined(OS_ANDROID) class UnixDomainServerSocketFactory : public content::DevToolsSocketFactory { public: explicit UnixDomainServerSocketFactory(const std::string& socket_name) : socket_name_(socket_name) {} private: // content::DevToolsSocketFactory. std::unique_ptr<net::ServerSocket> CreateForHttpServer() override { std::unique_ptr<net::UnixDomainServerSocket> socket( new net::UnixDomainServerSocket( base::BindRepeating(&CanUserConnectToDevTools), true /* use_abstract_namespace */)); if (socket->BindAndListen(socket_name_, kBackLog) != net::OK) return nullptr; return std::move(socket); } std::unique_ptr<net::ServerSocket> CreateForTethering( std::string* out_name) override { return nullptr; } std::string socket_name_; DISALLOW_COPY_AND_ASSIGN(UnixDomainServerSocketFactory); }; #else class TCPServerSocketFactory : public content::DevToolsSocketFactory { public: TCPServerSocketFactory(const std::string& address, uint16_t port) : address_(address), port_(port) {} private: // content::DevToolsSocketFactory. std::unique_ptr<net::ServerSocket> CreateForHttpServer() override { std::unique_ptr<net::ServerSocket> socket( new net::TCPServerSocket(nullptr, net::NetLogSource())); if (socket->ListenWithAddressAndPort(address_, port_, kBackLog) != net::OK) return nullptr; net::IPEndPoint endpoint; if (socket->GetLocalAddress(&endpoint) == net::OK) base::subtle::NoBarrier_Store(&g_last_used_port, endpoint.port()); return socket; } std::unique_ptr<net::ServerSocket> CreateForTethering( std::string* out_name) override { return nullptr; } std::string address_; uint16_t port_; DISALLOW_COPY_AND_ASSIGN(TCPServerSocketFactory); }; #endif std::unique_ptr<content::DevToolsSocketFactory> CreateSocketFactory() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); #if defined(OS_ANDROID) std::string socket_name = "content_shell_devtools_remote"; if (command_line.HasSwitch(switches::kRemoteDebuggingSocketName)) { socket_name = command_line.GetSwitchValueASCII( switches::kRemoteDebuggingSocketName); } return std::unique_ptr<content::DevToolsSocketFactory>( new UnixDomainServerSocketFactory(socket_name)); #else // See if the user specified a port on the command line (useful for // automation). If not, use an ephemeral port by specifying 0. uint16_t port = 0; if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) { int temp_port; std::string port_str = command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort); if (base::StringToInt(port_str, &temp_port) && temp_port >= 0 && temp_port < 65535) { port = static_cast<uint16_t>(temp_port); } else { DLOG(WARNING) << "Invalid http debugger port number " << temp_port; } } return std::unique_ptr<content::DevToolsSocketFactory>( new TCPServerSocketFactory("127.0.0.1", port)); #endif } } // namespace // ShellDevToolsManagerDelegate ---------------------------------------------- // static int ShellDevToolsManagerDelegate::GetHttpHandlerPort() { return base::subtle::NoBarrier_Load(&g_last_used_port); } // static void ShellDevToolsManagerDelegate::StartHttpHandler( BrowserContext* browser_context) { std::string frontend_url; DevToolsAgentHost::StartRemoteDebuggingServer( CreateSocketFactory(), browser_context->GetPath(), base::FilePath()); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kRemoteDebuggingPipe)) DevToolsAgentHost::StartRemoteDebuggingPipeHandler(base::OnceClosure()); } // static void ShellDevToolsManagerDelegate::StopHttpHandler() { DevToolsAgentHost::StopRemoteDebuggingServer(); } ShellDevToolsManagerDelegate::ShellDevToolsManagerDelegate( BrowserContext* browser_context) : browser_context_(browser_context) { } ShellDevToolsManagerDelegate::~ShellDevToolsManagerDelegate() { } BrowserContext* ShellDevToolsManagerDelegate::GetDefaultBrowserContext() { return browser_context_; } void ShellDevToolsManagerDelegate::ClientAttached( content::DevToolsAgentHostClientChannel* channel) { // Make sure we don't receive notifications twice for the same client. CHECK(clients_.find(channel->GetClient()) == clients_.end()); clients_.insert(channel->GetClient()); } void ShellDevToolsManagerDelegate::ClientDetached( content::DevToolsAgentHostClientChannel* channel) { clients_.erase(channel->GetClient()); } scoped_refptr<DevToolsAgentHost> ShellDevToolsManagerDelegate::CreateNewTarget(const GURL& url) { Shell* shell = Shell::CreateNewWindow(browser_context_, url, nullptr, Shell::GetShellDefaultSize()); return DevToolsAgentHost::GetOrCreateFor(shell->web_contents()); } std::string ShellDevToolsManagerDelegate::GetDiscoveryPageHTML() { #if defined(OS_ANDROID) return std::string(); #else return ui::ResourceBundle::GetSharedInstance().LoadDataResourceString( IDR_CONTENT_SHELL_DEVTOOLS_DISCOVERY_PAGE); #endif } bool ShellDevToolsManagerDelegate::HasBundledFrontendResources() { #if defined(OS_ANDROID) return false; #else return true; #endif } } // namespace content
32.165179
79
0.755031
[ "vector" ]
6d07ba23b3fb923c5217481177b4cae785216d0a
4,334
cpp
C++
src/org/apache/poi/sl/draw/geom/CustomGeometry.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/geom/CustomGeometry.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/geom/CustomGeometry.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/sl/draw/geom/CustomGeometry.java #include <org/apache/poi/sl/draw/geom/CustomGeometry.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/util/ArrayList.hpp> #include <java/util/Iterator.hpp> #include <java/util/List.hpp> #include <org/apache/poi/sl/draw/binding/CTCustomGeometry2D.hpp> #include <org/apache/poi/sl/draw/binding/CTGeomGuide.hpp> #include <org/apache/poi/sl/draw/binding/CTGeomGuideList.hpp> #include <org/apache/poi/sl/draw/binding/CTGeomRect.hpp> #include <org/apache/poi/sl/draw/binding/CTPath2D.hpp> #include <org/apache/poi/sl/draw/binding/CTPath2DList.hpp> #include <org/apache/poi/sl/draw/geom/AdjustValue.hpp> #include <org/apache/poi/sl/draw/geom/ClosePathCommand.hpp> #include <org/apache/poi/sl/draw/geom/Guide.hpp> #include <org/apache/poi/sl/draw/geom/LineToCommand.hpp> #include <org/apache/poi/sl/draw/geom/MoveToCommand.hpp> #include <org/apache/poi/sl/draw/geom/Path.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::sl::draw::geom::CustomGeometry::CustomGeometry(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::sl::draw::geom::CustomGeometry::CustomGeometry(::poi::sl::draw::binding::CTCustomGeometry2D* geom) : CustomGeometry(*static_cast< ::default_init_tag* >(0)) { ctor(geom); } void poi::sl::draw::geom::CustomGeometry::init() { adjusts = new ::java::util::ArrayList(); guides = new ::java::util::ArrayList(); paths = new ::java::util::ArrayList(); } void poi::sl::draw::geom::CustomGeometry::ctor(::poi::sl::draw::binding::CTCustomGeometry2D* geom) { super::ctor(); init(); auto avLst = npc(geom)->getAvLst(); if(avLst != nullptr) { for (auto _i = npc(npc(avLst)->getGd())->iterator(); _i->hasNext(); ) { ::poi::sl::draw::binding::CTGeomGuide* gd = java_cast< ::poi::sl::draw::binding::CTGeomGuide* >(_i->next()); { npc(adjusts)->add(static_cast< ::java::lang::Object* >(new AdjustValue(gd))); } } } auto gdLst = npc(geom)->getGdLst(); if(gdLst != nullptr) { for (auto _i = npc(npc(gdLst)->getGd())->iterator(); _i->hasNext(); ) { ::poi::sl::draw::binding::CTGeomGuide* gd = java_cast< ::poi::sl::draw::binding::CTGeomGuide* >(_i->next()); { npc(guides)->add(static_cast< ::java::lang::Object* >(new Guide(gd))); } } } auto pathLst = npc(geom)->getPathLst(); if(pathLst != nullptr) { for (auto _i = npc(npc(pathLst)->getPath())->iterator(); _i->hasNext(); ) { ::poi::sl::draw::binding::CTPath2D* spPath = java_cast< ::poi::sl::draw::binding::CTPath2D* >(_i->next()); { npc(paths)->add(static_cast< ::java::lang::Object* >(new Path(spPath))); } } } auto rect = npc(geom)->getRect(); if(rect != nullptr) { textBounds = new Path(); npc(textBounds)->addCommand(new MoveToCommand(npc(rect)->getL(), npc(rect)->getT())); npc(textBounds)->addCommand(new LineToCommand(npc(rect)->getR(), npc(rect)->getT())); npc(textBounds)->addCommand(new LineToCommand(npc(rect)->getR(), npc(rect)->getB())); npc(textBounds)->addCommand(new LineToCommand(npc(rect)->getL(), npc(rect)->getB())); npc(textBounds)->addCommand(new ClosePathCommand()); } } java::util::Iterator* poi::sl::draw::geom::CustomGeometry::iterator() { return npc(paths)->iterator(); } poi::sl::draw::geom::Path* poi::sl::draw::geom::CustomGeometry::getTextBounds() { return textBounds; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::sl::draw::geom::CustomGeometry::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.sl.draw.geom.CustomGeometry", 42); return c; } java::lang::Class* poi::sl::draw::geom::CustomGeometry::getClass0() { return class_(); }
35.235772
120
0.639825
[ "object" ]
6d0a819576b3324cc527ca36cbc33f1fc22cbf2e
5,663
cpp
C++
Granite/renderer/common_renderer_data.cpp
dmrlawson/parallel-rdp
f18e00728bb45e3a769ab7ad3b9064359ef82209
[ "MIT" ]
null
null
null
Granite/renderer/common_renderer_data.cpp
dmrlawson/parallel-rdp
f18e00728bb45e3a769ab7ad3b9064359ef82209
[ "MIT" ]
null
null
null
Granite/renderer/common_renderer_data.cpp
dmrlawson/parallel-rdp
f18e00728bb45e3a769ab7ad3b9064359ef82209
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * 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 "common_renderer_data.hpp" #include "mesh_util.hpp" #include "muglm/muglm_impl.hpp" #include <random> namespace Granite { PersistentFrameEvent::PersistentFrameEvent() { EVENT_MANAGER_REGISTER(PersistentFrameEvent, on_frame_time, FrameTickEvent); } bool PersistentFrameEvent::on_frame_time(const FrameTickEvent &tick) { frame_time = float(tick.get_frame_time()); return true; } LightMesh::LightMesh() { EVENT_MANAGER_REGISTER_LATCH(LightMesh, on_device_created, on_device_destroyed, Vulkan::DeviceCreatedEvent); } void LightMesh::create_point_mesh(const Vulkan::DeviceCreatedEvent &e) { auto mesh = create_sphere_mesh(3); Vulkan::BufferCreateInfo info = {}; info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; info.size = mesh.positions.size() * sizeof(mesh.positions[0]); info.domain = Vulkan::BufferDomain::Device; point_vbo = e.get_device().create_buffer(info, mesh.positions.data()); info.size = mesh.indices.size() * sizeof(uint16_t); info.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT; point_ibo = e.get_device().create_buffer(info, mesh.indices.data()); point_count = mesh.indices.size(); } void LightMesh::create_spot_mesh(const Vulkan::DeviceCreatedEvent &e) { vec3 positions[16 + 2]; positions[0] = vec3(0.0f); positions[1] = vec3(0.0f, 0.0f, -1.0f); float half_angle = 2.0f * pi<float>() / 32.0f; float padding_mod = 1.0f / cos(half_angle); // Make sure top and bottom are aligned to 1 so we can get correct culling checks, // rotate the mesh by half phase so we get a "flat" top and "flat" side. for (unsigned i = 0; i < 16; i++) { float rad = 2.0f * pi<float>() * (i + 0.5f) / 16.0f; positions[i + 2] = vec3(padding_mod * cos(rad), padding_mod * sin(rad), -1.0f); } std::vector <uint16_t> indices; indices.reserve(2 * 3 * 16); for (unsigned i = 0; i < 16; i++) { indices.push_back(0); indices.push_back((i & 15) + 2); indices.push_back(((i + 1) & 15) + 2); } for (unsigned i = 0; i < 16; i++) { indices.push_back(1); indices.push_back(((i + 1) & 15) + 2); indices.push_back((i & 15) + 2); } spot_count = indices.size(); Vulkan::BufferCreateInfo info = {}; info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; info.size = sizeof(positions); info.domain = Vulkan::BufferDomain::Device; spot_vbo = e.get_device().create_buffer(info, positions); info.size = indices.size() * sizeof(uint16_t); info.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT; spot_ibo = e.get_device().create_buffer(info, indices.data()); } void LightMesh::on_device_created(const Vulkan::DeviceCreatedEvent &e) { create_spot_mesh(e); create_point_mesh(e); } void LightMesh::on_device_destroyed(const Vulkan::DeviceCreatedEvent &) { spot_vbo.reset(); spot_ibo.reset(); point_vbo.reset(); point_ibo.reset(); } SSAOLookupTables::SSAOLookupTables() { EVENT_MANAGER_REGISTER_LATCH(SSAOLookupTables, on_device_created, on_device_destroyed, Vulkan::DeviceCreatedEvent); } void SSAOLookupTables::on_device_created(const Vulkan::DeviceCreatedEvent &e) { auto &device = e.get_device(); // Reused from http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html. std::mt19937 rnd; std::uniform_real_distribution<float> dist(-1.0f, 1.0f); std::uniform_real_distribution<float> dist_u(0.0f, 1.0f); Vulkan::ImageCreateInfo info = Vulkan::ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R16G16_SFLOAT); noise_resolution = 4; vec2 noise_samples[4 * 4]; for (auto &n : noise_samples) { float x = dist(rnd); float y = dist(rnd); n = normalize(vec2(x, y)); } u16vec2 noise_samples_fp16[4 * 4]; for (unsigned i = 0; i < 4 * 4; i++) noise_samples_fp16[i] = floatToHalf(noise_samples[i]); Vulkan::ImageInitialData initial = { noise_samples_fp16, 0, 0 }; noise = device.create_image(info, &initial); static const unsigned SSAO_KERNEL_SIZE = 16; kernel_size = SSAO_KERNEL_SIZE; vec4 hemisphere[SSAO_KERNEL_SIZE]; for (unsigned i = 0; i < SSAO_KERNEL_SIZE; i++) { float x = dist(rnd); float y = dist(rnd); float z = dist_u(rnd); hemisphere[i] = vec4(normalize(vec3(x, y, z)), 0.0f); float scale = float(i) / float(kernel_size); scale = mix(0.1f, 1.0f, scale * scale); hemisphere[i] *= scale; } Vulkan::BufferCreateInfo buffer = {}; buffer.size = sizeof(hemisphere); buffer.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; buffer.domain = Vulkan::BufferDomain::Device; kernel = device.create_buffer(buffer, hemisphere); } void SSAOLookupTables::on_device_destroyed(const Vulkan::DeviceCreatedEvent &) { kernel.reset(); noise.reset(); } }
30.777174
116
0.727883
[ "mesh", "vector" ]
6d0fc78855c13003de7ca4318909c2c498db5f98
11,007
cc
C++
test/e2e_test/FrameQueue.cc
MartinJindrisek/SVT-AV1
6fd564611bdb48a2a6d2c7b90a91b4b1bdbe74b9
[ "BSD-2-Clause-Patent" ]
null
null
null
test/e2e_test/FrameQueue.cc
MartinJindrisek/SVT-AV1
6fd564611bdb48a2a6d2c7b90a91b4b1bdbe74b9
[ "BSD-2-Clause-Patent" ]
1
2019-06-29T16:50:38.000Z
2019-06-29T16:50:38.000Z
test/e2e_test/FrameQueue.cc
eclipseo/SVT-AV1
d380874c5f5f985ff764fc18031760eaf313eea6
[ "BSD-2-Clause-Patent" ]
1
2020-01-07T09:03:46.000Z
2020-01-07T09:03:46.000Z
/* * Copyright(c) 2019 Netflix, Inc. * SPDX - License - Identifier: BSD - 2 - Clause - Patent */ /****************************************************************************** * @file FrameQueue.cc * * @brief Impelmentation of reconstructed frame queue * ******************************************************************************/ #include <stdio.h> #include <vector> #include <algorithm> #include "FrameQueue.h" #include "CompareTools.h" #ifdef ENABLE_DEBUG_MONITOR #include "VideoMonitor.h" #endif #if _WIN32 #define fseeko64 _fseeki64 #define ftello64 _ftelli64 #define FOPEN(f, s, m) fopen_s(&f, s, m) #else #define fseeko64 fseek #define ftello64 ftell #define FOPEN(f, s, m) f = fopen(s, m) #endif using svt_av1_e2e_tools::compare_image; class FrameQueueFile : public FrameQueue { public: FrameQueueFile(const VideoFrameParam &param, const char *file_path) : FrameQueue(param) { queue_type_ = FRAME_QUEUE_FILE; max_frame_ts_ = 0; FOPEN(recon_file_, file_path, "wb"); record_list_.clear(); } virtual ~FrameQueueFile() { if (recon_file_) { fflush(recon_file_); fclose(recon_file_); recon_file_ = nullptr; } record_list_.clear(); } void add_frame(VideoFrame *frame) override { if (recon_file_ && frame->buf_size && frame->timestamp < (uint64_t)frame_count_) { if (frame->timestamp >= max_frame_ts_) { // new frame is larger than max timestamp fseeko64(recon_file_, 0, SEEK_END); for (size_t i = max_frame_ts_; i < frame->timestamp + 1; ++i) { fwrite(frame->buffer, 1, frame->buf_size, recon_file_); } max_frame_ts_ = frame->timestamp; } rewind(recon_file_); uint64_t frameNum = frame->timestamp; while (frameNum > 0) { int ret = fseeko64(recon_file_, frame->buf_size, SEEK_CUR); if (ret != 0) { return; } frameNum--; } fwrite(frame->buffer, 1, frame->buf_size, recon_file_); fflush(recon_file_); record_list_.push_back((uint32_t)frame->timestamp); } delete frame; } const VideoFrame *take_frame(const uint64_t time_stamp) override { if (recon_file_ == nullptr) return nullptr; VideoFrame *new_frame = nullptr; fseeko64(recon_file_, 0, SEEK_END); int64_t actual_size = ftello64(recon_file_); if (actual_size > 0 && ((uint64_t)actual_size) > ((time_stamp + 1) * frame_size_)) { int ret = fseeko64(recon_file_, time_stamp * frame_size_, 0); if (ret != 0) { // printf("Error in fseeko64 returnVal %i\n", ret); return nullptr; } new_frame = get_empty_frame(); if (new_frame) { size_t read_size = fread(new_frame->buffer, 1, frame_size_, recon_file_); if (read_size != frame_size_) { printf("read recon file error!\n"); delete_frame(new_frame); new_frame = nullptr; } else { new_frame->timestamp = time_stamp; } } } return new_frame; } const VideoFrame *take_frame_inorder(const uint32_t index) override { return take_frame(index); } void delete_frame(VideoFrame *frame) override { delete frame; } bool is_compelete() override { if (record_list_.size() < frame_count_) return false; std::sort(record_list_.begin(), record_list_.end()); if (record_list_.at(frame_count_ - 1) != frame_count_ - 1) return false; return true; } public: FILE *recon_file_; /**< file handle to dave reconstructed video frames, set it to public for accessable by create_frame_queue */ protected: uint64_t max_frame_ts_; /**< maximun timestamp of current frames in list */ std::vector<uint32_t> record_list_; /**< list of frame timstamp, to help check if the file is completed*/ }; class FrameQueueBufferSort_ASC { public: bool operator()(VideoFrame *a, VideoFrame *b) const { return a->timestamp < b->timestamp; }; }; class FrameQueueBuffer : public FrameQueue { public: FrameQueueBuffer(VideoFrameParam fmt) : FrameQueue(fmt) { queue_type_ = FRAME_QUEUE_BUFFER; frame_list_.clear(); } virtual ~FrameQueueBuffer() { while (frame_list_.size() > 0) { delete frame_list_.back(); frame_list_.pop_back(); } } void add_frame(VideoFrame *frame) override { if (frame->timestamp < (uint64_t)frame_count_) { frame_list_.push_back(frame); std::sort(frame_list_.begin(), frame_list_.end(), FrameQueueBufferSort_ASC()); } else // drop the frames out of limitation delete frame; } const VideoFrame *take_frame(const uint64_t time_stamp) override { for (VideoFrame *frame : frame_list_) { if (frame->timestamp == time_stamp) return frame; } return nullptr; } const VideoFrame *take_frame_inorder(const uint32_t index) override { if (index < frame_list_.size()) return frame_list_.at(index); return nullptr; } void delete_frame(VideoFrame *frame) override { std::vector<VideoFrame *>::iterator it = std::find(frame_list_.begin(), frame_list_.end(), frame); if (it != frame_list_.end()) { // if the video frame is in list delete *it; frame_list_.erase(it); } else // only delete the video frame not in list delete frame; } bool is_compelete() override { if (frame_list_.size() < frame_count_) return false; VideoFrame *frame = frame_list_.at(frame_count_ - 1); if (frame == nullptr || frame->timestamp != frame_count_ - 1) return false; return true; } protected: std::vector<VideoFrame *> frame_list_; /**< list of frame containers */ }; class RefQueue : public ICompareQueue, FrameQueueBuffer { public: RefQueue(VideoFrameParam fmt, FrameQueue *my_friend) : FrameQueueBuffer(fmt) { friend_ = my_friend; frame_vec_.clear(); #ifdef ENABLE_DEBUG_MONITOR recon_monitor_ = nullptr; ref_monitor_ = nullptr; #endif } virtual ~RefQueue() { while (frame_vec_.size()) { const VideoFrame *p = frame_vec_.back(); frame_vec_.pop_back(); if (p) { // printf("Reference queue still remain frames when // delete(%u)\n", // (uint32_t)p->timestamp); delete p; } } friend_ = nullptr; #ifdef ENABLE_DEBUG_MONITOR if (recon_monitor_) { delete recon_monitor_; recon_monitor_ = nullptr; } if (ref_monitor_) { delete ref_monitor_; ref_monitor_ = nullptr; } #endif } public: bool compare_video(const VideoFrame &frame) override { const VideoFrame *friend_frame = friend_->take_frame(frame.timestamp); if (friend_frame) { draw_frames(&frame, friend_frame); bool is_same = compare_image(friend_frame, &frame); if (!is_same) { printf("ref_frame(%u) compare failed!!\n", (uint32_t)frame.timestamp); } return is_same; } else { clone_frame(frame); } return true; /**< default return suceess if not found recon frame */ } bool flush_video() override { bool is_all_same = true; for (const VideoFrame *frame : frame_vec_) { const VideoFrame *friend_frame = friend_->take_frame(frame->timestamp); if (friend_frame) { draw_frames(frame, friend_frame); if (!compare_image(friend_frame, frame)) { printf("ref_frame(%u) compare failed!!\n", (uint32_t)frame->timestamp); is_all_same = false; } } } return is_all_same; } private: void clone_frame(const VideoFrame &frame) { VideoFrame *new_frame = new VideoFrame(frame); if (new_frame) frame_vec_.push_back(new_frame); else printf("out of memory for clone video frame!!\n"); } void draw_frames(const VideoFrame *frame, const VideoFrame *friend_frame) { #ifdef ENABLE_DEBUG_MONITOR if (ref_monitor_ == nullptr) { ref_monitor_ = new VideoMonitor(frame->width, frame->height, frame->stride[0], frame->bits_per_sample, false, "Ref decode"); } if (ref_monitor_) { ref_monitor_->draw_frame( frame->planes[0], frame->planes[1], frame->planes[2]); } // Output to monitor for debug if (recon_monitor_ == nullptr) { recon_monitor_ = new VideoMonitor( frame->width, frame->height, frame->width * (frame->bits_per_sample > 8 ? 2 : 1), frame->bits_per_sample, false, "Recon"); } if (recon_monitor_) { recon_monitor_->draw_frame(friend_frame->planes[0], friend_frame->planes[1], friend_frame->planes[2]); } #endif } private: FrameQueue *friend_; std::vector<const VideoFrame *> frame_vec_; #ifdef ENABLE_DEBUG_MONITOR VideoMonitor *recon_monitor_; VideoMonitor *ref_monitor_; #endif }; FrameQueue *create_frame_queue(const VideoFrameParam &param, const char *file_path) { FrameQueueFile *new_queue = new FrameQueueFile(param, file_path); if (new_queue) { if (new_queue->recon_file_ == nullptr) { delete new_queue; new_queue = nullptr; } } return new_queue; } FrameQueue *create_frame_queue(const VideoFrameParam &param) { return new FrameQueueBuffer(param); } ICompareQueue *create_ref_compare_queue(const VideoFrameParam &param, FrameQueue *recon) { return new RefQueue(param, recon); }
33.153614
80
0.544108
[ "vector" ]
6d13896f2fbb78ffc7c880f4818d7d99694973aa
324
hpp
C++
include/awl/backends/x11/cursor/object_ref.hpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
include/awl/backends/x11/cursor/object_ref.hpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
include/awl/backends/x11/cursor/object_ref.hpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#ifndef AWL_BACKENDS_X11_CURSOR_OBJECT_REF_HPP_INCLUDED #define AWL_BACKENDS_X11_CURSOR_OBJECT_REF_HPP_INCLUDED #include <awl/backends/x11/cursor/object_fwd.hpp> #include <fcppt/reference_impl.hpp> namespace awl::backends::x11::cursor { using object_ref = fcppt::reference<awl::backends::x11::cursor::object>; } #endif
21.6
72
0.814815
[ "object" ]
6d1a30741ab5db314dff37db6a34a42cd1e2c9f7
1,882
cpp
C++
JOISC/day2/chameleon/chameleon.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
JOISC/day2/chameleon/chameleon.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
JOISC/day2/chameleon/chameleon.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <queue> #include <vector> #include "chameleon.h" namespace woshiluo{ }; void Solve(int n) { n = n * 2; bool vis[ n + 10 ], upd[ n + 10 ], inque[ n + 10 ]; //int f[ n + 10 ][ n + 10 ]; int same[ n + 10 ][ n + 10 ]; // -1 false 0 unkown 1 true std::vector<int> edge[ n + 10 ]; // memset( f, -1, sizeof(f) ); memset( same, 0, sizeof(same) ); memset( vis, 0, sizeof(vis) ); memset( inque, 0, sizeof(inque) ); memset( upd, 0, sizeof(upd) ); for( int top = 1; top <= n; top ++ ) { vis[top] = true; for( int i = 1; i <= n; i ++ ) { if( vis[i] || i == top ) continue; std::vector<int> a; a.push_back( top ); a.push_back(i); int cnt = Query(a); if( cnt != 2 ) { edge[top].push_back(i); edge[i].push_back(top); } } int size = edge[top].size(); if( size == 1 ) { int to = edge[top][0]; same[top][to] = same[to][top] = 1; } if( size == 3 ) { int son1 = edge[top][0], son2 = edge[top][1], son3 = edge[top][2], cnt12, cnt13, cnt23; std::vector<int> a, b; a.push_back( top ); b = a; b.push_back( son1 ); b.push_back( son2 ); cnt12 = Query(b); b = a; b.push_back( son1 ); b.push_back( son3 ); cnt13 = Query(b); b = a; b.push_back( son2 ); b.push_back( son3 ); cnt23 = Query(b); if( cnt12 == cnt13 && cnt12 == 2 ) same[top][son1] = same[son1][top] = -1; if( cnt12 == cnt23 && cnt12 == 2 ) same[top][son2] = same[son2][top] = -1; if( cnt13 == cnt23 && cnt13 == 2 ) same[top][son3] = same[son3][top] = -1; } } for( int i = 1; i <= n; i ++ ) { if( upd[i] ) continue; int size = edge[i].size(); for( int j = 0; j < size; j ++ ) { if( same[i][ edge[i][j] ] != -1 ) { fprintf( stderr, "%d %d\n", i, edge[i][j] ); Answer( i, edge[i][j] ); upd[i] = upd[ edge[i][j] ] = true; break; } } } }
23.234568
52
0.502657
[ "vector" ]
6d1c9a88c6407fd3d7dea4bf04b7b3784614e4b9
2,619
cpp
C++
dlls/airtank.cpp
QuakeEngines/halflife-sdk-2019
10b494deaef5433245213851634db1361f1ba4ce
[ "Unlicense" ]
77
2018-09-02T20:32:32.000Z
2022-03-31T00:25:33.000Z
dlls/airtank.cpp
QuakeEngines/halflife-sdk-2019
10b494deaef5433245213851634db1361f1ba4ce
[ "Unlicense" ]
79
2019-09-01T12:47:26.000Z
2022-03-28T11:02:16.000Z
dlls/airtank.cpp
QuakeEngines/halflife-sdk-2019
10b494deaef5433245213851634db1361f1ba4ce
[ "Unlicense" ]
51
2018-09-02T22:02:04.000Z
2022-03-30T09:08:41.000Z
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "weapons.h" #include "player.h" class CAirtank : public CGrenade { void Spawn() override; void Precache() override; void EXPORT TankThink(); void EXPORT TankTouch(CBaseEntity* pOther); int BloodColor() override { return DONT_BLEED; } void Killed(entvars_t* pevAttacker, int iGib) override; bool Save(CSave& save) override; bool Restore(CRestore& restore) override; static TYPEDESCRIPTION m_SaveData[]; bool m_state; }; LINK_ENTITY_TO_CLASS(item_airtank, CAirtank); TYPEDESCRIPTION CAirtank::m_SaveData[] = { DEFINE_FIELD(CAirtank, m_state, FIELD_BOOLEAN), }; IMPLEMENT_SAVERESTORE(CAirtank, CGrenade); void CAirtank::Spawn() { Precache(); // motor pev->movetype = MOVETYPE_FLY; pev->solid = SOLID_BBOX; SET_MODEL(ENT(pev), "models/w_oxygen.mdl"); UTIL_SetSize(pev, Vector(-16, -16, 0), Vector(16, 16, 36)); UTIL_SetOrigin(pev, pev->origin); SetTouch(&CAirtank::TankTouch); SetThink(&CAirtank::TankThink); pev->flags |= FL_MONSTER; pev->takedamage = DAMAGE_YES; pev->health = 20; pev->dmg = 50; m_state = true; } void CAirtank::Precache() { PRECACHE_MODEL("models/w_oxygen.mdl"); PRECACHE_SOUND("doors/aliendoor3.wav"); } void CAirtank::Killed(entvars_t* pevAttacker, int iGib) { pev->owner = ENT(pevAttacker); // UNDONE: this should make a big bubble cloud, not an explosion Explode(pev->origin, Vector(0, 0, -1)); } void CAirtank::TankThink() { // Fire trigger m_state = true; SUB_UseTargets(this, USE_TOGGLE, 0); } void CAirtank::TankTouch(CBaseEntity* pOther) { if (!pOther->IsPlayer()) return; if (!m_state) { // "no oxygen" sound EMIT_SOUND(ENT(pev), CHAN_BODY, "player/pl_swim2.wav", 1.0, ATTN_NORM); return; } // give player 12 more seconds of air pOther->pev->air_finished = gpGlobals->time + 12; // suit recharge sound EMIT_SOUND(ENT(pev), CHAN_VOICE, "doors/aliendoor3.wav", 1.0, ATTN_NORM); // recharge airtank in 30 seconds pev->nextthink = gpGlobals->time + 30; m_state = false; SUB_UseTargets(this, USE_TOGGLE, 1); }
22.194915
78
0.714395
[ "object", "vector", "solid" ]
6d2185b6ed7b16ddb0c68f70039f223aa031e3d5
32,605
cpp
C++
src/RuleApplication.cpp
AVBelyy/SAFRAN
115d0481c48302aaa958e364f357cfc7510131e6
[ "MIT" ]
null
null
null
src/RuleApplication.cpp
AVBelyy/SAFRAN
115d0481c48302aaa958e364f357cfc7510131e6
[ "MIT" ]
null
null
null
src/RuleApplication.cpp
AVBelyy/SAFRAN
115d0481c48302aaa958e364f357cfc7510131e6
[ "MIT" ]
null
null
null
#include "RuleApplication.h" RuleApplication::RuleApplication(Index* index, TraintripleReader* graph, ValidationtripleReader* vtr, RuleReader* rr, Explanation* exp) { this->index = index; this->graph = graph; this->vtr = vtr; this->rr = rr; this->rulegraph = new RuleGraph(index->getNodeSize(), graph, vtr); reflexiv_token = *index->getIdOfNodestring(Properties::get().REFLEXIV_TOKEN); this->k = Properties::get().TOP_K_OUTPUT; this->exp = exp; } RuleApplication::RuleApplication(Index* index, TraintripleReader* graph, TesttripleReader* ttr, ValidationtripleReader* vtr, RuleReader* rr, Explanation* exp) { this->index = index; this->graph = graph; this->ttr = ttr; this->vtr = vtr; this->rr = rr; this->rulegraph = new RuleGraph(index->getNodeSize(), graph, ttr, vtr); reflexiv_token = *index->getIdOfNodestring(Properties::get().REFLEXIV_TOKEN); this->k = Properties::get().TOP_K_OUTPUT; this->exp = exp; } void RuleApplication::updateTTR(TesttripleReader* testReader) { this->ttr = testReader; this->rulegraph->updateTTR(testReader); } void RuleApplication::apply_nr_noisy(std::unordered_map<int, std::pair<std::pair<bool, std::vector<std::vector<int>>>, std::pair<bool, std::vector<std::vector<int>>>>> rel2clusters) { int* adj_begin = rr->getCSR()->getAdjBegin(); Rule* rules_adj_list = rr->getCSR()->getAdjList(); fopen_s(&pFile, Properties::get().PATH_OUTPUT.c_str(), "w"); int iterations = index->getRelSize(); for (int rel = 0; rel < iterations; rel++) { if (iterations > 100 && (rel % ((iterations - 1) / 100)) == 0) { util::printProgress((double)rel / (double)(iterations - 1)); } else { std::cout << "Relation " << rel << "/" << iterations << " " << *index->getStringOfRelId(rel) << "\n"; } std::pair<std::pair<bool, std::vector<std::vector<int>>>, std::pair<bool, std::vector<std::vector<int>>>> cluster = rel2clusters[rel]; std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> headTailResults; std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> tailHeadResults; std::cout << cluster.first.first << " " << cluster.first.second.size() << " " << cluster.second.first << " " << cluster.second.second.size() << "\n"; if (cluster.first.first == true) { tailHeadResults = max(rel, cluster.first.second, true); } else { tailHeadResults = noisy(rel, cluster.first.second, true); } if (cluster.second.first == true) { headTailResults = max(rel, cluster.second.second, false); } else { headTailResults = noisy(rel, cluster.second.second, false); } auto it_head = headTailResults.begin(); while (it_head != headTailResults.end()) { auto it_tail = it_head->second.begin(); while (it_tail != it_head->second.end()) { { writeTopKCandidates(it_head->first, rel, it_tail->first, tailHeadResults[it_tail->first][it_head->first], it_tail->second, pFile, k); } it_tail++; } it_head++; } } fclose(pFile); } void RuleApplication::apply_only_noisy() { fopen_s(&pFile, Properties::get().PATH_OUTPUT.c_str(), "w"); int* adj_begin = rr->getCSR()->getAdjBegin(); Rule* rules_adj_list = rr->getCSR()->getAdjList(); int iterations = index->getRelSize(); for (int rel = 0; rel < iterations; rel++) { if (iterations > 100 && (rel % ((iterations - 1) / 100)) == 0) { util::printProgress((double)rel / (double)(iterations - 1)); } else { std::cout << "Relation " << rel << "/" << iterations << " " << *index->getStringOfRelId(rel) << "\n"; } int ind_ptr = adj_begin[3 + rel]; int lenRules = adj_begin[3 + rel + 1] - ind_ptr; std::vector<std::vector<int>> clusters; for (int i = 0; i < lenRules; i++) { std::vector<int> cluster; Rule& r = rules_adj_list[ind_ptr + i]; cluster.push_back(i); clusters.push_back(cluster); } std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> headTailResults; std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> tailHeadResults; tailHeadResults = noisy(rel, clusters, true); headTailResults = noisy(rel, clusters, false); auto it_head = headTailResults.begin(); while (it_head != headTailResults.end()) { auto it_tail = it_head->second.begin(); while (it_tail != it_head->second.end()) { { writeTopKCandidates(it_head->first, rel, it_tail->first, tailHeadResults[it_tail->first][it_head->first], it_tail->second, pFile, k); } it_tail++; } it_head++; } } fclose(pFile); } void RuleApplication::apply_only_max() { fopen_s(&pFile, Properties::get().PATH_OUTPUT.c_str(), "w"); int* adj_begin = rr->getCSR()->getAdjBegin(); Rule* rules_adj_list = rr->getCSR()->getAdjList(); int iterations = index->getRelSize(); for (int rel = 0; rel < iterations; rel++) { if (iterations > 100 && (rel % ((iterations - 1) / 100)) == 0) { util::printProgress((double)rel / (double)(iterations - 1)); } else { std::cout << "Relation " << rel << "/" << iterations << " " << *index->getStringOfRelId(rel) << "\n"; } int ind_ptr = adj_begin[3 + rel]; int lenRules = adj_begin[3 + rel + 1] - ind_ptr; std::vector<std::vector<int>> clusters; std::vector<int> cluster; for (int i = 0; i < lenRules; i++) { Rule& r = rules_adj_list[ind_ptr + i]; cluster.push_back(i); } clusters.push_back(cluster); std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> headTailResults; std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> tailHeadResults; tailHeadResults = max(rel, clusters, true); headTailResults = max(rel, clusters, false); auto it_head = headTailResults.begin(); while (it_head != headTailResults.end()) { auto it_tail = it_head->second.begin(); while (it_tail != it_head->second.end()) { { writeTopKCandidates(it_head->first, rel, it_tail->first, tailHeadResults[it_tail->first][it_head->first], it_tail->second, pFile, k); } it_tail++; } it_head++; } } fclose(pFile); } std::vector<std::tuple<int, int, int, float50>> RuleApplication::apply_only_max_in_memory(size_t K) { int* adj_begin = rr->getCSR()->getAdjBegin(); std::vector<std::tuple<int, int, int, float50>> out; int iterations = index->getRelSize(); for (int rel = 0; rel < iterations; rel++) { // TODO: precompute clusters outside of this call int ind_ptr = adj_begin[3 + rel]; int lenRules = adj_begin[3 + rel + 1] - ind_ptr; std::vector<std::vector<int>> clusters; std::vector<int> cluster; for (int i = 0; i < lenRules; i++) { cluster.push_back(i); } clusters.push_back(cluster); std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> headTailResults; headTailResults = max(rel, clusters, false); for (auto & [head, tailResults] : headTailResults) { for (auto & [_, tails] : tailResults) { size_t maxSize = std::min(tails.size(), K); size_t i = 0; for (auto [tail, val] : tails) { if (i >= maxSize) { break; } out.emplace_back(head, rel, tail, val); i++; } } } } return out; } std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> RuleApplication::noisy(int rel, std::vector<std::vector<int>> clusters, bool predictHeadNotTail) { int* adj_lists = graph->getCSR()->getAdjList(); int* adj_list_starts = graph->getCSR()->getAdjBegin(); Rule* rules_adj_list = rr->getCSR()->getAdjList(); int* adj_begin = rr->getCSR()->getAdjBegin(); int** testtriples = ttr->getTesttriples(); int* testtriplessize = ttr->getTesttriplesSize(); int* tt_adj_list = ttr->getCSR()->getAdjList(); int* tt_adj_begin = ttr->getCSR()->getAdjBegin(); int* vt_adj_list = vtr->getCSR()->getAdjList(); int* vt_adj_begin = vtr->getCSR()->getAdjBegin(); int nodesize = index->getNodeSize(); int ind_ptr = adj_begin[3 + rel]; int lenRules = adj_begin[3 + rel + 1] - ind_ptr; std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> entityEntityResults; if(!predictHeadNotTail) { // adj list of testtriple x r ? int* t_adj_list = &(tt_adj_list[tt_adj_begin[rel * 2]]); int lenHeads = t_adj_list[1]; // size + 1 of testtriple testtriple heads of a specific relation auto rHT = ttr->getRelHeadToTails()[rel]; #pragma omp parallel for schedule(dynamic) for (int b = 0; b < rHT.bucket_count(); b++) { float50* result_tail = new float50[nodesize]; double* cluster_result_tail = new double[nodesize]; std::fill(result_tail, result_tail + nodesize, 0.0); std::fill(cluster_result_tail, cluster_result_tail + nodesize, 0.0); std::unordered_map<int, std::vector<int>> entityToRules; for (auto heads = rHT.begin(b); heads != rHT.end(b); heads++) { int head = heads->first; int* head_ind_ptr = &t_adj_list[3 + head]; int lenTails = heads->second.size(); if (lenTails > 0) { std::vector<int> touched_tails; for (int i = 0; i < clusters.size(); i++) { std::vector<int> touched_cluster_tails; for (auto ruleIndex : clusters[i]) { Rule& currRule = rules_adj_list[ind_ptr + ruleIndex]; std::vector<int> tailresults_vec; if (currRule.is_c()) { rulegraph->searchDFSSingleStart_filt(true, head, head, currRule, false, tailresults_vec, true, false); } else { if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::XRule && *currRule.getHeadconstant() != head) { if (rulegraph->existsAcyclic(&head, currRule, true)) { tailresults_vec.push_back(*currRule.getHeadconstant()); } } else if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::YRule && head == *currRule.getHeadconstant()) { rulegraph->searchDFSSingleStart_filt(true, *currRule.getHeadconstant(), *currRule.getBodyconstantId(), currRule, true, tailresults_vec, true, false); } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::XRule && *currRule.getHeadconstant() != head) { if (rulegraph->existsAcyclic(&head, currRule, true)) { tailresults_vec.push_back(*currRule.getHeadconstant()); } } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::YRule && head == *currRule.getHeadconstant()) { rulegraph->searchDFSMultiStart_filt(true, *currRule.getHeadconstant(), currRule, true, tailresults_vec, true, false); } } if (tailresults_vec.size() > 0) { for (auto tailresult : tailresults_vec) { if (this->exp != nullptr) { entityToRules[tailresult].push_back(currRule.getID()); } if (cluster_result_tail[tailresult] == 0.0) { cluster_result_tail[tailresult] = currRule.getAppliedConfidence(); touched_cluster_tails.push_back(tailresult); } else { if (cluster_result_tail[tailresult] < currRule.getAppliedConfidence()) { cluster_result_tail[tailresult] = currRule.getAppliedConfidence(); } } } } } for (auto i : touched_cluster_tails) { if (result_tail[i] == 0.0) { touched_tails.push_back(i); } result_tail[i] = 1.0 - (1.0 - result_tail[i]) * (1.0 - cluster_result_tail[i]); cluster_result_tail[i] = 0.0; } } // INSERT EXPLAINATION if (this->exp != nullptr) { MinHeap tails(10); for (auto i : touched_tails) { if (result_tail[i] >= tails.getMin().second) { tails.deleteMin(); tails.insertKey(std::make_pair(i, result_tail[i])); } } std::vector<std::pair<int, float50>> tailresults_vec; for (int i = 9; i >= 0; i--) { std::pair<int, float50> tail_pred = tails.extractMin(); if (tail_pred.first != -1) tailresults_vec.push_back(tail_pred); } std::reverse(tailresults_vec.begin(), tailresults_vec.end()); int task_id = exp->getNextTaskID(); exp->begin(); exp->insertTask(task_id, true, rel, head); for (auto p : tailresults_vec) { bool hit = false; if (heads->second.find(p.first) != heads->second.end()) { hit = true; } exp->insertPrediction(task_id, p.first, hit, (double) p.second); auto it = entityToRules.find(p.first); if (it != entityToRules.end()) { for (auto rule : it->second) { exp->insertRule_Entity(rule, task_id, p.first); } } } exp->commit(); entityToRules.clear(); } for (int tailIndex = 0; tailIndex < lenTails; tailIndex++) { int tail = t_adj_list[3 + lenHeads + *head_ind_ptr + tailIndex]; MinHeap tails(k); for (auto i : touched_tails) { if (result_tail[i] >= tails.getMin().second) { float50 confidence = result_tail[i]; if (i == head) continue; if (i == reflexiv_token) { i = head; } if (i == tail || heads->second.find(i) == heads->second.end()) { tails.deleteMin(); tails.insertKey(std::make_pair(i, confidence)); } } } std::vector<std::pair<int, float50>> tailresults_vec; for (int i = k - 1; i >= 0; i--) { std::pair<int, float50> tail_pred = tails.extractMin(); if (tail_pred.first != -1) tailresults_vec.push_back(tail_pred); } std::reverse(tailresults_vec.begin(), tailresults_vec.end()); #pragma omp critical { entityEntityResults[head][tail] = tailresults_vec; } } for (auto i : touched_tails) { result_tail[i] = 0.0; } } } delete[] result_tail; delete[] cluster_result_tail; } } else { // adj list of testtriple x r ? int* t_adj_list = &(tt_adj_list[tt_adj_begin[rel * 2 + 1]]); int lenTails = t_adj_list[1]; // size + 1 of testtriple testtriple heads of a specific relation auto rTH = ttr->getRelTailToHeads()[rel]; #pragma omp parallel for schedule(dynamic) for (int b = 0; b < rTH.bucket_count(); b++) { float50* result_head = new float50[nodesize]; double* cluster_result_head = new double[nodesize]; std::fill(result_head, result_head + nodesize, 0.0); std::fill(cluster_result_head, cluster_result_head + nodesize, 0.0); std::unordered_map<int, std::vector<int>> entityToRules; for (auto tails = rTH.begin(b); tails != rTH.end(b); tails++) { int tail = tails->first; int* tail_ind_ptr = &t_adj_list[3 + tail]; int lenHeads = tails->second.size(); if (lenHeads > 0) { std::vector<int> touched_heads; for (int i = 0; i < clusters.size(); i++) { std::vector<int> touched_cluster_heads; for (auto ruleIndex : clusters[i]) { Rule& currRule = rules_adj_list[ind_ptr + ruleIndex]; std::vector<int> headresults_vec; if (currRule.is_c()) { rulegraph->searchDFSSingleStart_filt(false, tail, tail, currRule, true, headresults_vec, true, false); } else { if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::XRule && tail == *currRule.getHeadconstant()) { rulegraph->searchDFSSingleStart_filt(false, *currRule.getHeadconstant(), *currRule.getBodyconstantId(), currRule, true, headresults_vec, true, false); } else if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::YRule && *currRule.getHeadconstant() != tail) { if (rulegraph->existsAcyclic(&tail, currRule, true)) { headresults_vec.push_back(*currRule.getHeadconstant()); } } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::XRule && tail == *currRule.getHeadconstant()) { rulegraph->searchDFSMultiStart_filt(false, *currRule.getHeadconstant(), currRule, true, headresults_vec, true, false); } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::YRule && *currRule.getHeadconstant() != tail) { if (rulegraph->existsAcyclic(&tail, currRule, true)) { headresults_vec.push_back(*currRule.getHeadconstant()); } } } if (headresults_vec.size() > 0) { for (auto headresult : headresults_vec) { if (this->exp != nullptr) { entityToRules[headresult].push_back(currRule.getID()); } if (cluster_result_head[headresult] == 0.0) { cluster_result_head[headresult] = currRule.getAppliedConfidence(); touched_cluster_heads.push_back(headresult); } else { if (cluster_result_head[headresult] < currRule.getAppliedConfidence()) { cluster_result_head[headresult] = currRule.getAppliedConfidence(); } } } } } for (auto i : touched_cluster_heads) { if (result_head[i] == 0.0) { touched_heads.push_back(i); } result_head[i] = 1.0 - (1.0 - result_head[i]) * (1.0 - cluster_result_head[i]); cluster_result_head[i] = 0.0; } } // INSERT EXPLAINATION if (this->exp != nullptr) { MinHeap heads(10); for (auto i : touched_heads) { if (result_head[i] >= heads.getMin().second) { heads.deleteMin(); heads.insertKey(std::make_pair(i, result_head[i])); } } std::vector<std::pair<int, float50>> headresults_vec; for (int i = 9; i >= 0; i--) { std::pair<int, float50> head_pred = heads.extractMin(); if (head_pred.first != -1) headresults_vec.push_back(head_pred); } std::reverse(headresults_vec.begin(), headresults_vec.end()); int task_id = exp->getNextTaskID(); exp->begin(); exp->insertTask(task_id, false, rel, tail); for (auto p : headresults_vec) { bool hit = false; if (tails->second.find(p.first) != tails->second.end()) { hit = true; } exp->insertPrediction(task_id, p.first, hit, (double) p.second); auto it = entityToRules.find(p.first); if (it != entityToRules.end()) { for (auto rule : it->second) { exp->insertRule_Entity(rule, task_id, p.first); } } } exp->commit(); entityToRules.clear(); } for (int headIndex = 0; headIndex < lenHeads; headIndex++) { int head = t_adj_list[3 + lenTails + *tail_ind_ptr + headIndex]; MinHeap heads(k); for (auto i : touched_heads) { if (result_head[i] >= heads.getMin().second) { float50 confidence = result_head[i]; if (i == tail) continue; if (i == reflexiv_token) { i = tail; } if (i == head || tails->second.find(i) == tails->second.end()) { heads.deleteMin(); heads.insertKey(std::make_pair(i, confidence)); } } } std::vector<std::pair<int, float50>> headresults_vec; for (int i = k - 1; i >= 0; i--) { std::pair<int, float50> head_pred = heads.extractMin(); if (head_pred.first != -1) headresults_vec.push_back(head_pred); } std::reverse(headresults_vec.begin(), headresults_vec.end()); #pragma omp critical { entityEntityResults[tail][head] = headresults_vec; } } for (auto i : touched_heads) { result_head[i] = 0.0; } } } delete[] result_head; delete[] cluster_result_head; } } return entityEntityResults; } std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> RuleApplication::max(int rel, std::vector<std::vector<int>> clusters, bool predictHeadNotTail) { int* adj_lists = graph->getCSR()->getAdjList(); int* adj_list_starts = graph->getCSR()->getAdjBegin(); Rule* rules_adj_list = rr->getCSR()->getAdjList(); int* adj_begin = rr->getCSR()->getAdjBegin(); int** testtriples = ttr->getTesttriples(); int* testtriplessize = ttr->getTesttriplesSize(); int* tt_adj_list = ttr->getCSR()->getAdjList(); int* tt_adj_begin = ttr->getCSR()->getAdjBegin(); int* vt_adj_list = vtr->getCSR()->getAdjList(); int* vt_adj_begin = vtr->getCSR()->getAdjBegin(); int nodesize = index->getNodeSize(); int ind_ptr = adj_begin[3 + rel]; int lenRules = adj_begin[3 + rel + 1] - ind_ptr; std::unordered_map<int, std::unordered_map<int, std::vector<std::pair<int, float50>>>> entityEntityResults; if (!predictHeadNotTail) { // adj list of testtriple x r ? int* t_adj_list = &(tt_adj_list[tt_adj_begin[rel * 2]]); int lenHeads = t_adj_list[1]; // size + 1 of testtriple testtriple heads of a specific relation auto rHT = ttr->getRelHeadToTails()[rel]; #pragma omp parallel for schedule(dynamic) for (int b = 0; b < rHT.bucket_count(); b++) { std::unordered_map<int, std::vector<int>> entityToRules; for (auto heads = rHT.begin(b); heads != rHT.end(b); heads++) { int head = heads->first; int* head_ind_ptr = &t_adj_list[3 + head]; int lenTails = heads->second.size(); if (lenTails > 0) { ScoreTree* tailScoreTrees = new ScoreTree[lenTails]; std::vector<bool> fineScoreTrees(lenTails); ScoreTree* expScoreTree = nullptr; if (this->exp != nullptr) { expScoreTree = new ScoreTree(); } bool stop = false; for (auto ruleIndex : clusters[0]) { Rule& currRule = rules_adj_list[ind_ptr + ruleIndex]; std::vector<int> tailresults_vec; if (currRule.is_c()) { rulegraph->searchDFSSingleStart_filt(true, head, head, currRule, false, tailresults_vec, true, false); } else { if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::XRule && *currRule.getHeadconstant() != head) { if (rulegraph->existsAcyclic(&head, currRule, true)) { tailresults_vec.push_back(*currRule.getHeadconstant()); } } else if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::YRule && head == *currRule.getHeadconstant()) { rulegraph->searchDFSSingleStart_filt(true, *currRule.getHeadconstant(), *currRule.getBodyconstantId(), currRule, true, tailresults_vec, true, false); } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::XRule && *currRule.getHeadconstant() != head) { if (rulegraph->existsAcyclic(&head, currRule, true)) { tailresults_vec.push_back(*currRule.getHeadconstant()); } } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::YRule && head == *currRule.getHeadconstant()) { rulegraph->searchDFSMultiStart_filt(true, *currRule.getHeadconstant(), currRule, true, tailresults_vec, true, false); } } if (tailresults_vec.size() > 0) { stop = true; if (this->exp != nullptr) { for (auto a : tailresults_vec) { entityToRules[a].push_back(currRule.getID()); } expScoreTree->addValues(currRule.getAppliedConfidence(), &tailresults_vec[0], tailresults_vec.size()); } for (int tailIndex = 0; tailIndex < lenTails; tailIndex++) { if (fineScoreTrees[tailIndex] == false) { int tail = t_adj_list[3 + lenHeads + *head_ind_ptr + tailIndex]; std::vector<int> filtered_testresults_vec; for (auto a : tailresults_vec) { if (a == head) continue; if (a == reflexiv_token) { a = head; } if (a == tail || heads->second.find(a) == heads->second.end()) { filtered_testresults_vec.push_back(a); } } tailScoreTrees[tailIndex].addValues(currRule.getAppliedConfidence(), &filtered_testresults_vec[0], filtered_testresults_vec.size()); if (tailScoreTrees[tailIndex].fine()) { fineScoreTrees[tailIndex] = true; } else { stop = false; } } } } if (stop) { break; } } if (this->exp != nullptr) { std::vector<std::pair<int, double>> tailresults_vec; expScoreTree->getResults(tailresults_vec); std::sort(tailresults_vec.begin(), tailresults_vec.end(), finalResultComperator); int task_id = exp->getNextTaskID(); exp->begin(); exp->insertTask(task_id, true, rel, head); for (auto p : tailresults_vec) { bool hit = false; if (heads->second.find(p.first) != heads->second.end()) { hit = true; } exp->insertPrediction(task_id, p.first, hit, p.second); auto it = entityToRules.find(p.first); if (it != entityToRules.end()) { for (auto rule : it->second) { exp->insertRule_Entity(rule, task_id, p.first); } } } exp->commit(); entityToRules.clear(); } for (int tailIndex = 0; tailIndex < lenTails; tailIndex++) { int tail = t_adj_list[3 + lenHeads + *head_ind_ptr + tailIndex]; auto cmp = [](std::pair<int, double> const& a, std::pair<int, double> const& b) { return a.second > b.second; }; // Get Tailresults and final sorting std::vector<std::pair<int, double>> tailresults_vec; tailScoreTrees[tailIndex].getResults(tailresults_vec); std::sort(tailresults_vec.begin(), tailresults_vec.end(), finalResultComperator); // convert to float50 hack std::vector<std::pair<int, float50>> tailresults_vec_float50; for (auto a : tailresults_vec) { tailresults_vec_float50.push_back(std::make_pair(a.first, (float50)a.second)); } #pragma omp critical { entityEntityResults[head][tail] = tailresults_vec_float50; } tailScoreTrees[tailIndex].Free(); } delete[] tailScoreTrees; if (this->exp != nullptr) { delete expScoreTree; } } } } } else { // adj list of testtriple x r ? int* t_adj_list = &(tt_adj_list[tt_adj_begin[rel * 2 + 1]]); int lenTails = t_adj_list[1]; // size + 1 of testtriple testtriple heads of a specific relation auto rTH = ttr->getRelTailToHeads()[rel]; #pragma omp parallel for schedule(dynamic) for (int b = 0; b < rTH.bucket_count(); b++) { std::unordered_map<int, std::vector<int>> entityToRules; for (auto tails = rTH.begin(b); tails != rTH.end(b); tails++) { int tail = tails->first; int* tail_ind_ptr = &t_adj_list[3 + tail]; int lenHeads = tails->second.size(); if (lenHeads > 0) { ScoreTree* headScoreTrees = new ScoreTree[lenHeads]; std::vector<bool> fineScoreTrees(lenHeads); ScoreTree* expScoreTree = nullptr; if (this->exp != nullptr) { expScoreTree = new ScoreTree(); } bool stop = false; for (auto ruleIndex : clusters[0]) { Rule& currRule = rules_adj_list[ind_ptr + ruleIndex]; std::vector<int> headresults_vec; if (currRule.is_c()) { rulegraph->searchDFSSingleStart_filt(false, tail, tail, currRule, true, headresults_vec, true, false); } else { if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::XRule && tail == *currRule.getHeadconstant()) { rulegraph->searchDFSSingleStart_filt(false, *currRule.getHeadconstant(), *currRule.getBodyconstantId(), currRule, true, headresults_vec, true, false); } else if (currRule.is_ac2() && currRule.getRuletype() == Ruletype::YRule && *currRule.getHeadconstant() != tail) { if (rulegraph->existsAcyclic(&tail, currRule, true)) { headresults_vec.push_back(*currRule.getHeadconstant()); } } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::XRule && tail == *currRule.getHeadconstant()) { rulegraph->searchDFSMultiStart_filt(false, *currRule.getHeadconstant(), currRule, true, headresults_vec, true, false); } else if (currRule.is_ac1() && currRule.getRuletype() == Ruletype::YRule && *currRule.getHeadconstant() != tail) { if (rulegraph->existsAcyclic(&tail, currRule, true)) { headresults_vec.push_back(*currRule.getHeadconstant()); } } } if (headresults_vec.size() > 0) { if (this->exp != nullptr) { for (auto a : headresults_vec) { entityToRules[a].push_back(currRule.getID()); } expScoreTree->addValues(currRule.getAppliedConfidence(), &headresults_vec[0], headresults_vec.size()); } stop = true; for (int headIndex = 0; headIndex < lenHeads; headIndex++) { if (fineScoreTrees[headIndex] == false) { int head = t_adj_list[3 + lenTails + *tail_ind_ptr + headIndex]; std::vector<int> filtered_headresults_vec; for (auto a : headresults_vec) { if (a == tail) continue; if (a == reflexiv_token) { a = tail; } if (a == head || tails->second.find(a) == tails->second.end()) { filtered_headresults_vec.push_back(a); } } headScoreTrees[headIndex].addValues(currRule.getAppliedConfidence(), &filtered_headresults_vec[0], filtered_headresults_vec.size()); if (headScoreTrees[headIndex].fine()) { fineScoreTrees[headIndex] = true; } else { stop = false; } } } } if (stop) { break; } } if (this->exp != nullptr) { std::vector<std::pair<int, double>> headresults_vec; expScoreTree->getResults(headresults_vec); std::sort(headresults_vec.begin(), headresults_vec.end(), finalResultComperator); int task_id = exp->getNextTaskID(); exp->begin(); exp->insertTask(task_id, false, rel, tail); for (auto p : headresults_vec) { bool hit = false; if (tails->second.find(p.first) != tails->second.end()) { hit = true; } exp->insertPrediction(task_id, p.first, hit, p.second); auto it = entityToRules.find(p.first); if (it != entityToRules.end()) { for (auto rule : it->second) { exp->insertRule_Entity(rule, task_id, p.first); } } } exp->commit(); entityToRules.clear(); } for (int headIndex = 0; headIndex < lenHeads; headIndex++) { int head = t_adj_list[3 + lenTails + *tail_ind_ptr + headIndex]; // Get Headresults and final sorting std::vector<std::pair<int, double>> headresults_vec; headScoreTrees[headIndex].getResults(headresults_vec); std::sort(headresults_vec.begin(), headresults_vec.end(), finalResultComperator); // convert to float50 hack std::vector<std::pair<int, float50>> headresults_vec_float50; for (auto a : headresults_vec) { headresults_vec_float50.push_back(std::make_pair(a.first, (float50)a.second)); } #pragma omp critical { entityEntityResults[tail][head] = headresults_vec_float50; } headScoreTrees[headIndex].Free(); } delete[] headScoreTrees; if (this->exp != nullptr) { delete expScoreTree; } } } } } return entityEntityResults; } void RuleApplication::writeTopKCandidates(int head, int rel, int tail, std::vector<std::pair<int, double>> headresults, std::vector<std::pair<int, double>> tailresults, FILE* pFile, int& K) { fprintf(pFile, "%s %s %s\nHeads: ", index->getStringOfNodeId(head)->c_str(), index->getStringOfRelId(rel)->c_str(), index->getStringOfNodeId(tail)->c_str()); int maxHead = headresults.size() < K ? headresults.size() : K; for (int i = 0; i < maxHead; i++) { fprintf(pFile, "%s\t%.16f\t", index->getStringOfNodeId(headresults[i].first)->c_str(), headresults[i].second); } fprintf(pFile, "\nTails: "); int maxTail = tailresults.size() < K ? tailresults.size() : K; for (int i = 0; i < maxTail; i++) { fprintf(pFile, "%s\t%.16f\t", index->getStringOfNodeId(tailresults[i].first)->c_str(), tailresults[i].second); } fprintf(pFile, "\n"); } void RuleApplication::writeTopKCandidates(int head, int rel, int tail, std::vector<std::pair<int, float50>> headresults, std::vector<std::pair<int, float50>> tailresults, FILE* pFile, int& K) { fprintf(pFile, "%s %s %s\nHeads: ", index->getStringOfNodeId(head)->c_str(), index->getStringOfRelId(rel)->c_str(), index->getStringOfNodeId(tail)->c_str()); int maxHead = headresults.size() < K ? headresults.size() : K; for (int i = 0; i < maxHead; i++) { fprintf(pFile, "%s\t%s\t", index->getStringOfNodeId(headresults[i].first)->c_str(), headresults[i].second.str().c_str()); } fprintf(pFile, "\nTails: "); int maxTail = tailresults.size() < K ? tailresults.size() : K; for (int i = 0; i < maxTail; i++) { fprintf(pFile, "%s\t%s\t", index->getStringOfNodeId(tailresults[i].first)->c_str(), tailresults[i].second.str().c_str()); } fprintf(pFile, "\n"); }
36.883484
193
0.624505
[ "vector" ]
6d22cf63704c5b28a90198fde6e03a244cd42225
9,012
cpp
C++
src/pose_estimation.cpp
epfl-lasa/aruco-markers
aadea1955c57411d9a737bf48a58e7bd25f665e0
[ "BSD-3-Clause" ]
null
null
null
src/pose_estimation.cpp
epfl-lasa/aruco-markers
aadea1955c57411d9a737bf48a58e7bd25f665e0
[ "BSD-3-Clause" ]
null
null
null
src/pose_estimation.cpp
epfl-lasa/aruco-markers
aadea1955c57411d9a737bf48a58e7bd25f665e0
[ "BSD-3-Clause" ]
null
null
null
#include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> #include <opencv2/aruco.hpp> #include <iostream> #include <ros/ros.h> #include <ros/package.h> #include <tf/transform_broadcaster.h> #include <math.h> using namespace std; using namespace cv; namespace { const char* about = "Pose estimation of aruco markers\n"; const char* keys = "{l | | Real length of the aruco markers (in m) }" "{ci | | Id of the camera as it appears in /dev/video* }"; } int main(int argc, char *argv[]) { CommandLineParser parser(argc, argv, keys); parser.about(about); if(argc < 3) { parser.printMessage(); return 0; } ros::init(argc, argv, "marker_poses_publisher"); ros::NodeHandle n; static tf::TransformBroadcaster br; int wait_time = 10; float actual_marker_length = parser.get<float>("l"); int camera_id = parser.get<int>("ci"); cv::Mat image, image_copy, image2, image_copy2; cv::Mat camera_matrix, dist_coeffs; std::ostringstream vector_to_marker; cv::VideoCapture in_video; in_video.open(camera_id); cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_ARUCO_ORIGINAL); std::string path = ros::package::getPath("aruco_markers") + "/config/calibration_params.yml"; cv::FileStorage fs(path, cv::FileStorage::READ); fs["camera_matrix"] >> camera_matrix; fs["distortion_coefficients"] >> dist_coeffs; while (in_video.grab() && ros::ok()) { in_video.retrieve(image); image.copyTo(image_copy); std::vector<int> ids; std::vector<std::vector<cv::Point2f> > corners; cv::aruco::detectMarkers(image, dictionary, corners, ids); // if at least one marker detected if (ids.size() > 0) { cv::aruco::drawDetectedMarkers(image_copy, corners, ids); std::vector<cv::Vec3d> rvecs, tvecs; cv::aruco::estimatePoseSingleMarkers(corners, actual_marker_length, camera_matrix, dist_coeffs, rvecs, tvecs); // draw axis for each marker for(int i=0; i < ids.size(); i++) { cv::aruco::drawAxis(image_copy, camera_matrix, dist_coeffs, rvecs[i], tvecs[i], 0.1); tf::Transform transform; transform.setOrigin( tf::Vector3(tvecs[i][0], tvecs[i][1], tvecs[i][2]) ); double alpha = sqrt(pow(rvecs[i][0], 2) + pow(rvecs[i][1], 2) + pow(rvecs[i][2], 2)); transform.setRotation( tf::Quaternion(rvecs[i][0] / alpha * sin(alpha/2), rvecs[i][1] / alpha * sin(alpha/2), rvecs[i][2] / alpha * sin(alpha/2), cos(alpha/2)) ); br.sendTransform( tf::StampedTransform(transform, ros::Time::now(), "camera/" + to_string(camera_id), "marker/" + to_string(ids[i])) ); vector_to_marker.str(std::string()); vector_to_marker << std::setprecision(4) << "x: " << std::setw(8)<< tvecs[i](0); cv::putText(image_copy, vector_to_marker.str(), cvPoint(10, 30), cv::FONT_HERSHEY_SIMPLEX, 0.6, cvScalar(0, 252, 124), 1, CV_AA); vector_to_marker.str(std::string()); vector_to_marker << std::setprecision(4) << "y: " << std::setw(8) << tvecs[i](1); cv::putText(image_copy, vector_to_marker.str(), cvPoint(10, 50), cv::FONT_HERSHEY_SIMPLEX, 0.6, cvScalar(0, 252, 124), 1, CV_AA); vector_to_marker.str(std::string()); vector_to_marker << std::setprecision(4) << "z: " << std::setw(8) << tvecs[i](2); cv::putText(image_copy, vector_to_marker.str(), cvPoint(10, 70), cv::FONT_HERSHEY_SIMPLEX, 0.6, cvScalar(0, 252, 124), 1, CV_AA); } } cv::imshow("Pose estimation", image_copy); //BLOB DETECTION SimpleBlobDetector::Params params; // // Change thresholds params.minThreshold = 50; params.maxThreshold = 80; //Filter by area params.filterByArea = true; params.minArea = 450; // // Filter by Circularity params.filterByCircularity = true; params.minCircularity = 0.2; params.blobColor = 255; Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params); Mat image_copy_bis; Mat segmented_image_green; Mat segmented_image_blue; Mat segmented_image_green_filtered; Mat segmented_image_blue_filtered; vector<vector<Point> > contours_green; vector<vector<Point> > contours_blue; vector<Vec4i> hierarchy; int largest_area_green=0; int largest_contour_index_green=0; int largest_area_blue=0; int largest_contour_index_blue=0; Scalar color_green = Scalar(0,255,0); // B G R values Scalar color_blue = Scalar(255,0,0); image.copyTo(image_copy_bis); //Green inRange(image_copy_bis, Scalar(30,81,40), Scalar(75,181,140), segmented_image_green); //Green cube //B,G,R // inRange(image_copy_bis, Scalar(50,90,70), Scalar(75,120,90), segmented_image_green); findContours( segmented_image_green, contours_green, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); Mat drawing(segmented_image_green.size(), CV_8UC3, Scalar(255,255,255)); //Find biggest contour for( int i = 0; i< contours_green.size(); i++ ) // iterate through each contour. { double a=contourArea( contours_green[i],false); // Find the area of contour if(a>largest_area_green) { largest_area_green=a; largest_contour_index_green=i; } } Moments mu_green; if (!contours_green.empty() && largest_area_green >= 1400 && largest_area_green < 3300) { mu_green = moments(contours_green[largest_contour_index_green], false ); Point2f mc_green; mc_green = Point2f( mu_green.m10/mu_green.m00 , mu_green.m01/mu_green.m00 ); drawContours(drawing, contours_green, largest_contour_index_green, color_green, 2, 8, hierarchy, 0, Point()); circle( drawing, mc_green, 4, color_green, -1, 8, 0 ); static tf::TransformBroadcaster brGreenBlob; tf::Transform transformGreenBlob; transformGreenBlob.setOrigin( tf::Vector3(mc_green.x, mc_green.y, 0.44)); //positions recuperees, 0.45 = z marker transformGreenBlob.setRotation( tf::Quaternion(0, 0, 0, 1)); brGreenBlob.sendTransform( tf::StampedTransform(transformGreenBlob, ros::Time::now(), "camera/" + to_string(camera_id), "green" )); } //Blue inRange(image_copy_bis, Scalar(60,20,6), Scalar(180,100,70), segmented_image_blue); //Blue cube // inRange(image_copy_bis, Scalar(90,80,50), Scalar(135,105,80), segmented_image_blue); findContours( segmented_image_blue, contours_blue, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); for( int i = 0; i< contours_blue.size(); i++ ) // iterate through each contour. { double a=contourArea( contours_blue[i],false); // Find the area of contour if(a>largest_area_blue) { largest_area_blue=a; largest_contour_index_blue=i; //Store the index of largest contour } } if (!contours_blue.empty() && largest_area_blue >= 1400 && largest_area_blue <= 3300) { Moments mu_blue; mu_blue = moments(contours_blue[largest_contour_index_blue], false ); Point2f mc_blue; mc_blue = Point2f( mu_blue.m10/mu_blue.m00 , mu_blue.m01/mu_blue.m00 ); drawContours(drawing, contours_blue, largest_contour_index_blue, color_blue, 2, 8, hierarchy, 0, Point()); circle( drawing, mc_blue, 4, color_blue, -1, 8, 0 ); static tf::TransformBroadcaster brBlueBlob; tf::Transform transformBlueBlob; transformBlueBlob.setOrigin( tf::Vector3(mc_blue.x, mc_blue.y, 0.44) ); transformBlueBlob.setRotation( tf::Quaternion(0, 0, 0, 1)); brBlueBlob.sendTransform( tf::StampedTransform(transformBlueBlob, ros::Time::now(), "camera/" + to_string(camera_id), "blue")); } namedWindow("Contours", CV_WINDOW_AUTOSIZE); imshow("Contours", drawing); char key = (char) cv::waitKey(wait_time); if (key == 27) break; } in_video.release(); }
40.778281
178
0.584887
[ "vector", "transform" ]
6d291ac84a5458e4c39b845b72dcf12c39fad18e
1,777
cpp
C++
Failed/B908_failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
Failed/B908_failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
Failed/B908_failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
#include <bits/stdc++.h> using namespace std; class B908 { private: int n,m,x0,y0,xn,yn,ans; char **G; bool **isVisited; vector<char> Stack; string s; public: void DFS(){ DFS_visit(x0,y0); cout<<"d2\n"; } void DFS_visit(int a,int b){ cout<<"a="<<a<<",b="<<b<<endl; cout<<"d3\n"; isVisited[a][b] = true; if(G[a][b]=='E'){ if(Stack.size() == s.length()){ ans++; }return; } cout<<"d4\n"; if(((a-1)>=0) && (!isVisited[a-1][b]) && (G[a-1][b]!='#')){ Stack.push_back('L'); DFS_visit(a-1,b); Stack.pop_back();} cout<<"d5\n"; if(((a+1)<m) && (!isVisited[a+1][b]) && (G[a+1][b]!='#') ){ Stack.push_back('R'); DFS_visit(a+1,b); Stack.pop_back();} cout<<"d6\n"; if(((b-1)>=0) && (!isVisited[a][b-1]) && (G[a][b-1]!='#')){ Stack.push_back('D');DFS_visit(a,b-1); Stack.pop_back();} cout<<"d7\n"; if(((b+1)<n) && (!isVisited[a][b+1]) && (G[a][b+1]!='#') ){ Stack.push_back('U'); DFS_visit(a,b+1); Stack.pop_back();} } B908(){ ans = 0; cin>>n>>m; G = new char*[n+10]; isVisited = new bool*[n+10]; for(int i=0; i<n; i++){ G[i]=new char[m+10]; isVisited[i] = new bool[m+10];} for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cin>>G[i][j]; if(G[i][j]=='S'){x0=i;y0=j;} if(G[i][j]=='E'){xn=i;yn=j;} } } cin>>s; /*for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cout<<G[i][j]; }cout<<endl;5 6 .....# S....# .#.... .#.... ...E.. 333300012 } cout<<s<<endl; cout<<G[x0][y0]<<G[xn][yn]<<endl;*/ cout<<"d1\n"; DFS(); cout<<ans<<endl; } ~B908(){ for(int i=0; i<n; i++){ if(!G[i])delete[] G[i]; if(!isVisited[i])delete[] isVisited; } if(!G)delete[] G; if(!isVisited)delete[] isVisited; } }; int main(int argc, char const *argv[]) { /* code */ B908 b908; return 0; }
19.966292
120
0.49184
[ "vector" ]
6d2a960f501b88350d082814eb296c9048ec9655
5,580
cc
C++
applications/physbam/smoke/job_loop_frame.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/smoke/job_loop_frame.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/smoke/job_loop_frame.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
/* * Copyright 2013 Stanford University. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * - Neither the name of the copyright holders 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. */ /* * This file contains a loop frame job that spawns loop iteration jobs to * calculate a frame of the simulation. It checks whether the last required * frame has compututed or not, if so it terminates the application. * * Author: Omid Mashayekhi <omidm@stanford.edu> * Modifier for smoke: Andrew Lim <alim16@stanford.edu> */ #include "applications/physbam/smoke/app_utils.h" #include "applications/physbam/smoke/job_loop_frame.h" #include "applications/physbam/smoke/smoke_driver.h" #include "applications/physbam/smoke/smoke_example.h" #include "applications/physbam/smoke/job_names.h" #include "applications/physbam/smoke/data_names.h" #include "src/data/physbam/physbam_data.h" #include "src/shared/dbg.h" #include "src/shared/nimbus.h" #include <sstream> #include <string> namespace application { JobLoopFrame::JobLoopFrame(nimbus::Application *app) { set_application(app); }; nimbus::Job* JobLoopFrame::Clone() { return new JobLoopFrame(application()); } void JobLoopFrame::Execute(nimbus::Parameter params, const nimbus::DataArray& da) { dbg(APP_LOG, "Executing loop frame job.\n"); // get frame from parameters int frame; GeometricRegion global_region; std::string params_str(params.ser_data().data_ptr_raw(), params.ser_data().size()); LoadParameter(params_str, &frame, &global_region); // get time from frame PhysBAM::SMOKE_EXAMPLE<TV>* example = new PhysBAM::SMOKE_EXAMPLE<TV>(PhysBAM::STREAM_TYPE((RW())), false, 1); T time = example->Time_At_Frame(frame); delete example; if (frame < (int)kLastFrame) { //Spawn the loop iteration job to start computing the frame. dbg(APP_LOG, "Loop frame is spawning loop iteration job for frame %i.\n", frame); int job_num = 1; std::vector<nimbus::job_id_t> job_ids; GetNewJobID(&job_ids, job_num); int calculate_dt_job_num = kAppPartNum; std::vector<nimbus::job_id_t> calculate_dt_job_ids; GetNewJobID(&calculate_dt_job_ids, calculate_dt_job_num); nimbus::IDSet<nimbus::logical_data_id_t> read, write; nimbus::IDSet<nimbus::job_id_t> before, after; nimbus::Parameter iter_params; for (int i = 0; i < calculate_dt_job_num; ++i) { read.clear(); LoadLdoIdsInSet( &read, ph.map()["kRegY2W3Outer"][i], APP_FACE_VEL, NULL); write.clear(); LoadLdoIdsInSet( &write, ph.map()["kRegY2W3Central"][i], APP_DT, NULL); before.clear(); after.clear(); nimbus::Parameter dt_params; std::string dt_str; SerializeParameter(frame, time, 0, global_region, ph.map()["kRegY2W3Central"][i], &dt_str); dt_params.set_ser_data(SerializedData(dt_str)); SpawnComputeJob(SUBSTEP, calculate_dt_job_ids[i], read, write, before, after, dt_params, true); } std::string str; SerializeParameter(frame, time, global_region, &str); iter_params.set_ser_data(SerializedData(str)); read.clear(); LoadLdoIdsInSet( &read, ph.map()["kRegW3Central"][0], APP_DT, NULL); write.clear(); before.clear(); for (int i = 0; i < calculate_dt_job_num; ++i) { before.insert(calculate_dt_job_ids[i]); } SpawnComputeJob(LOOP_ITERATION, job_ids[0], read, write, before, after, iter_params); } else { // Last job has been computed, just terminate the application. dbg(APP_LOG, "Simulation is complete, last frame computed.\n"); TerminateApplication(); } } } // namespace application
38.219178
91
0.651971
[ "vector" ]
6d2c4de4c2ad8b7f8faef0cd5034617377d80022
5,216
cpp
C++
plane_seg/src/plane-seg-20150423.cpp
wx-b/plane_seg
f94dc77c684225eded23f488d5b94baf579fd460
[ "BSD-3-Clause" ]
105
2020-11-02T09:08:50.000Z
2022-03-27T19:59:49.000Z
plane_seg/src/plane-seg-20150423.cpp
wx-b/plane_seg
f94dc77c684225eded23f488d5b94baf579fd460
[ "BSD-3-Clause" ]
62
2016-01-16T18:08:14.000Z
2016-03-24T15:16:28.000Z
plane_seg/src/plane-seg-20150423.cpp
wx-b/plane_seg
f94dc77c684225eded23f488d5b94baf579fd460
[ "BSD-3-Clause" ]
41
2016-01-14T21:26:58.000Z
2022-03-28T03:10:39.000Z
#include <string> #include <fstream> #include <unordered_map> #include <chrono> #include <drc_utils/RansacGeneric.hpp> #include <pcl/io/pcd_io.h> #include <pcl/filters/voxel_grid.h> #include <pcl/common/common.h> #include "RectangleFitter.hpp" #include "RobustNormalEstimator.hpp" #include "PlaneSegmenter.hpp" typedef pcl::PointCloud<pcl::Normal> NormalCloud; typedef pcl::PointCloud<pcl::PointXYZL> LabeledCloud; typedef Eigen::Matrix<float,Eigen::Dynamic,3> MatrixX3f; int main() { // read pcd file std::string inFile = "/home/antone/data/tilted-steps.pcd"; Eigen::Vector3f origin(0.248091, 0.012443, 1.806473); Eigen::Vector3f lookDir(0.837001, 0.019831, -0.546842); /* inFile = "/home/antone/data/2015-03-11_testbed/terrain_med.pcd"; origin << -0.028862, -0.007466, 0.087855; lookDir << 0.999890, -0.005120, -0.013947; inFile = "/home/antone/data/2015-03-11_testbed/terrain_close.pcd"; origin << -0.028775, -0.005776, 0.087898; lookDir << 0.999956, -0.005003, 0.007958; */ LabeledCloud::Ptr inCloud(new LabeledCloud()); pcl::io::loadPCDFile(inFile, *inCloud); std::cout << "Original cloud size " << inCloud->size() << std::endl; // voxelize LabeledCloud::Ptr cloud(new LabeledCloud()); pcl::VoxelGrid<pcl::PointXYZL> voxelGrid; voxelGrid.setInputCloud(inCloud); voxelGrid.setLeafSize (0.01f, 0.01f, 0.01f); voxelGrid.filter(*cloud); for (int i = 0; i < (int)cloud->size(); ++i) cloud->points[i].label = i; std::cout << "Voxelized cloud size " << cloud->size() << std::endl; // write cloud pcl::io::savePCDFileBinary("/home/antone/temp/cloud.pcd", *cloud); // pose cloud->sensor_origin_.head<3>() = origin; cloud->sensor_origin_[3] = 1; Eigen::Vector3f rz = lookDir; Eigen::Vector3f rx = rz.cross(Eigen::Vector3f::UnitZ()); Eigen::Vector3f ry = rz.cross(rx); Eigen::Matrix3f rotation; rotation.col(0) = rx.normalized(); rotation.col(1) = ry.normalized(); rotation.col(2) = rz.normalized(); Eigen::Isometry3f pose = Eigen::Isometry3f::Identity(); pose.linear() = rotation; pose.translation() = origin; // kdtree based normals auto t0 = std::chrono::high_resolution_clock::now(); std::cout << "computing normals..." << std::flush; RobustNormalEstimator normalEstimator; normalEstimator.setMaxEstimationError(0.01); normalEstimator.setRadius(0.1); normalEstimator.setMaxCenterError(0.02); normalEstimator.setMaxIterations(100); NormalCloud::Ptr normals(new NormalCloud()); normalEstimator.go(cloud, *normals); auto t1 = std::chrono::high_resolution_clock::now(); auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(t1-t0); std::cout << "finished in " << dt.count()/1e3 << " sec" << std::endl; // write normals pcl::io::savePCDFileBinary("/home/antone/temp/robust_normals.pcd", *normals); // try custom plane segmentation t0 = std::chrono::high_resolution_clock::now(); std::cout << "segmenting planes..." << std::flush; PlaneSegmenter segmenter; segmenter.setData(cloud, normals); segmenter.setMaxError(0.05); segmenter.setMaxAngle(10); segmenter.setMinPoints(100); PlaneSegmenter::Result result = segmenter.go(); t1 = std::chrono::high_resolution_clock::now(); dt = std::chrono::duration_cast<std::chrono::milliseconds>(t1-t0); std::cout << "finished in " << dt.count()/1e3 << " sec" << std::endl; { std::ofstream ofs("/home/antone/temp/labels.txt"); for (const int lab : result.mLabels) { ofs << lab << std::endl; } ofs.close(); } { std::ofstream ofs("/home/antone/temp/planes.txt"); for (auto it : result.mPlanes) { auto& plane = it.second; ofs << it.first << " " << plane.transpose() << std::endl; } ofs.close(); } // create point clouds std::unordered_map<int,std::vector<Eigen::Vector3f>> cloudMap; for (int i = 0; i < (int)result.mLabels.size(); ++i) { int label = result.mLabels[i]; if (label <= 0) continue; cloudMap[label].push_back(cloud->points[i].getVector3fMap()); } struct Plane { MatrixX3f mPoints; Eigen::Vector4f mPlane; }; std::vector<Plane> planes; planes.reserve(cloudMap.size()); for (auto it : cloudMap) { int n = it.second.size(); Plane plane; plane.mPoints.resize(n,3); for (int i = 0; i < n; ++i) plane.mPoints.row(i) = it.second[i]; plane.mPlane = result.mPlanes[it.first]; planes.push_back(plane); } std::vector<RectangleFitter::Result> results; for (auto& plane : planes) { RectangleFitter fitter; fitter.setData(plane.mPoints, plane.mPlane); auto result = fitter.go(); results.push_back(result); } { std::ofstream ofs("/home/antone/temp/boxes.txt"); for (int i = 0; i < (int)results.size(); ++i) { auto& res = results[i]; for (auto& p : res.mPolygon) { ofs << i << " " << p.transpose() << std::endl; } } ofs.close(); } { std::ofstream ofs("/home/antone/temp/hulls.txt"); for (int i = 0; i < (int)results.size(); ++i) { auto& res = results[i]; for (auto& p : res.mConvexHull) { ofs << i << " " << p.transpose() << std::endl; } } ofs.close(); } return 1; }
31.047619
74
0.645897
[ "vector" ]
6d2dd245b0b06ae95f4843fd020c19166e13a382
12,280
cpp
C++
Engine/General/System.cpp
BielBdeLuna/DarkXL
647f88835b78f0afc595c17ccb7410c0661c93a9
[ "MIT" ]
3
2020-02-21T13:25:46.000Z
2021-02-27T06:49:18.000Z
Engine/General/System.cpp
BielBdeLuna/DarkXL
647f88835b78f0afc595c17ccb7410c0661c93a9
[ "MIT" ]
null
null
null
Engine/General/System.cpp
BielBdeLuna/DarkXL
647f88835b78f0afc595c17ccb7410c0661c93a9
[ "MIT" ]
null
null
null
#include "System.h" #include "Map.h" #include "DXL_Console.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> bool System::m_bMissionComplete=false; bool System::m_abGoalComplete[16]; int System::m_nLogLevel = System::LOG_INFO; char System::m_szText[2048]; float System::m_fTexDispTime=0.0f; vector<System::TextMsg_t *> System::m_MsgList; int System::m_anSecretsFound[32]; int System::m_nSecretFoundCnt=0; int System::m_nTotalSecretCnt=0; vector<System::MsgHandler_t *> System::m_MsgHandlers; bool System::PostMsg(int msg, int val/*=0*/) { int i; bool bRet=true; switch (msg) { case SYSMSG_RESET: m_bMissionComplete = false; for (i=0; i<16; i++) { m_abGoalComplete[i] = false; } break; case SYSMSG_COMPLETE: if ( m_bMissionComplete ) bRet = false; m_bMissionComplete = true; for (int i=0; i<16; i++) { m_abGoalComplete[i] = true; } break; case SYSMSG_GOALCOMPLETE: if ( m_abGoalComplete[val] ) bRet = false; m_abGoalComplete[val] = true; break; }; return bRet; } bool System::IsGolComplete(int gol) { return m_abGoalComplete[gol]; } bool System::IsMissionComplete() { return m_bMissionComplete; } void System::SetSecretFound(int secID) { for (int s=0; s<m_nSecretFoundCnt; s++) { if ( m_anSecretsFound[s] == secID ) return; } m_anSecretsFound[m_nSecretFoundCnt++] = secID; } void System::Update(float dt) { m_fTexDispTime -= dt; if ( m_fTexDispTime < 0.0f ) m_fTexDispTime = 0.0f; } FILE *m_fLogFile = NULL; bool System::InitLogFile() { //setup variables and stuff. for (int i=0; i<16; i++) { char szGoalName[64]; sprintf(szGoalName, "g_goal%02d_complete", i); DXL_Console::RegisterCmd(szGoalName, &m_abGoalComplete[i], Console::CTYPE_BOOL, "Is the goal complete (0/1)?"); } DXL_Console::RegisterCmd("g_mission_complete", &m_bMissionComplete, Console::CTYPE_BOOL, "Are all the mission objectives complete (0/1)?"); m_fLogFile = fopen("DXL_Log.rtf", "wc"); if ( m_fLogFile ) { //RTF header. //fprintf(m_fLogFile, "{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0 Courier New;}}\\fs20\n"); fprintf(m_fLogFile, "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fswiss\\fcharset0 Courier New;}}\n"); //Color table fprintf(m_fLogFile, "{\\colortbl ;"); fprintf(m_fLogFile, "\\red255\\green255\\blue255;"); //White fprintf(m_fLogFile, "\\red128\\green128\\blue128;"); //Grey fprintf(m_fLogFile, "\\red255\\green0\\blue0;"); //Red fprintf(m_fLogFile, "\\red0\\green255\\blue0;"); //Green fprintf(m_fLogFile, "\\red0\\green0\\blue255;"); //Blue fprintf(m_fLogFile, "\\red0\\green255\\blue255;"); //Cyan fprintf(m_fLogFile, "\\red255\\green255\\blue0;"); //Yellow fprintf(m_fLogFile, "\\red255\\green0\\blue255;"); //Magenta fprintf(m_fLogFile, "\\red128\\green0\\blue0;"); //Dark Red fprintf(m_fLogFile, "\\red0\\green128\\blue0;"); //Dark Green fprintf(m_fLogFile, "\\red0\\green0\\blue128;"); //Dark Blue fprintf(m_fLogFile, "\\red255\\green128\\blue128;"); //Light Red fprintf(m_fLogFile, "\\red128\\green255\\blue128;"); //Light Green fprintf(m_fLogFile, "\\red128\\green128\\blue255;"); //Light Blue fprintf(m_fLogFile, "\\red255\\green128\\blue0;"); //Orange fprintf(m_fLogFile, "}\n"); fflush(m_fLogFile); LogMsg("DarkXL Alpha, Build 9.08", System::LOG_LightRed); Log(LogInfo, "Log File Open"); return true; } return false; } void System::CloseLogFile() { if ( m_fLogFile ) { Log(LogInfo, "Log File Close"); fprintf(m_fLogFile, "}\n"); fclose( m_fLogFile ); } m_fLogFile = NULL; } const char *m_apszColor[]= { "\\cf1", "\\cf1", "\\cf2", "\\cf3", "\\cf4", "\\cf5", "\\cf6", "\\cf7", "\\cf8", "\\cf9", "\\cf10", "\\cf11", "\\cf12", "\\cf13", "\\cf14", "\\cf15" }; static char szCommentStore[2048]; static char _tmpStr[2048]; void System::LogMessageF(int nType, const char *pszFunc, int line, const char *pszComment, ...) { if ( nType == LOG_VERBOSE && m_nLogLevel < LOG_VERBOSE ) { return; } int clr = 0; va_list args; va_start(args, pszComment); _vsnprintf( _tmpStr, 2048, pszComment, args ); va_end(args); int s=0; for (s=0; s<(int)strlen(_tmpStr); s++) { if ( _tmpStr[s] == '\\' ) { szCommentStore[s] = '/'; } else { szCommentStore[s] = _tmpStr[s]; } } szCommentStore[s] = 0; char szConsoleMsg[256]; switch (nType) { case System::LOG_ERROR: fprintf(m_fLogFile, "\\pard \\cf3 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "^1ERROR Func: %s, Line: %d, %s", pszFunc, line, szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_INFO: fprintf(m_fLogFile, "\\pard \\cf2 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "%s", szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_WARNING: fprintf(m_fLogFile, "\\pard \\cf15 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "^8WARNING %s", szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_VERBOSE: fprintf(m_fLogFile, "\\pard \\cf5 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "%s", szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_MSG: { fprintf(m_fLogFile, "\\pard %s \\b \\i %s \\b0 \\i0 \\par\n", m_apszColor[clr], szCommentStore); sprintf(szConsoleMsg, "%s", szCommentStore); DXL_Console::Print(szConsoleMsg); } break; } fflush(m_fLogFile); } void System::LogMessage(int nType, const char *pszFunc, int line, const char *pszComment, int clr/*=0*/) { if ( nType == LOG_VERBOSE && m_nLogLevel < LOG_VERBOSE ) { return; } int s=0; for (s=0; s<(int)strlen(pszComment); s++) { if ( pszComment[s] == '\\' ) { szCommentStore[s] = '/'; } else { szCommentStore[s] = pszComment[s]; } } szCommentStore[s] = 0; char szConsoleMsg[256]; switch (nType) { case System::LOG_ERROR: fprintf(m_fLogFile, "\\pard \\cf3 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "^1ERROR Func: %s, Line: %d, %s", pszFunc, line, szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_INFO: fprintf(m_fLogFile, "\\pard \\cf2 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "%s", szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_WARNING: fprintf(m_fLogFile, "\\pard \\cf15 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "^8WARNING %s", szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_VERBOSE: fprintf(m_fLogFile, "\\pard \\cf5 \\b <%s %d> \\b0 %s\\par\n", pszFunc, line, szCommentStore); sprintf(szConsoleMsg, "%s", szCommentStore); DXL_Console::Print(szConsoleMsg); break; case System::LOG_MSG: { fprintf(m_fLogFile, "\\pard %s \\b \\i %s \\b0 \\i0 \\par\n", m_apszColor[clr], szCommentStore); sprintf(szConsoleMsg, "%s", szCommentStore); DXL_Console::Print(szConsoleMsg); } break; } fflush(m_fLogFile); } void System::SetTextDisp(const char *pszText) { strcpy(m_szText, pszText); m_fTexDispTime = 5.0f; } void System::SetTextDispIndex(int index) { for (int i=0; i<(int)m_MsgList.size(); i++) { if ( m_MsgList[i]->index == index ) { strcpy(m_szText, m_MsgList[i]->szMsg); m_fTexDispTime = 5.0f; char szConsoleMsg[256]; sprintf(szConsoleMsg, "^6%s", m_szText); DXL_Console::Print(szConsoleMsg); break; } } } void System::Msg_ParseLine(char *pszLine) { static char szWorkingStr[2048]; if ( pszLine[0] == '#' ) { return; } strcpy(szWorkingStr, pszLine); int l = (int)strlen(szWorkingStr); //now remove leading spaces... int nSpaceEnd = -1; int ii; for (ii=0; ii<l; ii++) { if ( szWorkingStr[ii] > ' ' && szWorkingStr[ii] <= '~' ) { nSpaceEnd = ii-1; break; } } if ( nSpaceEnd > -1 ) { nSpaceEnd++; for (ii=0; ii<l-nSpaceEnd; ii++) { szWorkingStr[ii] = szWorkingStr[ii+nSpaceEnd]; } szWorkingStr[ii] = 0; } if ( szWorkingStr[0] == '#' || szWorkingStr[0] <= ' ' ) { return; } if ( szWorkingStr[0] == 'E' && szWorkingStr[1] == 'N' && szWorkingStr[2] == 'D' ) { return; } //# space(s) priority: space(s) "msg" //first extract the number... char szIndex[256]; int i, strIdx = 0; l = (int)strlen(szWorkingStr); for (i=0; i<l; i++) { if ( szWorkingStr[i] > ' ' ) { szIndex[i] = szWorkingStr[i]; strIdx++; } else { strIdx++; break; } } szIndex[i] = 0; //now extract priority. char szPriority[256]; int nPStart = -1; for (i=strIdx; i<l; i++) { if ( szWorkingStr[i] > ' ' ) { nPStart = i; break; } } for (i=nPStart; i<l; i++) { if ( szWorkingStr[i] != ':' ) { szPriority[i-nPStart] = szWorkingStr[i]; } else { break; } } szPriority[i-nPStart] = 0; //now extract the message itself. int nMsgStart = -1; for (; i<l; i++) { if ( szWorkingStr[i] == '"' ) { nMsgStart = i; break; } } char szMsg[256]; for (i=nMsgStart+1; i<l; i++) { if ( szWorkingStr[i] == '"' ) { break; } else { szMsg[i-(nMsgStart+1)] = szWorkingStr[i]; } } szMsg[i-(nMsgStart+1)] = 0; char *tmp; TextMsg_t *pMsg = new TextMsg_t; pMsg->index = (short)strtol(szIndex, &tmp, 10); pMsg->priority = (short)strtol(szPriority, &tmp, 10); strcpy(pMsg->szMsg, szMsg); m_MsgList.push_back(pMsg); } void System::Init(Map *pMap) { if ( pMap->m_pDarkGOB->OpenFile("TEXT.MSG") ) { long len = pMap->m_pDarkGOB->GetFileLen(); char *pData = new char[len+1]; pMap->m_pDarkGOB->ReadFile(pData); pMap->m_pDarkGOB->CloseFile(); //parse pData Map::m_pFileData = pData; Map::m_nFileSize = len; Map::m_nFilePtr = 0; int nMsgCnt=0; Map::SearchKeyword("MSGS", nMsgCnt); //now parse each line... char *pszCur = &pData[Map::m_nFilePtr]; char szLine[256]; int lineIdx = 0; int sl = (int)strlen(pszCur); for (int l=0; l<sl; l++) { if ( pszCur[l] == '\r' || pszCur[l] == '\n' ) { szLine[lineIdx] = 0; if ( lineIdx > 0 ) { Msg_ParseLine(szLine); } lineIdx = 0; szLine[lineIdx] = 0; } else { szLine[lineIdx] = pszCur[l]; lineIdx++; } } //free pData delete [] pData; pData = NULL; } } void System::Destroy() { if ( m_MsgList.size() > 0 ) { vector<TextMsg_t *>::iterator iter = m_MsgList.begin(); vector<TextMsg_t *>::iterator end = m_MsgList.end(); for (; iter!=end; ++iter) { TextMsg_t *pMsg = *iter; if ( pMsg ) { delete pMsg; } } m_MsgList.clear(); } if ( m_MsgHandlers.size() > 0 ) { vector<MsgHandler_t *>::iterator iter = m_MsgHandlers.begin(); vector<MsgHandler_t *>::iterator end = m_MsgHandlers.end(); for (; iter!=end; ++iter) { MsgHandler_t *pMsg = *iter; if ( pMsg ) { delete pMsg; } } m_MsgHandlers.clear(); } } const char *System::GetTextDisp() { if ( m_fTexDispTime > 0.0f ) { return m_szText; } return NULL; } void System::RegisterMsgHandler(int ID, void *pUserData, MsgHandlerFunc_t msgHandler) { MsgHandler_t *pNewHandler = new MsgHandler_t; if ( pNewHandler ) { pNewHandler->ID = ID; pNewHandler->msgFunc = msgHandler; pNewHandler->pUserData = pUserData; m_MsgHandlers.push_back( pNewHandler ); } } void System::PostGameMessage(int ID, void *pData) { vector<MsgHandler_t *>::iterator iter = m_MsgHandlers.begin(); vector<MsgHandler_t *>::iterator end = m_MsgHandlers.end(); for (; iter!=end; ++iter) { MsgHandler_t *pMsg = *iter; if ( pMsg->ID == ID ) { pMsg->msgFunc( pMsg->pUserData, pData ); } } }
23.479924
141
0.602687
[ "vector" ]
6d3325af8eff24f391362ab5b5af806ed0e87b87
21,058
tpp
C++
vpr/src/timing/PostClusterDelayCalculator.tpp
HubertSun7/vtr-verilog-to-routing
190dbbeffc1ad82adb2779f56d6b70cfd6de8d29
[ "MIT" ]
1
2020-05-07T17:38:58.000Z
2020-05-07T17:38:58.000Z
vpr/src/timing/PostClusterDelayCalculator.tpp
MohamedEldafrawy/vtr-verilog-to-routing
190dbbeffc1ad82adb2779f56d6b70cfd6de8d29
[ "MIT" ]
null
null
null
vpr/src/timing/PostClusterDelayCalculator.tpp
MohamedEldafrawy/vtr-verilog-to-routing
190dbbeffc1ad82adb2779f56d6b70cfd6de8d29
[ "MIT" ]
null
null
null
#include <cmath> #include "PostClusterDelayCalculator.h" #include "vpr_error.h" #include "vpr_utils.h" #include "globals.h" #include "vtr_assert.h" //Print detailed debug info about edge delay calculation /*#define POST_CLUSTER_DELAY_CALC_DEBUG*/ inline PostClusterDelayCalculator::PostClusterDelayCalculator(const AtomNetlist& netlist, const AtomLookup& netlist_lookup, vtr::vector<ClusterNetId, float*>& net_delay) : netlist_(netlist) , netlist_lookup_(netlist_lookup) , net_delay_() , atom_delay_calc_(netlist, netlist_lookup) , edge_min_delay_cache_(g_vpr_ctx.timing().graph->edges().size(), tatum::Time(NAN)) , edge_max_delay_cache_(g_vpr_ctx.timing().graph->edges().size(), tatum::Time(NAN)) , driver_clb_min_delay_cache_(g_vpr_ctx.timing().graph->edges().size(), tatum::Time(NAN)) , driver_clb_max_delay_cache_(g_vpr_ctx.timing().graph->edges().size(), tatum::Time(NAN)) , sink_clb_min_delay_cache_(g_vpr_ctx.timing().graph->edges().size(), tatum::Time(NAN)) , sink_clb_max_delay_cache_(g_vpr_ctx.timing().graph->edges().size(), tatum::Time(NAN)) , pin_cache_min_(g_vpr_ctx.timing().graph->edges().size(), std::pair<ClusterPinId, ClusterPinId>(ClusterPinId::INVALID(), ClusterPinId::INVALID())) , pin_cache_max_(g_vpr_ctx.timing().graph->edges().size(), std::pair<ClusterPinId, ClusterPinId>(ClusterPinId::INVALID(), ClusterPinId::INVALID())) { net_delay_ = net_delay; } inline void PostClusterDelayCalculator::clear_cache() { std::fill(edge_min_delay_cache_.begin(), edge_min_delay_cache_.end(), tatum::Time(NAN)); std::fill(edge_max_delay_cache_.begin(), edge_max_delay_cache_.end(), tatum::Time(NAN)); std::fill(driver_clb_min_delay_cache_.begin(), driver_clb_min_delay_cache_.end(), tatum::Time(NAN)); std::fill(driver_clb_max_delay_cache_.begin(), driver_clb_max_delay_cache_.end(), tatum::Time(NAN)); std::fill(sink_clb_min_delay_cache_.begin(), sink_clb_min_delay_cache_.end(), tatum::Time(NAN)); std::fill(sink_clb_max_delay_cache_.begin(), sink_clb_max_delay_cache_.end(), tatum::Time(NAN)); std::fill(pin_cache_min_.begin(), pin_cache_min_.end(), std::pair<ClusterPinId, ClusterPinId>(ClusterPinId::INVALID(), ClusterPinId::INVALID())); std::fill(pin_cache_max_.begin(), pin_cache_max_.end(), std::pair<ClusterPinId, ClusterPinId>(ClusterPinId::INVALID(), ClusterPinId::INVALID())); } inline void PostClusterDelayCalculator::set_tsu_margin_relative(float new_margin) { tsu_margin_rel_ = new_margin; } inline void PostClusterDelayCalculator::set_tsu_margin_absolute(float new_margin) { tsu_margin_abs_ = new_margin; } inline tatum::Time PostClusterDelayCalculator::max_edge_delay(const tatum::TimingGraph& tg, tatum::EdgeId edge_id) const { #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG("=== Edge %zu (max) ===\n", size_t(edge_id)); #endif return calc_edge_delay(tg, edge_id, DelayType::MAX); } inline tatum::Time PostClusterDelayCalculator::min_edge_delay(const tatum::TimingGraph& tg, tatum::EdgeId edge_id) const { #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG("=== Edge %zu (min) ===\n", size_t(edge_id)); #endif return calc_edge_delay(tg, edge_id, DelayType::MIN); } inline tatum::Time PostClusterDelayCalculator::setup_time(const tatum::TimingGraph& tg, tatum::EdgeId edge_id) const { #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG("=== Edge %zu (setup) ===\n", size_t(edge_id)); #endif return atom_setup_time(tg, edge_id); } inline tatum::Time PostClusterDelayCalculator::hold_time(const tatum::TimingGraph& tg, tatum::EdgeId edge_id) const { #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG("=== Edge %zu (hold) ===\n", size_t(edge_id)); #endif return atom_hold_time(tg, edge_id); } inline tatum::Time PostClusterDelayCalculator::calc_edge_delay(const tatum::TimingGraph& tg, tatum::EdgeId edge, DelayType delay_type) const { tatum::EdgeType edge_type = tg.edge_type(edge); if (edge_type == tatum::EdgeType::PRIMITIVE_COMBINATIONAL) { return atom_combinational_delay(tg, edge, delay_type); } else if (edge_type == tatum::EdgeType::PRIMITIVE_CLOCK_LAUNCH) { return atom_clock_to_q_delay(tg, edge, delay_type); } else if (edge_type == tatum::EdgeType::INTERCONNECT) { return atom_net_delay(tg, edge, delay_type); } VPR_FATAL_ERROR(VPR_ERROR_TIMING, "Invalid edge type"); return tatum::Time(NAN); //Suppress compiler warning } inline tatum::Time PostClusterDelayCalculator::atom_combinational_delay(const tatum::TimingGraph& tg, tatum::EdgeId edge_id, DelayType delay_type) const { tatum::Time delay = get_cached_delay(edge_id, delay_type); if (std::isnan(delay.value())) { //Miss tatum::NodeId src_node = tg.edge_src_node(edge_id); tatum::NodeId sink_node = tg.edge_sink_node(edge_id); AtomPinId src_pin = netlist_lookup_.tnode_atom_pin(src_node); AtomPinId sink_pin = netlist_lookup_.tnode_atom_pin(sink_node); delay = tatum::Time(atom_delay_calc_.atom_combinational_delay(src_pin, sink_pin, delay_type)); //Insert set_cached_delay(edge_id, delay_type, delay); } #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu Atom Comb Delay: %g\n", size_t(edge_id), delay.value()); #endif return delay; } inline tatum::Time PostClusterDelayCalculator::atom_setup_time(const tatum::TimingGraph& tg, tatum::EdgeId edge_id) const { tatum::Time tsu = get_cached_setup_time(edge_id); if (std::isnan(tsu.value())) { //Miss tatum::NodeId clock_node = tg.edge_src_node(edge_id); VTR_ASSERT(tg.node_type(clock_node) == tatum::NodeType::CPIN); tatum::NodeId in_node = tg.edge_sink_node(edge_id); VTR_ASSERT(tg.node_type(in_node) == tatum::NodeType::SINK); AtomPinId input_pin = netlist_lookup_.tnode_atom_pin(in_node); AtomPinId clock_pin = netlist_lookup_.tnode_atom_pin(clock_node); tsu = tatum::Time(tsu_margin_rel_ * atom_delay_calc_.atom_setup_time(clock_pin, input_pin) + tsu_margin_abs_); //Insert set_cached_setup_time(edge_id, tsu); } #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu Atom Tsu: %g\n", size_t(edge_id), tsu.value()); #endif return tsu; } inline tatum::Time PostClusterDelayCalculator::atom_hold_time(const tatum::TimingGraph& tg, tatum::EdgeId edge_id) const { tatum::Time thld = get_cached_hold_time(edge_id); if (std::isnan(thld.value())) { //Miss tatum::NodeId clock_node = tg.edge_src_node(edge_id); VTR_ASSERT(tg.node_type(clock_node) == tatum::NodeType::CPIN); tatum::NodeId in_node = tg.edge_sink_node(edge_id); VTR_ASSERT(tg.node_type(in_node) == tatum::NodeType::SINK); AtomPinId input_pin = netlist_lookup_.tnode_atom_pin(in_node); AtomPinId clock_pin = netlist_lookup_.tnode_atom_pin(clock_node); thld = tatum::Time(atom_delay_calc_.atom_hold_time(clock_pin, input_pin)); //Insert set_cached_hold_time(edge_id, thld); } #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu Atom Thld: %g\n", size_t(edge_id), thld.value()); #endif return thld; } inline tatum::Time PostClusterDelayCalculator::atom_clock_to_q_delay(const tatum::TimingGraph& tg, tatum::EdgeId edge_id, DelayType delay_type) const { tatum::Time tco = get_cached_delay(edge_id, delay_type); if (std::isnan(tco.value())) { //Miss tatum::NodeId clock_node = tg.edge_src_node(edge_id); VTR_ASSERT(tg.node_type(clock_node) == tatum::NodeType::CPIN); tatum::NodeId out_node = tg.edge_sink_node(edge_id); VTR_ASSERT(tg.node_type(out_node) == tatum::NodeType::SOURCE); AtomPinId output_pin = netlist_lookup_.tnode_atom_pin(out_node); AtomPinId clock_pin = netlist_lookup_.tnode_atom_pin(clock_node); tco = tatum::Time(atom_delay_calc_.atom_clock_to_q_delay(clock_pin, output_pin, delay_type)); //Insert set_cached_delay(edge_id, delay_type, tco); } #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu Atom Tco: %g\n", size_t(edge_id), tco.value()); #endif return tco; } inline tatum::Time PostClusterDelayCalculator::atom_net_delay(const tatum::TimingGraph& tg, tatum::EdgeId edge_id, DelayType delay_type) const { //A net in the atom netlist consists of several different delay components: // // delay = launch_cluster_delay + inter_cluster_delay + capture_cluster_delay // //where: // * launch_cluster_delay is the delay from the primitive output pin to the cluster output pin, // * inter_cluster_delay is the routing delay through the inter-cluster routing network, and // * catpure_cluster_delay is the delay from the cluster input pin to the primitive input pin // //Note that if the connection is completely absorbed within the cluster then inter_cluster_delay //and capture_cluster_delay will both be zero. auto& cluster_ctx = g_vpr_ctx.clustering(); ClusterNetId net_id = ClusterNetId::INVALID(); int src_block_pin_index, sink_net_pin_index, sink_block_pin_index; tatum::Time edge_delay = get_cached_delay(edge_id, delay_type); if (std::isnan(edge_delay.value())) { //Miss //Note that the net pin pair will only be valid if we have already processed and cached //the clb delays on a previous call ClusterPinId src_pin = ClusterPinId::INVALID(); ClusterPinId sink_pin = ClusterPinId::INVALID(); std::tie(src_pin, sink_pin) = get_cached_pins(edge_id, delay_type); if (src_pin == ClusterPinId::INVALID() && sink_pin == ClusterPinId::INVALID()) { //No cached intermediate results tatum::NodeId src_node = tg.edge_src_node(edge_id); tatum::NodeId sink_node = tg.edge_sink_node(edge_id); AtomPinId atom_src_pin = netlist_lookup_.tnode_atom_pin(src_node); VTR_ASSERT(atom_src_pin); AtomPinId atom_sink_pin = netlist_lookup_.tnode_atom_pin(sink_node); VTR_ASSERT(atom_sink_pin); AtomBlockId atom_src_block = netlist_.pin_block(atom_src_pin); AtomBlockId atom_sink_block = netlist_.pin_block(atom_sink_pin); ClusterBlockId clb_src_block = netlist_lookup_.atom_clb(atom_src_block); VTR_ASSERT(clb_src_block != ClusterBlockId::INVALID()); ClusterBlockId clb_sink_block = netlist_lookup_.atom_clb(atom_sink_block); VTR_ASSERT(clb_sink_block != ClusterBlockId::INVALID()); const t_pb_graph_pin* src_gpin = netlist_lookup_.atom_pin_pb_graph_pin(atom_src_pin); VTR_ASSERT(src_gpin); const t_pb_graph_pin* sink_gpin = netlist_lookup_.atom_pin_pb_graph_pin(atom_sink_pin); VTR_ASSERT(sink_gpin); int src_pb_route_id = src_gpin->pin_count_in_cluster; int sink_pb_route_id = sink_gpin->pin_count_in_cluster; AtomNetId atom_net = netlist_.pin_net(atom_sink_pin); VTR_ASSERT(cluster_ctx.clb_nlist.block_pb(clb_src_block)->pb_route[src_pb_route_id].atom_net_id == atom_net); VTR_ASSERT(cluster_ctx.clb_nlist.block_pb(clb_sink_block)->pb_route[sink_pb_route_id].atom_net_id == atom_net); //NOTE: even if both the source and sink atoms are contained in the same top-level // CLB, the connection between them may not have been absorbed, and may go // through the global routing network. //We trace the delay backward from the atom sink pin to the source //Either the atom source pin (in the same cluster), or a cluster input pin std::tie(net_id, sink_block_pin_index, sink_net_pin_index) = find_pb_route_clb_input_net_pin(clb_sink_block, sink_pb_route_id); if (net_id != ClusterNetId::INVALID() && sink_block_pin_index != -1 && sink_net_pin_index != -1) { //Connection leaves the CLB ClusterBlockId driver_block_id = cluster_ctx.clb_nlist.net_driver_block(net_id); VTR_ASSERT(driver_block_id == clb_src_block); src_block_pin_index = cluster_ctx.clb_nlist.net_pin_physical_index(net_id, 0); tatum::Time driver_clb_delay = tatum::Time(clb_delay_calc_.internal_src_to_clb_output_delay(driver_block_id, src_block_pin_index, src_pb_route_id, delay_type)); tatum::Time net_delay = tatum::Time(inter_cluster_delay(net_id, 0, sink_net_pin_index)); tatum::Time sink_clb_delay = tatum::Time(clb_delay_calc_.clb_input_to_internal_sink_delay(clb_sink_block, sink_block_pin_index, sink_pb_route_id, delay_type)); edge_delay = driver_clb_delay + net_delay + sink_clb_delay; //Save the clb delays (but not the net delay since it may change during placement) //Also save the source and sink pins associated with these delays set_driver_clb_cached_delay(edge_id, delay_type, driver_clb_delay); set_sink_clb_cached_delay(edge_id, delay_type, sink_clb_delay); src_pin = cluster_ctx.clb_nlist.net_driver(net_id); sink_pin = *(cluster_ctx.clb_nlist.net_pins(net_id).begin() + sink_net_pin_index); VTR_ASSERT(src_pin != ClusterPinId::INVALID()); VTR_ASSERT(sink_pin != ClusterPinId::INVALID()); set_cached_pins(edge_id, delay_type, src_pin, sink_pin); #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu net delay: %g = %g + %g + %g (= clb_driver + net + clb_sink) [UNcached]\n", size_t(edge_id), edge_delay.value(), driver_clb_delay.value(), net_delay.value(), sink_clb_delay.value()); #endif } else { //Connection entirely within the CLB VTR_ASSERT(clb_src_block == clb_sink_block); edge_delay = tatum::Time(clb_delay_calc_.internal_src_to_internal_sink_delay(clb_src_block, src_pb_route_id, sink_pb_route_id, delay_type)); //Save the delay, since it won't change during placement or routing // Note that we cache the full edge delay for edges completely contained within CLBs set_cached_delay(edge_id, delay_type, edge_delay); #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu CLB Internal delay: %g [UNcached]\n", size_t(edge_id), edge_delay.value()); #endif } } else { //Calculate the edge delay using cached clb delays and the latest net delay // // Note: we do not need to handle the case of edges fully contained within CLBs, // since such delays are cached using edge_delay_cache_ and are handled earlier VTR_ASSERT(src_pin != ClusterPinId::INVALID()); VTR_ASSERT(sink_pin != ClusterPinId::INVALID()); tatum::Time driver_clb_delay = get_driver_clb_cached_delay(edge_id, delay_type); tatum::Time sink_clb_delay = get_sink_clb_cached_delay(edge_id, delay_type); VTR_ASSERT(!std::isnan(driver_clb_delay.value())); VTR_ASSERT(!std::isnan(sink_clb_delay.value())); ClusterNetId src_net = cluster_ctx.clb_nlist.pin_net(src_pin); VTR_ASSERT(src_net == cluster_ctx.clb_nlist.pin_net(sink_pin)); tatum::Time net_delay = tatum::Time(inter_cluster_delay(src_net, 0, cluster_ctx.clb_nlist.pin_net_index(sink_pin))); edge_delay = driver_clb_delay + net_delay + sink_clb_delay; #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu net delay: %g = %g + %g + %g (= clb_driver + net + clb_sink) [Cached]\n", size_t(edge_id), edge_delay.value(), driver_clb_delay.value(), net_delay.value(), sink_clb_delay.value()); #endif } } else { #ifdef POST_CLUSTER_DELAY_CALC_DEBUG VTR_LOG(" Edge %zu CLB Internal delay: %g [Cached]\n", size_t(edge_id), edge_delay.value()); #endif } VTR_ASSERT(!std::isnan(edge_delay.value())); return edge_delay; } inline float PostClusterDelayCalculator::inter_cluster_delay(const ClusterNetId net_id, const int src_net_pin_index, const int sink_net_pin_index) const { VTR_ASSERT(src_net_pin_index == 0); //TODO: support minimum net delays return net_delay_[net_id][sink_net_pin_index]; } inline tatum::Time PostClusterDelayCalculator::get_cached_delay(tatum::EdgeId edge, DelayType delay_type) const { if (delay_type == DelayType::MAX) { return edge_max_delay_cache_[edge]; } else { VTR_ASSERT(delay_type == DelayType::MIN); return edge_min_delay_cache_[edge]; } } inline void PostClusterDelayCalculator::set_cached_delay(tatum::EdgeId edge, DelayType delay_type, tatum::Time delay) const { if (delay_type == DelayType::MAX) { edge_max_delay_cache_[edge] = delay; } else { VTR_ASSERT(delay_type == DelayType::MIN); edge_min_delay_cache_[edge] = delay; } } inline void PostClusterDelayCalculator::set_driver_clb_cached_delay(tatum::EdgeId edge, DelayType delay_type, tatum::Time delay) const { if (delay_type == DelayType::MAX) { driver_clb_max_delay_cache_[edge] = delay; } else { VTR_ASSERT(delay_type == DelayType::MIN); driver_clb_min_delay_cache_[edge] = delay; } } inline tatum::Time PostClusterDelayCalculator::get_driver_clb_cached_delay(tatum::EdgeId edge, DelayType delay_type) const { if (delay_type == DelayType::MAX) { return driver_clb_max_delay_cache_[edge]; } else { VTR_ASSERT(delay_type == DelayType::MIN); return driver_clb_min_delay_cache_[edge]; } } inline void PostClusterDelayCalculator::set_sink_clb_cached_delay(tatum::EdgeId edge, DelayType delay_type, tatum::Time delay) const { if (delay_type == DelayType::MAX) { sink_clb_max_delay_cache_[edge] = delay; } else { VTR_ASSERT(delay_type == DelayType::MIN); sink_clb_min_delay_cache_[edge] = delay; } } inline tatum::Time PostClusterDelayCalculator::get_sink_clb_cached_delay(tatum::EdgeId edge, DelayType delay_type) const { if (delay_type == DelayType::MAX) { return sink_clb_max_delay_cache_[edge]; } else { VTR_ASSERT(delay_type == DelayType::MIN); return sink_clb_min_delay_cache_[edge]; } } inline tatum::Time PostClusterDelayCalculator::get_cached_setup_time(tatum::EdgeId edge) const { //We store the cached setup times in the max delay cache, since there will be no regular edge //delays on setup edges return edge_max_delay_cache_[edge]; } inline void PostClusterDelayCalculator::set_cached_setup_time(tatum::EdgeId edge, tatum::Time setup) const { edge_max_delay_cache_[edge] = setup; } inline tatum::Time PostClusterDelayCalculator::get_cached_hold_time(tatum::EdgeId edge) const { //We store the cached hold times in the min delay cache, since there will be no regular edge //delays on hold edges return edge_min_delay_cache_[edge]; } inline void PostClusterDelayCalculator::set_cached_hold_time(tatum::EdgeId edge, tatum::Time hold) const { edge_min_delay_cache_[edge] = hold; } inline std::pair<ClusterPinId, ClusterPinId> PostClusterDelayCalculator::get_cached_pins(tatum::EdgeId edge, DelayType delay_type) const { if (delay_type == DelayType::MAX) { return pin_cache_max_[edge]; } else { VTR_ASSERT(delay_type == DelayType::MIN); return pin_cache_min_[edge]; } } inline void PostClusterDelayCalculator::set_cached_pins(tatum::EdgeId edge, DelayType delay_type, ClusterPinId src_pin, ClusterPinId sink_pin) const { if (delay_type == DelayType::MAX) { pin_cache_max_[edge] = std::make_pair(src_pin, sink_pin); } else { VTR_ASSERT(delay_type == DelayType::MIN); pin_cache_min_[edge] = std::make_pair(src_pin, sink_pin); } }
46.281319
156
0.670909
[ "vector" ]
6d34f7fbdf03af0cda04181168474d8a91ece4c7
8,107
cpp
C++
src/GafferArnoldUI/DecayVisualiser.cpp
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
[ "BSD-3-Clause" ]
561
2016-10-18T04:30:48.000Z
2022-03-30T06:52:04.000Z
src/GafferArnoldUI/DecayVisualiser.cpp
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
[ "BSD-3-Clause" ]
1,828
2016-10-14T19:01:46.000Z
2022-03-30T16:07:19.000Z
src/GafferArnoldUI/DecayVisualiser.cpp
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
[ "BSD-3-Clause" ]
120
2016-10-18T15:19:13.000Z
2021-12-20T16:28:23.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine. 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferScene/Private/IECoreGLPreview/LightFilterVisualiser.h" #include "IECoreGL/Group.h" #include "IECoreGL/Primitive.h" #include "IECoreGL/Renderable.h" #include "IECoreGL/ShaderLoader.h" #include "IECoreGL/ShaderStateComponent.h" #include "IECoreGL/TextureLoader.h" #include "IECoreGL/ToGLMeshConverter.h" #include "IECoreScene/MeshPrimitive.h" #include "IECore/CompoundObject.h" using namespace Imath; using namespace IECore; using namespace IECoreScene; using namespace IECoreGL; using namespace IECoreGLPreview; namespace { typedef std::pair<float, V3f> Knot; typedef std::vector<Knot> KnotVector; const char *faceCameraVertexSource() { return "#version 120\n" "" "#if __VERSION__ <= 120\n" "#define in attribute\n" "#endif\n" "" "in vec3 vertexP;" "void main()" "{" "vec3 aimedXAxis, aimedYAxis, aimedZAxis;" "" "aimedXAxis = normalize( gl_ModelViewMatrixInverse * vec4( 0, 0, -1, 0 ) ).xyz;" "aimedYAxis = normalize( gl_ModelViewMatrixInverse * vec4( 0, 1, 0, 0 ) ).xyz;" "aimedZAxis = normalize( gl_ModelViewMatrixInverse * vec4( 1, 0, 0, 0 ) ).xyz;" "" "vec3 pAimed = vertexP.x * aimedXAxis + vertexP.y * aimedYAxis + vertexP.z * aimedZAxis;" "vec4 pCam = gl_ModelViewMatrix * vec4( pAimed, 1 );" "" "gl_Position = gl_ProjectionMatrix * pCam;" "}" ; } const char *knotFragSource() { return "uniform vec3 markerColor;" "" "void main()" "{" "gl_FragColor = vec4(markerColor, 1);" "}" ; } // \todo These should be consolidated with the function in BarndoorVisualiser into a templatized version // Where should that live? float parameterOrDefault( const IECore::CompoundData *data, const char *key, const float def ) { ConstFloatDataPtr member = data->member<const FloatData>( key ); if( member ) { return member->readable(); } return def; } bool parameterOrDefault( const IECore::CompoundData *data, const char *key, const bool def ) { ConstBoolDataPtr member = data->member<const BoolData>( key ); if( member ) { return member->readable(); } return def; } void getKnotsToVisualize( const IECoreScene::ShaderNetwork *shaderNetwork, KnotVector &knots ) { const IECore::CompoundData *filterShaderParameters = shaderNetwork->outputShader()->parametersData(); bool nearEnabled = parameterOrDefault( filterShaderParameters, "use_near_atten", false ); bool farEnabled = parameterOrDefault( filterShaderParameters, "use_far_atten", false ); if( nearEnabled ) { float nearStart = parameterOrDefault( filterShaderParameters, "near_start", 0.0f ); float nearEnd = parameterOrDefault( filterShaderParameters, "near_end", 0.0f ); knots.push_back( Knot( nearStart, V3f( 0.0f ) ) ); knots.push_back( Knot( nearEnd, V3f( 1.0f ) ) ); } if( farEnabled ) { float farStart = parameterOrDefault( filterShaderParameters, "far_start", 0.0f ); float farEnd = parameterOrDefault( filterShaderParameters, "far_end", 0.0f ); knots.push_back( Knot( farStart, V3f( 1.0f ) ) ); knots.push_back( Knot( farEnd, V3f( 0.0f ) ) ); } } void addKnot( IECoreGL::GroupPtr group, const Knot &knot ) { IECoreGL::GroupPtr markerGroup = new IECoreGL::Group(); IntVectorDataPtr vertsPerPoly = new IntVectorData; std::vector<int> &vertsPerPolyVec = vertsPerPoly->writable(); vertsPerPolyVec.push_back( 3 ); IntVectorDataPtr vertIds = new IntVectorData; std::vector<int> &vertIdsVec = vertIds->writable(); vertIdsVec.push_back( 0 ); vertIdsVec.push_back( 1 ); vertIdsVec.push_back( 2 ); V3fVectorDataPtr p = new V3fVectorData; std::vector<V3f> &pVec = p->writable(); pVec.push_back( V3f( 0, 0, 0 ) ); pVec.push_back( V3f( 0, 1, -1 ) ); pVec.push_back( V3f( 0, 1, 1 ) ); IECoreScene::MeshPrimitivePtr mesh = new IECoreScene::MeshPrimitive( vertsPerPoly, vertIds, "linear", p ); ToGLMeshConverterPtr meshConverter = new ToGLMeshConverter( mesh ); markerGroup->addChild( IECore::runTimeCast<IECoreGL::Renderable>( meshConverter->convert() ) ); Imath::M44f trans; trans.translate( V3f( 0, 0, -knot.first ) ); trans.scale( V3f( 0.05 ) ); markerGroup->setTransform( trans ); IECore::CompoundObjectPtr shaderParameters = new CompoundObject; shaderParameters->members()["markerColor"] = new IECore::Color3fData( knot.second ); markerGroup->getState()->add( new IECoreGL::Primitive::Selectable( false ) ); markerGroup->getState()->add( new IECoreGL::ShaderStateComponent( ShaderLoader::defaultShaderLoader(), TextureLoader::defaultTextureLoader(), faceCameraVertexSource(), "", knotFragSource(), shaderParameters ) ); group->addChild( markerGroup ); } class DecayVisualiser final : public LightFilterVisualiser { public : IE_CORE_DECLAREMEMBERPTR( DecayVisualiser ) DecayVisualiser(); ~DecayVisualiser() override; Visualisations visualise( const IECore::InternedString &attributeName, const IECoreScene::ShaderNetwork *shaderNetwork, const IECoreScene::ShaderNetwork *lightShaderNetwork, const IECore::CompoundObject *attributes, IECoreGL::ConstStatePtr &state ) const override; protected : static LightFilterVisualiser::LightFilterVisualiserDescription<DecayVisualiser> g_visualiserDescription; }; IE_CORE_DECLAREPTR( DecayVisualiser ) // register the new visualiser LightFilterVisualiser::LightFilterVisualiserDescription<DecayVisualiser> DecayVisualiser::g_visualiserDescription( "ai:lightFilter", "light_decay" ); DecayVisualiser::DecayVisualiser() { } DecayVisualiser::~DecayVisualiser() { } Visualisations DecayVisualiser::visualise( const IECore::InternedString &attributeName, const IECoreScene::ShaderNetwork *shaderNetwork, const IECoreScene::ShaderNetwork *lightShaderNetwork, const IECore::CompoundObject *attributes, IECoreGL::ConstStatePtr &state ) const { KnotVector knots; getKnotsToVisualize( shaderNetwork, knots ); if( knots.empty() ) { return {}; } IECoreGL::GroupPtr result = new IECoreGL::Group(); for( KnotVector::size_type i = 0; i < knots.size(); ++i ) { addKnot( result, knots[i] ); } // On the whole in Gaffer we assume that light scale doesn't affect the // render (this may need to be configurable later). Decay shouldn't scale // with visualisation scale either though. return { Visualisation( result, Visualisation::Scale::None ) }; } } // namespace
32.558233
271
0.718515
[ "mesh", "render", "vector" ]
6d3644c9f49479d2d4044adf55afd212f142a060
3,725
cpp
C++
src/consumer/DefaultMQPushConsumer.cpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
5
2019-04-24T13:37:05.000Z
2021-01-29T16:37:55.000Z
src/consumer/DefaultMQPushConsumer.cpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
null
null
null
src/consumer/DefaultMQPushConsumer.cpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
1
2021-02-03T03:11:03.000Z
2021-02-03T03:11:03.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DefaultMQPushConsumer.h" #include <vector> #include "DefaultMQPushConsumerConfigImpl.hpp" #include "DefaultMQPushConsumerImpl.h" #include "MQClientConfigProxy.h" #include "UtilAll.h" namespace rocketmq { namespace { class MessageListenerImpl { public: MessageListenerImpl(MQMessageListener* listener) : listener_(listener) {} ConsumeStatus operator()(std::vector<MessageExtPtr>& messages) { auto message_list = MQMessageExt::Wrap(messages); return listener_->consumeMessage(message_list); } private: MQMessageListener* listener_; }; } // namespace DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& groupname) : DefaultMQPushConsumer(groupname, nullptr) {} DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& groupname, RPCHookPtr rpc_hook) : DefaultMQPushConsumer(groupname, rpc_hook, std::make_shared<DefaultMQPushConsumerConfigImpl>()) {} DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& groupname, RPCHookPtr rpc_hook, std::shared_ptr<DefaultMQPushConsumerConfigImpl> config) : DefaultMQPushConsumerConfigProxy(*config), MQClientConfigProxy(config), push_consumer_config_impl_(config) { // set default group name if (groupname.empty()) { set_group_name(DEFAULT_CONSUMER_GROUP); } else { set_group_name(groupname); } // create DefaultMQPushConsumerImpl push_consumer_impl_ = DefaultMQPushConsumerImpl::Create(push_consumer_config_impl_, rpc_hook); } void DefaultMQPushConsumer::start() { push_consumer_impl_->start(); } void DefaultMQPushConsumer::shutdown() { push_consumer_impl_->shutdown(); } void DefaultMQPushConsumer::suspend() { push_consumer_impl_->Suspend(); } void DefaultMQPushConsumer::resume() { push_consumer_impl_->Resume(); } MQMessageListener* DefaultMQPushConsumer::getMessageListener() const { return message_listener_; } void DefaultMQPushConsumer::registerMessageListener(MessageListenerConcurrently* message_listener) { message_listener_ = message_listener; push_consumer_impl_->RegisterMessageListener(MessageListenerImpl{message_listener}, DefaultMQPushConsumerImpl::MessageListenerType::kConcurrently); } void DefaultMQPushConsumer::registerMessageListener(MessageListenerOrderly* message_listener) { message_listener_ = message_listener; push_consumer_impl_->RegisterMessageListener(MessageListenerImpl{message_listener}, DefaultMQPushConsumerImpl::MessageListenerType::kOrderly); } void DefaultMQPushConsumer::subscribe(const std::string& topic, const std::string& expression) { push_consumer_impl_->Subscribe(topic, expression); } void DefaultMQPushConsumer::setRPCHook(RPCHookPtr rpc_hook) { push_consumer_impl_->setRPCHook(rpc_hook); } } // namespace rocketmq
34.813084
114
0.754362
[ "vector" ]
6d3d081ca4a8fb2dde857ffe53cb29302473330e
13,126
cpp
C++
src/syntax.cpp
gitter-badger/zep
f56837c09529b9a02dfb4fc64f854ca0521092c3
[ "MIT" ]
null
null
null
src/syntax.cpp
gitter-badger/zep
f56837c09529b9a02dfb4fc64f854ca0521092c3
[ "MIT" ]
null
null
null
src/syntax.cpp
gitter-badger/zep
f56837c09529b9a02dfb4fc64f854ca0521092c3
[ "MIT" ]
null
null
null
#include "zep/syntax.h" #include "zep/editor.h" #include "zep/syntax_rainbow_brackets.h" #include "zep/theme.h" #include "zep/mcommon/logger.h" #include "zep/mcommon/string/stringutils.h" #include <string> #include <vector> namespace Zep { ZepSyntax::ZepSyntax( ZepBuffer& buffer, const std::unordered_set<std::string>& keywords, const std::unordered_set<std::string>& identifiers, uint32_t flags) : ZepComponent(buffer.GetEditor()) , m_buffer(buffer) , m_keywords(keywords) , m_identifiers(identifiers) , m_stop(false) , m_flags(flags) { m_syntax.resize(m_buffer.GetText().size()); m_adornments.push_back(std::make_shared<ZepSyntaxAdorn_RainbowBrackets>(*this, m_buffer)); } ZepSyntax::~ZepSyntax() { Interrupt(); } SyntaxResult ZepSyntax::GetSyntaxAt(long offset) const { Zep::SyntaxResult result; Wait(); if (m_processedChar < offset || (long)m_syntax.size() <= offset) { return result; } result.background = m_syntax[offset].background; result.foreground = m_syntax[offset].foreground; result.underline = m_syntax[offset].underline; bool found = false; for (auto& adorn : m_adornments) { auto adornResult = adorn->GetSyntaxAt(offset, found); if (found) { result = adornResult; break; } } if (m_flashRange.x != m_flashRange.y && m_flashRange.x <= offset && m_flashRange.y >= offset) { auto elapsed = timer_get_elapsed_seconds(m_flashTimer); if (elapsed < m_flashDuration) { // first get the preferred back color NVec4f backColor; if (result.background != ThemeColor::None) { backColor = GetEditor().GetTheme().GetColor(result.background); } else { backColor = GetEditor().GetTheme().GetColor(ThemeColor::Background); } // Swap it out for our custom flash color float time = float(elapsed) / m_flashDuration; result.background = ThemeColor::Custom; result.customBackgroundColor = NVec4f(GetEditor().GetTheme().GetColor(ThemeColor::FlashColor)); if (m_flashType == SyntaxFlashType::Flash) { result.customBackgroundColor = Mix(backColor, result.customBackgroundColor, sin(time * ZPI)); } else { float t = std::abs(sin(time * ZPI * .5f)) * 2.0f + .5f; if (t > 1.0f) { t = 1.0f - (t - 1.0f); } // https://codegolf.stackexchange.com/a/22629 // Light up the characters with a bright spot in the center, and a // ten character fall off; walk through the text and return auto bellCurve = [](float x) { float b = 0.0f; float c = 6.0f; return std::exp((-((x - b) * (x - b)) / 2) * (c * c)); }; auto range = m_flashRange.y - m_flashRange.x; auto center = range * t; // Sample a bell curve about the current point, but don't draw the head auto distance = bellCurve(((offset - center) / range)); distance = std::min(1.0f, distance); distance = std::max(0.0f, distance); result.customBackgroundColor = Mix(backColor, result.customBackgroundColor, float(distance)); } } else { EndFlash(); } } return result; } void ZepSyntax::Wait() const { if (m_syntaxResult.valid()) { m_syntaxResult.wait(); } } void ZepSyntax::Interrupt() { // Stop the thread, wait for it m_stop = true; if (m_syntaxResult.valid()) { m_syntaxResult.get(); } m_stop = false; } void ZepSyntax::QueueUpdateSyntax(ByteIndex startLocation, ByteIndex endLocation) { assert(startLocation >= 0); assert(endLocation >= startLocation); // Record the max location the syntax is valid up to. This will // ensure that multiple calls to restart the thread keep track of where to start // This means a small edit at the end of a big file, followed by a small edit at the top // is the worst case scenario, because m_processedChar = std::min(startLocation, long(m_processedChar)); m_targetChar = std::max(endLocation, long(m_targetChar)); // Make sure the syntax buffer is big enough - adding normal syntax to the end // This may also 'chop' m_syntax.resize(m_buffer.GetText().size(), SyntaxData{}); m_processedChar = std::min(long(m_processedChar), long(m_buffer.GetText().size() - 1)); m_targetChar = std::min(long(m_targetChar), long(m_buffer.GetText().size() - 1)); // Have the thread update the syntax in the new region // If the pool has no threads, this will end up serial m_syntaxResult = GetEditor().GetThreadPool().enqueue([=]() { UpdateSyntax(); }); } void ZepSyntax::Notify(std::shared_ptr<ZepMessage> spMsg) { // Handle any interesting buffer messages if (spMsg->messageId == Msg::Buffer) { auto spBufferMsg = std::static_pointer_cast<BufferMessage>(spMsg); if (spBufferMsg->pBuffer != &m_buffer) { return; } if (spBufferMsg->type == BufferMessageType::PreBufferChange) { Interrupt(); } else if (spBufferMsg->type == BufferMessageType::TextDeleted) { Interrupt(); m_syntax.erase(m_syntax.begin() + spBufferMsg->startLocation, m_syntax.begin() + spBufferMsg->endLocation); QueueUpdateSyntax(spBufferMsg->startLocation, spBufferMsg->endLocation); } else if (spBufferMsg->type == BufferMessageType::TextAdded || spBufferMsg->type == BufferMessageType::Loaded) { Interrupt(); m_syntax.insert(m_syntax.begin() + spBufferMsg->startLocation, spBufferMsg->endLocation - spBufferMsg->startLocation, SyntaxData{}); QueueUpdateSyntax(spBufferMsg->startLocation, spBufferMsg->endLocation); } else if (spBufferMsg->type == BufferMessageType::TextChanged) { Interrupt(); QueueUpdateSyntax(spBufferMsg->startLocation, spBufferMsg->endLocation); } } } // TODO: Multiline comments void ZepSyntax::UpdateSyntax() { auto& buffer = m_buffer.GetText(); auto itrCurrent = buffer.begin() + m_processedChar; auto itrEnd = buffer.begin() + m_targetChar; assert(std::distance(itrCurrent, itrEnd) < int(m_syntax.size())); assert(m_syntax.size() == buffer.size()); std::string delim(" \t.\n;(){}=:"); std::string lineEnd("\n"); // Walk backwards to previous delimiter while (itrCurrent > buffer.begin()) { if (std::find(delim.begin(), delim.end(), *itrCurrent) == delim.end()) { itrCurrent--; } else { break; } } // Back to the previous line while (itrCurrent > buffer.begin() && *itrCurrent != '\n') { itrCurrent--; } itrEnd = buffer.find_first_of(itrEnd, buffer.end(), lineEnd.begin(), lineEnd.end()); // Mark a region of the syntax buffer with the correct marker auto mark = [&](GapBuffer<uint8_t>::const_iterator itrA, GapBuffer<uint8_t>::const_iterator itrB, ThemeColor type, ThemeColor background) { std::fill(m_syntax.begin() + (itrA - buffer.begin()), m_syntax.begin() + (itrB - buffer.begin()), SyntaxData{ type, background }); }; auto markSingle = [&](GapBuffer<uint8_t>::const_iterator itrA, ThemeColor type, ThemeColor background) { (m_syntax.begin() + (itrA - buffer.begin()))->foreground = type; (m_syntax.begin() + (itrA - buffer.begin()))->background = background; }; // Update start location m_processedChar = long(itrCurrent - buffer.begin()); //LOG(DEBUG) << "Updating Syntax: Start=" << m_processedChar << ", End=" << std::distance(buffer.begin(), itrEnd); // Walk the buffer updating information about syntax coloring while (itrCurrent != itrEnd) { if (m_stop == true) { return; } // Find a token, skipping delim <itrFirst, itrLast> auto itrFirst = buffer.find_first_not_of(itrCurrent, buffer.end(), delim.begin(), delim.end()); if (itrFirst == buffer.end()) break; auto itrLast = buffer.find_first_of(itrFirst, buffer.end(), delim.begin(), delim.end()); // Ensure we found a token assert(itrLast >= itrFirst); // Mark whitespace for (auto& itr = itrCurrent; itr < itrFirst; itr++) { if (*itr == ' ') { mark(itr, itr + 1, ThemeColor::Whitespace, ThemeColor::None); } else if (*itr == '\t') { mark(itr, itr + 1, ThemeColor::Whitespace, ThemeColor::None); } } // Do I need to make a string here? auto token = std::string(itrFirst, itrLast); if (m_flags & ZepSyntaxFlags::CaseInsensitive) { token = string_tolower(token); } if (m_keywords.find(token) != m_keywords.end()) { mark(itrFirst, itrLast, ThemeColor::Keyword, ThemeColor::None); } else if (m_identifiers.find(token) != m_identifiers.end()) { mark(itrFirst, itrLast, ThemeColor::Identifier, ThemeColor::None); } else if (token.find_first_not_of("0123456789") == std::string::npos) { mark(itrFirst, itrLast, ThemeColor::Number, ThemeColor::None); } else if (token.find_first_not_of("{}()[]") == std::string::npos) { mark(itrFirst, itrLast, ThemeColor::Parenthesis, ThemeColor::None); } else { mark(itrFirst, itrLast, ThemeColor::Normal, ThemeColor::None); } // Find String auto findString = [&](uint8_t ch) { auto itrString = itrFirst; if (*itrString == ch) { itrString++; while (itrString < buffer.end()) { // handle end of string if (*itrString == ch) { itrString++; mark(itrFirst, itrString, ThemeColor::String, ThemeColor::None); itrLast = itrString + 1; break; } if (itrString < (buffer.end() - 1)) { auto itrNext = itrString + 1; // Ignore quoted if (*itrString == '\\' && *itrNext == ch) { itrString++; } } itrString++; } } }; findString('\"'); findString('\''); std::string commentStr = "/"; auto itrComment = buffer.find_first_of(itrFirst, itrLast, commentStr.begin(), commentStr.end()); if (itrComment != buffer.end()) { auto itrCommentStart = itrComment++; if (itrComment < buffer.end()) { if (*itrComment == '/') { itrLast = buffer.find_first_of(itrCommentStart, buffer.end(), lineEnd.begin(), lineEnd.end()); mark(itrCommentStart, itrLast, ThemeColor::Comment, ThemeColor::None); } } } itrCurrent = itrLast; } // If we got here, we sucessfully completed // Reset the target to the beginning m_targetChar = long(0); m_processedChar = long(buffer.size() - 1); } void ZepSyntax::EndFlash() const { m_flashRange = NVec2<ByteIndex>(0, 0); GetEditor().SetFlags(ZClearFlags(GetEditor().GetFlags(), ZepEditorFlags::FastUpdate)); } void ZepSyntax::BeginFlash(float seconds, SyntaxFlashType flashType, const NVec2i& range) { m_flashRange = range; m_flashDuration = seconds; m_flashType = flashType; timer_restart(m_flashTimer); if (range == NVec2i(0)) { m_flashRange = NVec2i(long(0), long(m_syntax.size() - 1)); } GetEditor().SetFlags(ZSetFlags(GetEditor().GetFlags(), ZepEditorFlags::FastUpdate)); } const NVec4f& ZepSyntax::ToBackgroundColor(const SyntaxResult& res) const { if (res.background == ThemeColor::Custom) { return res.customBackgroundColor; } else { return m_buffer.GetTheme().GetColor(res.background); } } const NVec4f& ZepSyntax::ToForegroundColor(const SyntaxResult& res) const { if (res.foreground == ThemeColor::Custom) { return res.customForegroundColor; } else { return m_buffer.GetTheme().GetColor(res.foreground); } } } // namespace Zep
31.705314
144
0.567423
[ "vector" ]
6d401d0a11c827e06b28072aca2ae185208a4996
1,844
cpp
C++
tests/test_vector_optional_argument.cpp
sandman42292/structopt
a9f30992980bb0d36da69398b25b51f9898868bb
[ "BSL-1.0", "MIT" ]
389
2020-08-16T22:27:04.000Z
2022-03-28T12:48:55.000Z
tests/test_vector_optional_argument.cpp
sandman42292/structopt
a9f30992980bb0d36da69398b25b51f9898868bb
[ "BSL-1.0", "MIT" ]
10
2020-08-17T12:28:27.000Z
2021-06-17T03:00:40.000Z
tests/test_vector_optional_argument.cpp
sandman42292/structopt
a9f30992980bb0d36da69398b25b51f9898868bb
[ "BSL-1.0", "MIT" ]
20
2020-08-17T01:38:10.000Z
2021-11-23T01:52:37.000Z
#include <doctest.hpp> #include <structopt/app.hpp> using doctest::test_suite; struct OptionalVectorIntArgument { std::optional<std::vector<int>> value = {}; }; STRUCTOPT(OptionalVectorIntArgument, value); TEST_CASE("structopt can parse vector optional argument" * test_suite("vector_optional")) { // Vector of ints { auto arguments = structopt::app("test").parse<OptionalVectorIntArgument>(std::vector<std::string>{"./main", "--value", "1", "2", "3"}); REQUIRE(arguments.value.has_value() == true); REQUIRE(arguments.value.value() == std::vector<int>{1, 2, 3}); } } struct OptionalVectorIntArgumentWithOtherFlags { std::optional<std::vector<int>> value = {}; std::optional<bool> foo = false; }; STRUCTOPT(OptionalVectorIntArgumentWithOtherFlags, value, foo); TEST_CASE("structopt can parse vector optional argument" * test_suite("vector_optional")) { { auto arguments = structopt::app("test").parse<OptionalVectorIntArgumentWithOtherFlags>(std::vector<std::string>{"./main", "--value", "1", "2", "3", "--foo"}); REQUIRE(arguments.value == std::vector<int>{1, 2, 3}); REQUIRE(arguments.foo == true); } { auto arguments = structopt::app("test").parse<OptionalVectorIntArgumentWithOtherFlags>(std::vector<std::string>{"./main", "--foo", "--value", "1", "2", "3"}); REQUIRE(arguments.value == std::vector<int>{1, 2, 3}); REQUIRE(arguments.foo == true); } { bool exception_thrown{false}; try { auto arguments = structopt::app("test").parse<OptionalVectorIntArgumentWithOtherFlags>(std::vector<std::string>{"./main", "--value", "1", "2", "--foo", "3"}); REQUIRE(arguments.value == std::vector<int>{1, 2}); REQUIRE(arguments.foo == true); } catch(structopt::exception& e) { exception_thrown = true; } REQUIRE(exception_thrown == true); } }
36.88
164
0.664859
[ "vector" ]
6d40ecbc23449c7a4a8165f973d2f9a45fbc4a04
14,127
cpp
C++
tests/Aql/InputRangeTest.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
tests/Aql/InputRangeTest.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
tests/Aql/InputRangeTest.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" #include "AqlExecutorTestCase.h" #include "Aql/AqlItemBlockInputMatrix.h" #include "Aql/AqlItemBlockInputRange.h" #include "Aql/ExecutionState.h" #include "Aql/MultiAqlItemBlockInputRange.h" #if GTEST_HAS_TYPED_TEST_P using namespace arangodb; using namespace arangodb::aql; namespace arangodb::tests::aql { namespace { std::string const stateToString(ExecutorState state) { switch (state) { case ExecutorState::DONE: return "DONE"; case ExecutorState::HASMORE: return "HASMORE"; default: // just to suppress a warning .. return "UNKNOWN"; } } } // namespace template<typename Range> class InputRangeTest : public AqlExecutorTestCase<> { protected: // Used to holdData for InputMatrixTests AqlItemMatrix _matrix{1}; // Picked a random number of dependencies for MultiInputRanges size_t _numberDependencies{3}; auto buildRange(ExecutorState state, SharedAqlItemBlockPtr block) -> Range { if constexpr (std::is_same_v<Range, AqlItemBlockInputRange>) { return AqlItemBlockInputRange{state, 0, block, 0}; } if constexpr (std::is_same_v<Range, AqlItemBlockInputMatrix>) { _matrix.clear(); _matrix.addBlock(block); return AqlItemBlockInputMatrix(state, &_matrix); } if constexpr (std::is_same_v<Range, MultiAqlItemBlockInputRange>) { MultiAqlItemBlockInputRange res{state}; res.resizeOnce(state, 0, _numberDependencies); size_t depNr = 0; std::unordered_map<size_t, std::vector<size_t>> chosenRows; chosenRows.reserve(_numberDependencies); for (size_t i = 0; i < _numberDependencies; ++i) { chosenRows.emplace(i, std::vector<size_t>{}); } for (size_t i = 0; i < block->numRows(); ++i) { if (block->isShadowRow(i)) { // ShadowRows need to be added to all Clients for (auto& [key, value] : chosenRows) { value.emplace_back(i); } } else { // We alternate between dependendies to emplace rows chosenRows[depNr % _numberDependencies].emplace_back(i); ++depNr; } } for (auto const& [index, chosen] : chosenRows) { if (chosen.empty()) { res.setDependency(index, AqlItemBlockInputRange{state}); } else { auto copiedBlock = block->slice(chosen, 0, chosen.size()); if (index != 0) { // Simulate that shadowRows have been "moved" by clearing their // dataRegisters for (size_t i = 0; i < copiedBlock->numRows(); ++i) { if (copiedBlock->isShadowRow(i)) { for (RegisterId::value_t r = 0; r < copiedBlock->numRegisters(); ++r) { copiedBlock->destroyValue(i, r); } } } } AqlItemBlockInputRange splitRange{state, 0, copiedBlock, 0}; res.setDependency(index, splitRange); } } return res; } THROW_ARANGO_EXCEPTION(TRI_ERROR_NOT_IMPLEMENTED); } auto consumeData(Range& range) -> void { if constexpr (std::is_same_v<Range, AqlItemBlockInputRange>) { while (range.hasDataRow()) { std::ignore = range.nextDataRow(); } } else if constexpr (std::is_same_v<Range, AqlItemBlockInputMatrix> || std::is_same_v<Range, MultiAqlItemBlockInputRange>) { std::ignore = range.skipAllRemainingDataRows(); } else { THROW_ARANGO_EXCEPTION(TRI_ERROR_NOT_IMPLEMENTED); } } }; TYPED_TEST_CASE_P(InputRangeTest); TYPED_TEST_P(InputRangeTest, test_default_initializer) { std::vector<ExecutorState> states{ExecutorState::DONE, ExecutorState::HASMORE}; for (auto const& finalState : states) { if (std::is_same_v<AqlItemBlockInputMatrix, TypeParam> && finalState == ExecutorState::DONE) { // The AqlItemBlockInputMatrix may not be instantiated with DONE continue; } SCOPED_TRACE("Testing state: " + stateToString(finalState)); auto testee = std::invoke([&]() { if constexpr (std::is_same_v<TypeParam, AqlItemBlockInputMatrix>) { if (finalState == ExecutorState::HASMORE) { return TypeParam{finalState}; } else { TRI_ASSERT(finalState == ExecutorState::DONE); // AqlItemBlockInputMatrix may not be instantiated with DONE and // without a matrix, thus this conditionals. return TypeParam{finalState, &this->_matrix}; } } else { return TypeParam{finalState}; } }); // assert is just for documentation static_assert(std::is_same_v<decltype(testee), TypeParam>); if constexpr (std::is_same_v<decltype(testee), MultiAqlItemBlockInputRange>) { // Default has only 1 dependency EXPECT_EQ(testee.upstreamState(0), finalState); } else { EXPECT_EQ(testee.upstreamState(), finalState); } EXPECT_FALSE(testee.hasDataRow()); EXPECT_FALSE(testee.hasShadowRow()); // Required for expected Number Of Rows EXPECT_EQ(testee.finalState(), finalState); EXPECT_EQ(testee.countDataRows(), 0); EXPECT_EQ(testee.countShadowRows(), 0); { auto shadow = testee.peekShadowRow(); EXPECT_FALSE(shadow.isInitialized()); } } } // namespace arangodb::tests::aql TYPED_TEST_P(InputRangeTest, test_block_only_datarows) { std::vector<ExecutorState> states{ExecutorState::DONE, ExecutorState::HASMORE}; for (auto const& finalState : states) { SCOPED_TRACE("Testing state: " + stateToString(finalState)); auto block = buildBlock<1>(this->manager(), {{1}, {2}, {3}}); auto testee = this->buildRange(finalState, block); if constexpr (std::is_same_v<decltype(testee), AqlItemBlockInputMatrix>) { // Matrix is only done, if it has reached a shadowRow, or the end EXPECT_EQ(testee.upstreamState(), finalState); } else if constexpr (std::is_same_v<decltype(testee), MultiAqlItemBlockInputRange>) { EXPECT_GT(testee.numberDependencies(), 0); for (size_t i = 0; i < testee.numberDependencies(); ++i) { // We have enough rows for every depenendy to contain something EXPECT_EQ(testee.upstreamState(i), ExecutorState::HASMORE); } } else { EXPECT_EQ(testee.upstreamState(), ExecutorState::HASMORE); } if constexpr (std::is_same_v<decltype(testee), AqlItemBlockInputMatrix>) { // The AqlItemBlockInputMatrix may only report it has a data row when it // knows it has consumed all input (of the current subquery iteration, if // applicable). EXPECT_EQ(testee.hasDataRow(), finalState == ExecutorState::DONE); } else { EXPECT_TRUE(testee.hasDataRow()); } EXPECT_FALSE(testee.hasShadowRow()); // Required for expected Number Of Rows EXPECT_EQ(testee.finalState(), finalState); EXPECT_EQ(testee.countDataRows(), 3); EXPECT_EQ(testee.countShadowRows(), 0); { auto shadow = testee.peekShadowRow(); EXPECT_FALSE(shadow.isInitialized()); } } } TYPED_TEST_P(InputRangeTest, test_block_only_shadowrows) { std::vector<ExecutorState> states{ExecutorState::DONE, ExecutorState::HASMORE}; for (auto const& finalState : states) { SCOPED_TRACE("Testing state: " + stateToString(finalState)); auto block = buildBlock<1>(this->manager(), {{1}, {2}, {3}}, {{0, 0}, {1, 1}, {2, 0}}); auto testee = this->buildRange(finalState, block); if constexpr (std::is_same_v<decltype(testee), MultiAqlItemBlockInputRange>) { EXPECT_GT(testee.numberDependencies(), 0); for (size_t i = 0; i < testee.numberDependencies(); ++i) { // We have enough rows for every depenendy to contain something EXPECT_EQ(testee.upstreamState(i), ExecutorState::DONE); } } else { EXPECT_EQ(testee.upstreamState(), ExecutorState::DONE); } EXPECT_FALSE(testee.hasDataRow()); EXPECT_TRUE(testee.hasShadowRow()); // Required for expected Number Of Rows EXPECT_EQ(testee.finalState(), finalState); EXPECT_EQ(testee.countDataRows(), 0); EXPECT_EQ(testee.countShadowRows(), 3); { auto shadow = testee.peekShadowRow(); EXPECT_TRUE(shadow.isInitialized()); } } } TYPED_TEST_P(InputRangeTest, test_block_mixed_rows) { std::vector<ExecutorState> states{ExecutorState::DONE, ExecutorState::HASMORE}; for (auto const& finalState : states) { SCOPED_TRACE("Testing state: " + stateToString(finalState)); auto block = buildBlock<1>(this->manager(), {{1}, {2}, {3}, {4}}, {{1, 0}, {3, 0}}); auto testee = this->buildRange(finalState, block); if constexpr (std::is_same_v<decltype(testee), AqlItemBlockInputMatrix>) { // Matrix is only done, if it has reached a shadowRow, or the end EXPECT_EQ(testee.upstreamState(), ExecutorState::DONE); } else if constexpr (std::is_same_v<decltype(testee), MultiAqlItemBlockInputRange>) { EXPECT_GT(testee.numberDependencies(), 0); // We only have one Data Row. This is assigned to dependency 0 EXPECT_EQ(testee.upstreamState(0), ExecutorState::HASMORE); for (size_t i = 1; i < testee.numberDependencies(); ++i) { // All others do not have data rows, and need to be done EXPECT_EQ(testee.upstreamState(i), ExecutorState::DONE); } } else { EXPECT_EQ(testee.upstreamState(), ExecutorState::HASMORE); } EXPECT_TRUE(testee.hasDataRow()); EXPECT_FALSE(testee.hasShadowRow()); // Required for expected Number Of Rows EXPECT_EQ(testee.finalState(), finalState); EXPECT_EQ(testee.countDataRows(), 2); EXPECT_EQ(testee.countShadowRows(), 2); { auto shadow = testee.peekShadowRow(); EXPECT_FALSE(shadow.isInitialized()); } } } TYPED_TEST_P(InputRangeTest, test_block_continuous_walk_only_relevant_rows) { std::vector<ExecutorState> states{ExecutorState::DONE, ExecutorState::HASMORE}; for (auto const& finalState : states) { SCOPED_TRACE("Testing state: " + stateToString(finalState)); auto block = buildBlock<1>( this->manager(), {{1}, {2}, {3}, {4}, {1}, {2}, {3}, {4}, {1}, {2}, {3}, {4}}, {{3, 0}, {6, 0}, {11, 0}}); auto testee = this->buildRange(finalState, block); { // First subquery // Required for expected Number Of Rows EXPECT_EQ(testee.finalState(), finalState); EXPECT_EQ(testee.countDataRows(), 9); EXPECT_EQ(testee.countShadowRows(), 3); EXPECT_TRUE(testee.hasDataRow()); EXPECT_FALSE(testee.hasShadowRow()); // Consume all DataRows. this->consumeData(testee); EXPECT_FALSE(testee.hasDataRow()); EXPECT_TRUE(testee.hasShadowRow()); EXPECT_EQ(testee.countDataRows(), 6); EXPECT_EQ(testee.countShadowRows(), 3); auto [state, shadow] = testee.nextShadowRow(); EXPECT_EQ(state, ExecutorState::HASMORE); EXPECT_TRUE(shadow.isInitialized()); EXPECT_EQ(testee.countDataRows(), 6); EXPECT_EQ(testee.countShadowRows(), 2); } { // Second subquery EXPECT_TRUE(testee.hasDataRow()); EXPECT_FALSE(testee.hasShadowRow()); // Consume all DataRows. this->consumeData(testee); EXPECT_FALSE(testee.hasDataRow()); EXPECT_TRUE(testee.hasShadowRow()); EXPECT_EQ(testee.countDataRows(), 4); EXPECT_EQ(testee.countShadowRows(), 2); auto [state, shadow] = testee.nextShadowRow(); EXPECT_EQ(state, ExecutorState::HASMORE); EXPECT_TRUE(shadow.isInitialized()); EXPECT_EQ(testee.countDataRows(), 4); EXPECT_EQ(testee.countShadowRows(), 1); } { // Third subquery EXPECT_TRUE(testee.hasDataRow()); EXPECT_FALSE(testee.hasShadowRow()); // Consume all DataRows. this->consumeData(testee); EXPECT_FALSE(testee.hasDataRow()); EXPECT_TRUE(testee.hasShadowRow()); EXPECT_EQ(testee.countDataRows(), 0); EXPECT_EQ(testee.countShadowRows(), 1); auto [state, shadow] = testee.nextShadowRow(); EXPECT_EQ(state, finalState); EXPECT_TRUE(shadow.isInitialized()); EXPECT_EQ(testee.countDataRows(), 0); EXPECT_EQ(testee.countShadowRows(), 0); } } } REGISTER_TYPED_TEST_CASE_P(InputRangeTest, test_default_initializer, test_block_only_datarows, test_block_only_shadowrows, test_block_mixed_rows, test_block_continuous_walk_only_relevant_rows); using RangeTypes = ::testing::Types<AqlItemBlockInputRange, AqlItemBlockInputMatrix, MultiAqlItemBlockInputRange>; INSTANTIATE_TYPED_TEST_CASE_P(InputRangeTestInstance, InputRangeTest, RangeTypes); } // namespace arangodb::tests::aql #endif
35.85533
80
0.635237
[ "vector" ]
6d41f43a5b618767645438aaf9f3964a9f95ae56
2,069
cpp
C++
src/Sowl/Windows/WindowClassBuilder.cpp
opflucker/Sowl
78bba310b83cee6ec597ad125b4c4e038324c158
[ "MIT" ]
1
2020-07-26T18:07:46.000Z
2020-07-26T18:07:46.000Z
src/Sowl/Windows/WindowClassBuilder.cpp
opflucker/Sowl
78bba310b83cee6ec597ad125b4c4e038324c158
[ "MIT" ]
null
null
null
src/Sowl/Windows/WindowClassBuilder.cpp
opflucker/Sowl
78bba310b83cee6ec597ad125b4c4e038324c158
[ "MIT" ]
1
2021-03-09T20:46:01.000Z
2021-03-09T20:46:01.000Z
#include "WindowClassBuilder.h" using namespace sowl; /// @brief Initialize the builder with given parameters and defaults. /// @param processHandle Handle of the process where the window class to be registered must belongs to. /// @param className A valid window class name. /// @param wndProc A pointer to the window procedure. /// @return A builder. If parameters are valid, a call to Register() must return a valid registered window class. WindowClassBuilder::WindowClassBuilder(HINSTANCE processHandle, LPCWSTR className, WNDPROC wndProc) { wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = NULL; wc.hCursor = NULL; wc.hIcon = NULL; wc.lpszClassName = className; wc.lpszMenuName = NULL; wc.style = 0; wc.hInstance = processHandle; wc.lpfnWndProc = wndProc; } WindowClassBuilder& WindowClassBuilder::WithBackgroundBrush(HBRUSH handle) { wc.hbrBackground = handle; return *this; } WindowClassBuilder& WindowClassBuilder::WithCursor(HCURSOR handle) { wc.hCursor = handle; return *this; } WindowClassBuilder& WindowClassBuilder::WithIcon(HICON handle) { wc.hCursor = handle; return *this; } WindowClassBuilder& WindowClassBuilder::WithMenu(LPCWSTR name) { wc.lpszMenuName = name; return *this; } WindowClassBuilder& WindowClassBuilder::WithStyle(UINT style) { wc.style = style; return *this; } /// @brief If the class was not registered, register it. Otherwise, retrieve the registered class information. /// @return Structure with information about the registered class. WNDCLASS WindowClassBuilder::Register() const { WNDCLASS wcFound; if (GetClassInfo(wc.hInstance, wc.lpszClassName, &wcFound) == FALSE) RegisterClass(&wc); return wc; } /// @brief Calls to Register(), creates a WindowHandleBuilder using the registered class and returns it. /// @return A WindowHandleBuilder object. WindowHandleBuilder WindowClassBuilder::RegisterAndCreateHandleBuilder() const { Register(); return WindowHandleBuilder(wc.hInstance, wc.lpszClassName); }
28.736111
113
0.738521
[ "object" ]
6d45811d71a9c0b22491bf8c299a6a4e557d89c8
944
cpp
C++
SPOJ/Random/SAMER08G/sam.cpp
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
SPOJ/Random/SAMER08G/sam.cpp
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
SPOJ/Random/SAMER08G/sam.cpp
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<stdio.h> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<math.h> #define sd(x) scanf("%d",&x); #define sd2(x,y) scanf("%d %d",&x,&y); #define sd3(x,y,z) scanf("%d %d %d",&x,&y,&z); #define sull(x) scanf("%ull",&x); #define print(x) printf("%d\n",x); #define print2(x,y) printf("%d %d\n",x,y); #define print3(x,y,z) printf("%d %d %d\n",x,y,z); #define printull(x) printf("%ull\n",x); using namespace std; int main(){ int n, pos[1000], c, p, flag; sd(n); while(n){ for(int i = 0; i < n; i++) pos[i] = 0; flag = 0; for(int i = 0; i < n; i++){ sd2(c,p); if(i+ p < n and i + p >=0){ if(pos[i+p] == 0) pos[i+p] = c; else flag = 1; } else flag = 1; } if(flag) printf("-1\n"); else{ for(int i = 0; i < n; i++) printf("%d ", pos[i]); printf("\n"); } sd(n); } return 0; }
18.153846
49
0.524364
[ "vector" ]
6d4f33c3aa6e86a44c1d7515c6345ec5dc3ca8d9
3,715
hpp
C++
core/src/Boundings/SphereBoundingVolume.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
core/src/Boundings/SphereBoundingVolume.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
core/src/Boundings/SphereBoundingVolume.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_CORE_BOUNDINGS_BOUNDING_VOLUME_SPHERE_ #define CRIMILD_CORE_BOUNDINGS_BOUNDING_VOLUME_SPHERE_ #include "BoundingVolume.hpp" namespace crimild { class SphereBoundingVolume : public BoundingVolume { public: SphereBoundingVolume( void ); SphereBoundingVolume( const Vector3f &center, float radius ); explicit SphereBoundingVolume( const Sphere3f &sphere ); virtual ~SphereBoundingVolume( void ); virtual const Vector3f &getCenter( void ) const override { return _sphere.getCenter(); } virtual float getRadius( void ) const override { return _sphere.getRadius(); } private: Sphere3f _sphere; public: virtual void computeFrom( const BoundingVolume *volume ) override; virtual void computeFrom( const BoundingVolume *volume, const Transformation &transform ) override; virtual void computeFrom( const Vector3f *positions, unsigned int positionCount ) override; virtual void computeFrom( const VertexBufferObject *vbo ) override; virtual void computeFrom( const Vector3f &min, const Vector3f &max ) override; public: virtual void expandToContain( const Vector3f &point ) override; virtual void expandToContain( const Vector3f *positions, unsigned int positionCount ) override; virtual void expandToContain( const VertexBufferObject *vbo ) override; virtual void expandToContain( const BoundingVolume *input ) override; public: virtual int whichSide( const Plane3f &plane ) const override; virtual bool contains( const Vector3f &point ) const override; public: virtual bool testIntersection( const Ray3f &ray ) const override; virtual bool testIntersection( const BoundingVolume *input ) const override; virtual bool testIntersection( const Sphere3f &sphere ) const override; virtual bool testIntersection( const Plane3f &plane ) const override; virtual void resolveIntersection( const BoundingVolume *other, Transformation &result ) const override; virtual void resolveIntersection( const Sphere3f &sphere, Transformation &result ) const override; virtual void resolveIntersection( const Plane3f &plane, Transformation &result ) const override; }; } #endif
46.4375
105
0.774428
[ "transform" ]
6d51a9e0a8e67076583f3a46947ad101c675f399
4,281
hh
C++
gazebo/gui/building/BuildingMakerPrivate.hh
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
gazebo/gui/building/BuildingMakerPrivate.hh
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
gazebo/gui/building/BuildingMakerPrivate.hh
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _GAZEBO_GUI_BUILDING_BUILDINGMAKERPRIVATE_HH_ #define _GAZEBO_GUI_BUILDING_BUILDINGMAKERPRIVATE_HH_ #include <map> #include <memory> #include <string> #include <vector> #include <sdf/sdf.hh> #include "gazebo/common/CommonTypes.hh" #include "gazebo/gui/qt.h" #include "gazebo/gui/building/BuildingMaker.hh" #include "gazebo/rendering/RenderTypes.hh" #include "gazebo/transport/TransportTypes.hh" namespace gazebo { namespace gui { class BuildingModelManip; class SaveDialog; /// \internal /// \brief Private data for BuildingMaker class BuildingMakerPrivate { /// \enum SaveState /// \brief Save states for the building editor. public: enum SaveState { // NEVER_SAVED: The building has never been saved. NEVER_SAVED, // ALL_SAVED: All changes have been saved. ALL_SAVED, // UNSAVED_CHANGES: Has been saved before, but has unsaved changes. UNSAVED_CHANGES }; /// \brief A map of building part names to model manip objects which /// manage the visuals representing the building part. public: std::map<std::string, BuildingModelManip *> allItems; /// \brief A map of building part names to model manip objects which /// manage the visuals representing the building part. public: std::map<std::string, std::vector<std::string>> attachmentMap; /// \brief The building model in SDF format. public: sdf::SDFPtr modelSDF; /// \brief A template SDF of a simple box model. public: sdf::SDFPtr modelTemplateSDF; /// \brief Name of the building model. public: std::string modelName; /// \brief Folder name, which is the model name without spaces. public: std::string folderName; /// \brief Default name of building model public: std::string buildingDefaultName; /// \brief Name of the building model preview. public: std::string previewName; /// \brief The root visual of the building model preview. public: rendering::VisualPtr previewVisual; /// \brief Counter for the number of walls in the model. public: int wallCounter; /// \brief Counter for the number of windows in the model. public: int windowCounter; /// \brief Counter for the number of doors in the model. public: int doorCounter; /// \brief Counter for the number of staircases in the model. public: int stairsCounter; /// \brief Counter for the number of floors in the model. public: int floorCounter; /// \brief Store the current save state of the model. public: enum SaveState currentSaveState; /// \brief A list of gui editor events connected to the building maker. public: std::vector<event::ConnectionPtr> connections; /// \brief A dialog for setting building model name and save location. public: std::unique_ptr<SaveDialog> saveDialog; /// \brief Visual that is currently hovered over by the mouse. public: rendering::VisualPtr hoverVis; /// \brief The color currently selected. If none is selected, it will be /// QColor::Invalid. public: QColor selectedColor; /// \brief The texture currently selected. If none is selected, it will be /// an empty string. public: QString selectedTexture; /// \brief The current level that is being edited. public: int currentLevel; /// \brief Node used to publish messages. public: transport::NodePtr node; /// \brief Publisher for factory messages. public: transport::PublisherPtr makerPub; }; } } #endif
31.021739
80
0.682317
[ "vector", "model" ]
6d524464d0ae748c270f7d92b9c5c78a18a2d8d2
1,423
cpp
C++
src/population.cpp
dmarcini/GA-TSP
91719435fe8f4a4b75e721060d34a2b7a5f52205
[ "MIT" ]
null
null
null
src/population.cpp
dmarcini/GA-TSP
91719435fe8f4a4b75e721060d34a2b7a5f52205
[ "MIT" ]
null
null
null
src/population.cpp
dmarcini/GA-TSP
91719435fe8f4a4b75e721060d34a2b7a5f52205
[ "MIT" ]
null
null
null
#include "population.hpp" #include <algorithm> #include <random> #include <tuple> #include "rand.hpp" #include "specimen.hpp" #include "graph.hpp" void Population::generate_specimens(int size) { for (int i {0}; i < size; ++i) { std::vector<int> chromosome; for (int j {0}; j < chromosome_size_; ++j) { chromosome.push_back(j); } std::shuffle(chromosome.begin(), chromosome.end(), std::mt19937{std::random_device{}()}); specimens_.emplace_back(chromosome); } } void Population::add_specimen(const Specimen &specimen) { specimens_.push_back(specimen); } Specimen& Population::get_specimen(int number) { return specimens_[number]; } Specimen Population::get_random_specimen() { return specimens_[utility::rand(0, specimens_.size())]; } void Population::pop_specimen() { specimens_.pop_back(); } void Population::sort(const Graph &graph) { std::vector<std::tuple<int, int>> ranking; for (size_t i {0}; i < specimens_.size(); ++i) { int path_length { graph.calculate_path_length(specimens_[i].chromosome()) }; ranking.emplace_back(i, path_length); } std::sort(ranking.begin(), ranking.end(), [](const std::tuple<int, int> &e1, const std::tuple<int, int> &e2) { return std::get<1>(e1) < std::get<1>(e2); }); }
19.763889
67
0.604357
[ "vector" ]
6d5b2dff9da482a3a8ebddf788f3e779478a687a
4,732
cxx
C++
ThirdParty/xdmf2/vtkxdmf2/libsrc/XdmfObject.cxx
OpenGeoscience/VTK
a373e975b9284a022f43a062ebf5042bb17b4e44
[ "BSD-3-Clause" ]
1
2016-09-08T14:47:11.000Z
2016-09-08T14:47:11.000Z
ThirdParty/xdmf2/vtkxdmf2/libsrc/XdmfObject.cxx
OpenGeoscience/VTK
a373e975b9284a022f43a062ebf5042bb17b4e44
[ "BSD-3-Clause" ]
null
null
null
ThirdParty/xdmf2/vtkxdmf2/libsrc/XdmfObject.cxx
OpenGeoscience/VTK
a373e975b9284a022f43a062ebf5042bb17b4e44
[ "BSD-3-Clause" ]
5
2015-10-09T04:12:29.000Z
2021-12-15T16:57:11.000Z
/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : Id */ /* Date : $Date$ */ /* Version : $Revision$ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* clarke@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice 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 "XdmfObject.h" #include <string.h> static XdmfInt32 GlobalDebugFlag = 0; static XdmfInt64 NameCntr = 0; istrstream& XDMF_READ_STREAM64(istrstream& istr, XDMF_64_INT& i) { #if defined( XDMF_HAVE_64BIT_STREAMS ) istr >>i; #else // a double here seems to not work // for hex characters so use an int. // since XDMF_HAVE_64BIT_STREAMS is unset // we don't have a long long. // double d = 0; unsigned int d = 0; istr >> d; i = (XDMF_64_INT)d; #endif return istr; } // This is a comment XdmfObject::XdmfObject() { this->Debug = 0; } XdmfObject::~XdmfObject() { } XdmfInt32 XdmfObject::GetGlobalDebug(){ return GlobalDebugFlag; } void XdmfObject::SetGlobalDebug( XdmfInt32 Value ){ GlobalDebugFlag = Value; } XdmfConstString XdmfObject::GetUniqueName(XdmfConstString NameBase){ return(GetUnique(NameBase)); } XdmfInt32 GetGlobalDebug(){ return GlobalDebugFlag; } void SetGlobalDebug( XdmfInt32 Value ){ GlobalDebugFlag = Value; } void SetGlobalDebugOn(){ GlobalDebugFlag = 1; } void SetGlobalDebugOff(){ GlobalDebugFlag = 0; } XdmfString GetUnique( XdmfConstString Pattern ) { static char ReturnName[80]; ostrstream String(ReturnName,80); if( Pattern == NULL ) Pattern = "Xdmf_"; String << Pattern << XDMF_64BIT_CAST(NameCntr++) << ends; return( ReturnName ); } XdmfString XdmfObjectToHandle( XdmfObject *Source ){ ostrstream Handle; XDMF_64_INT RealObjectPointer; XdmfObject **Rpt = &Source; RealObjectPointer = reinterpret_cast<XDMF_64_INT>(*Rpt); Handle << "_"; Handle.setf(ios::hex,ios::basefield); Handle << XDMF_64BIT_CAST(RealObjectPointer) << "_" << Source->GetClassName() << ends; // cout << "XdmfObjectToHandle : Source = " << Source << endl; // cout << "Handle = " << (XdmfString)Handle.str() << endl; return( (XdmfString)Handle.str() ); } XdmfObject * HandleToXdmfObject( XdmfConstString Source ){ XdmfString src = new char[ strlen(Source) + 1 ]; strcpy(src, Source); istrstream Handle( src, strlen(src)); char c; XDMF_64_INT RealObjectPointer; XdmfObject *RealObject = NULL, **Rpt = &RealObject; Handle >> c; if( c != '_' ) { XdmfErrorMessage("Bad Handle " << Source ); delete [] src; return( NULL ); } Handle.setf(ios::hex,ios::basefield); XDMF_READ_STREAM64(Handle, RealObjectPointer); // cout << "Source = " << Source << endl; // cout << "RealObjectPointer = " << RealObjectPointer << endl; *Rpt = reinterpret_cast<XdmfObject *>(RealObjectPointer); delete [] src; return( RealObject ); } XdmfPointer VoidPointerHandleToXdmfPointer( XdmfConstString Source ){ XdmfString src = new char[ strlen(Source) + 1 ]; strcpy(src, Source); istrstream Handle( src, strlen(src)); char c; XDMF_64_INT RealObjectPointer; XdmfPointer RealObject = NULL, *Rpt = &RealObject; Handle >> c; if( c != '_' ) { XdmfErrorMessage("Bad Handle " << Source ); delete [] src; return( NULL ); } Handle.setf(ios::hex,ios::basefield); XDMF_READ_STREAM64(Handle, RealObjectPointer); // Handle >> RealObjectPointer; // cout << "Source = " << Source << endl; // cout << "RealObjectPointer = " << RealObjectPointer << endl; *Rpt = reinterpret_cast<XdmfPointer>(RealObjectPointer); delete [] src; return( RealObject ); }
28.678788
86
0.559806
[ "model" ]
6d5db4060ec0c0ee95353b4bb28f58758e334e3a
1,788
cpp
C++
Generator/examples/Generator/random_degenerate_point_set.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Generator/examples/Generator/random_degenerate_point_set.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Generator/examples/Generator/random_degenerate_point_set.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Simple_cartesian.h> #include <cassert> #include <vector> #include <algorithm> #include <CGAL/point_generators_2.h> #include <CGAL/algorithm.h> #include <CGAL/random_selection.h> using namespace CGAL; typedef Simple_cartesian<double> R; typedef R::Point_2 Point; typedef Creator_uniform_2<double,Point> Creator; typedef std::vector<Point> Vector; int main() { // Create test point set. Prepare a vector for 1000 points. Vector points; points.reserve(1000); // Create 600 points within a disc of radius 150. Random_points_in_disc_2<Point,Creator> g( 150.0); std::copy_n( g, 600, std::back_inserter(points)); // Create 200 points from a 15 x 15 grid. points_on_square_grid_2( 250.0, 200, std::back_inserter(points),Creator()); // Select 100 points randomly and append them at the end of // the current vector of points. random_selection( points.begin(), points.end(), 100, std::back_inserter(points)); // Create 100 points that are collinear to two randomly chosen // points and append them to the current vector of points. random_collinear_points_2( points.begin(), points.end(), 100, std::back_inserter( points)); // Check that we have really created 1000 points. assert( points.size() == 1000); // Use a random permutation to hide the creation history // of the point set. CGAL::cpp98::random_shuffle( points.begin(), points.end()); // Check range of values. for ( Vector::iterator i = points.begin(); i != points.end(); i++){ assert( i->x() <= 251); assert( i->x() >= -251); assert( i->y() <= 251); assert( i->y() >= -251); } return 0; }
33.111111
79
0.63311
[ "vector" ]
6d65b928d8267df3913b593b007f1f7d01b43f62
3,150
cpp
C++
internal/plugin/gdiplus/gvplugin_gdiplus.cpp
edamato/go-graphviz
c6e832de6f05c754b430d996f3493d507ab7061a
[ "MIT" ]
343
2020-01-28T15:13:22.000Z
2022-03-29T08:03:06.000Z
internal/plugin/gdiplus/gvplugin_gdiplus.cpp
edamato/go-graphviz
c6e832de6f05c754b430d996f3493d507ab7061a
[ "MIT" ]
31
2020-02-21T16:09:37.000Z
2022-03-29T12:23:19.000Z
internal/plugin/gdiplus/gvplugin_gdiplus.cpp
edamato/go-graphviz
c6e832de6f05c754b430d996f3493d507ab7061a
[ "MIT" ]
38
2020-02-05T11:09:55.000Z
2022-03-23T19:09:03.000Z
/* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #include "gvplugin.h" #include "gvplugin_gdiplus.h" extern gvplugin_installed_t gvrender_gdiplus_types[]; extern gvplugin_installed_t gvtextlayout_gdiplus_types[]; extern gvplugin_installed_t gvloadimage_gdiplus_types[]; extern gvplugin_installed_t gvdevice_gdiplus_types[]; extern gvplugin_installed_t gvdevice_gdiplus_types_for_cairo[]; using namespace std; using namespace Gdiplus; /* class id corresponding to each format_type */ static GUID format_id [] = { GUID_NULL, GUID_NULL, ImageFormatBMP, ImageFormatEMF, ImageFormatEMF, ImageFormatGIF, ImageFormatJPEG, ImageFormatPNG, ImageFormatTIFF }; static ULONG_PTR _gdiplusToken = NULL; static void UnuseGdiplus() { GdiplusShutdown(_gdiplusToken); } void UseGdiplus() { /* only startup once, and ensure we get shutdown */ if (!_gdiplusToken) { GdiplusStartupInput input; GdiplusStartup(&_gdiplusToken, &input, NULL); atexit(&UnuseGdiplus); } } const Gdiplus::StringFormat* GetGenericTypographic() { const Gdiplus::StringFormat* format = StringFormat::GenericTypographic(); return format; } void SaveBitmapToStream(Bitmap &bitmap, IStream *stream, int format) { /* search the encoders for one that matches our device id, then save the bitmap there */ GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); UINT encoderNum; UINT encoderSize; GetImageEncodersSize(&encoderNum, &encoderSize); vector<char> codec_buffer(encoderSize); ImageCodecInfo *codecs = (ImageCodecInfo *)&codec_buffer.front(); GetImageEncoders(encoderNum, encoderSize, codecs); for (UINT i = 0; i < encoderNum; ++i) if (memcmp(&(format_id[format]), &codecs[i].FormatID, sizeof(GUID)) == 0) { bitmap.Save(stream, &codecs[i].Clsid, NULL); break; } } static gvplugin_api_t apis[] = { {API_render, gvrender_gdiplus_types}, {API_textlayout, gvtextlayout_gdiplus_types}, {API_loadimage, gvloadimage_gdiplus_types}, {API_device, gvdevice_gdiplus_types}, {API_device, gvdevice_gdiplus_types_for_cairo}, {(api_t)0, 0}, }; #ifdef WIN32_DLL /*visual studio*/ #ifndef GVPLUGIN_GDIPLUS_EXPORTS __declspec(dllimport) gvplugin_library_t gvplugin_gdiplus_LTX_library = { "gdiplus", apis }; #else __declspec(dllexport) gvplugin_library_t gvplugin_gdiplus_LTX_library = { "gdiplus", apis }; #endif #else /*end visual studio*/ #ifdef GVDLL __declspec(dllexport) gvplugin_library_t gvplugin_gdiplus_LTX_library = { "gdiplus", apis }; #else extern "C" gvplugin_library_t gvplugin_gdiplus_LTX_library = { "gdiplus", apis }; #endif #endif
29.716981
92
0.733333
[ "vector" ]
6d67cac8f73ca44ca148a49dca9e4e2e3a12a5ed
3,326
cpp
C++
divi/src/AddrDB.cpp
smcneilly4/xCoin
e4f9fa4af1ad07e03fdad792be3b5d4288947b7e
[ "MIT" ]
56
2019-05-16T21:31:18.000Z
2022-03-16T16:13:02.000Z
divi/src/AddrDB.cpp
smcneilly4/xCoin
e4f9fa4af1ad07e03fdad792be3b5d4288947b7e
[ "MIT" ]
98
2018-03-07T19:30:42.000Z
2019-04-29T14:17:12.000Z
divi/src/AddrDB.cpp
smcneilly4/xCoin
e4f9fa4af1ad07e03fdad792be3b5d4288947b7e
[ "MIT" ]
38
2019-05-07T11:08:41.000Z
2022-03-02T20:06:12.000Z
#include <AddrDB.h> #include <vector> #include <string> #include <DataDirectory.h> #include <random.h> #include <tinyformat.h> #include <streams.h> #include <Logging.h> #include <uint256.h> #include <util.h> #include <serialize.h> #include <clientversion.h> #include <chainparams.h> #include <hash.h> #include <addrman.h> #include <boost/filesystem.hpp> CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open output file, and associate with CAutoFile boost::filesystem::path pathAddr = GetDataDir() / "peers.dat"; FILE* file = fopen(pathAddr.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE* file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; std::vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("%s : Checksum mismatch, data corrupted", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s : Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } return true; }
30.236364
81
0.644017
[ "object", "vector" ]
6d6e253c046051a2b1c4e6c3307100337b89eba8
1,283
cpp
C++
LeetCode/673.cpp
ZubinGou/leetcode
25ac47a5406af04adbc69482afe0acc2abba25ca
[ "Apache-2.0" ]
1
2021-08-04T00:52:30.000Z
2021-08-04T00:52:30.000Z
LeetCode/673.cpp
ZubinGou/leetcode
25ac47a5406af04adbc69482afe0acc2abba25ca
[ "Apache-2.0" ]
null
null
null
LeetCode/673.cpp
ZubinGou/leetcode
25ac47a5406af04adbc69482afe0acc2abba25ca
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <climits> #include <string> #include <vector> using namespace std; class Solution { public: int findNumberOfLIS(vector<int>& nums) { int n = nums.size(); vector<int> dp(n); vector<int> count(n); int max_dp = 1; for (int i = 0; i < n; i++) { dp[i] = count[i] = 1; for (int j = i - 1; j >= 0; j--) { if (nums[j] < nums[i]) { if (dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; count[i] = count[j]; } else if (dp[j] + 1 == dp[i]) { count[i] += count[j]; } } } max_dp = max(max_dp, dp[i]); } cout << max_dp << endl; for (int i = 0; i < n; i++) cout << "count[" << i << "] = " << count[i] << endl; int res = 0; for (int i = 0; i < n; i++) { if (dp[i] == max_dp) { res += count[i]; } } return res; } }; int main() { Solution sol; vector<int> nums({1,1,1,2,2,2,3,3,3}); int res = sol.findNumberOfLIS(nums); cout << res; }
24.207547
64
0.353858
[ "vector" ]
6d793c9a035eef992918d0db331f6a7961028394
2,835
cpp
C++
audio_editor_core/audio_editor_core/file_track/ae_file_module_utils.cpp
objective-audio/audio_editor
649f74cdca3d7db3d618922a345ea158a0c03a1d
[ "MIT" ]
null
null
null
audio_editor_core/audio_editor_core/file_track/ae_file_module_utils.cpp
objective-audio/audio_editor
649f74cdca3d7db3d618922a345ea158a0c03a1d
[ "MIT" ]
null
null
null
audio_editor_core/audio_editor_core/file_track/ae_file_module_utils.cpp
objective-audio/audio_editor
649f74cdca3d7db3d618922a345ea158a0c03a1d
[ "MIT" ]
null
null
null
// // ae_file_module_utils.cpp // #include "ae_file_module_utils.h" using namespace yas; using namespace yas::ae; std::optional<file_module> file_module_utils::module(file_track_module_map_t const &modules, frame_index_t const frame) { for (auto const &pair : modules) { if (pair.first.is_contain(frame)) { return pair.second; } } return std::nullopt; } std::optional<file_module> file_module_utils::first_module(file_track_module_map_t const &modules) { auto const iterator = modules.cbegin(); if (iterator != modules.cend()) { return iterator->second; } return std::nullopt; } std::optional<file_module> file_module_utils::last_module(file_track_module_map_t const &modules) { auto const iterator = modules.crbegin(); if (iterator != modules.crend()) { return iterator->second; } return std::nullopt; } std::optional<file_module> file_module_utils::previous_module(file_track_module_map_t const &modules, frame_index_t const frame) { auto it = modules.rbegin(); while (it != modules.rend()) { auto const &pair = *it; if (pair.first.next_frame() <= frame) { return pair.second; } ++it; } return std::nullopt; } std::optional<file_module> file_module_utils::next_module(file_track_module_map_t const &modules, frame_index_t const frame) { for (auto const &pair : modules) { if (frame < pair.first.frame) { return pair.second; } } return std::nullopt; } bool file_module_utils::can_split_time_range(time::range const &range, frame_index_t const frame) { return range.is_contain(frame) && range.frame != frame; } std::optional<file_module> file_module_utils::splittable_module(file_track_module_map_t const &modules, frame_index_t const frame) { for (auto const &pair : modules) { if (can_split_time_range(pair.second.range, frame)) { return pair.second; } } return std::nullopt; } std::vector<file_module> file_module_utils::overlapped_modules(file_track_module_map_t const &modules, time::range const &range) { auto const next_frame = range.next_frame(); std::vector<file_module> result; for (auto const &pair : modules) { auto const &module_range = pair.first; if (next_frame <= module_range.frame) { break; } if (module_range.is_overlap(range)) { result.emplace_back(pair.second); } } return result; }
30.815217
103
0.594709
[ "vector" ]
6d7ae8c3d98dd6d51d0b69dd644c0ec4916633c5
68,097
cpp
C++
Engine/Plugins/2D/Paper2D/Source/Paper2D/Private/PaperSprite.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Plugins/2D/Paper2D/Source/Paper2D/Private/PaperSprite.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Plugins/2D/Paper2D/Source/Paper2D/Private/PaperSprite.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "Paper2DPrivatePCH.h" #include "PaperSprite.h" #include "PhysicsEngine/BodySetup.h" #include "PhysicsEngine/BodySetup2D.h" #include "PaperCustomVersion.h" #include "PaperGeomTools.h" #include "PaperSpriteComponent.h" #include "PaperFlipbookComponent.h" #include "PaperGroupedSpriteComponent.h" #include "SpriteDrawCall.h" #if WITH_EDITOR #include "UnrealEd.h" #endif #if WITH_EDITOR static void UpdateGeometryToBeBoxPositionRelative(FSpriteGeometryCollection& Geometry) { // Make sure the per-shape GeometryType fields are up to date (introduced in this version) const bool bWasBoundingBox = (Geometry.GeometryType == ESpritePolygonMode::SourceBoundingBox) || (Geometry.GeometryType == ESpritePolygonMode::TightBoundingBox); if (bWasBoundingBox) { for (FSpriteGeometryShape& Shape : Geometry.Shapes) { Shape.ShapeType = ESpriteShapeType::Box; // Recenter the bounding box (BoxPosition is now defined as the center) const FVector2D AmountToSubtract = Shape.BoxPosition + Shape.BoxSize * 0.5f; Shape.BoxPosition += Shape.BoxSize * 0.5f; for (FVector2D& Vertex : Shape.Vertices) { Vertex -= AmountToSubtract; } } } else { for (FSpriteGeometryShape& Shape : Geometry.Shapes) { Shape.ShapeType = ESpriteShapeType::Polygon; // Make sure BoxPosition is zeroed since polygon points are relative to it now, but it was being ignored //@TODO: Consider computing the center and recentering verts to keep the numbers small/relative Shape.BoxPosition = FVector2D::ZeroVector; Shape.BoxSize = FVector2D::ZeroVector; } } } #endif #if WITH_EDITOR #include "PaperSpriteAtlas.h" #include "GeomTools.h" #include "BitmapUtils.h" #include "ComponentReregisterContext.h" #include "PaperRuntimeSettings.h" ////////////////////////////////////////////////////////////////////////// // maf void RemoveCollinearPoints(TArray<FIntPoint>& PointList) { if (PointList.Num() < 3) { return; } // Wrap around to get the final pair of vertices (N-1, 0, 1) for (int32 VertexIndex = 1; VertexIndex <= PointList.Num() && PointList.Num() >= 3; ) { const FVector2D A(PointList[VertexIndex-1]); const FVector2D B(PointList[VertexIndex % PointList.Num()]); const FVector2D C(PointList[(VertexIndex+1) % PointList.Num()]); // Determine if the area of the triangle ABC is zero (if so, they're collinear) const float AreaABC = (A.X * (B.Y - C.Y)) + (B.X * (C.Y - A.Y)) + (C.X * (A.Y - B.Y)); if (FMath::Abs(AreaABC) < KINDA_SMALL_NUMBER) { // Remove B PointList.RemoveAt(VertexIndex % PointList.Num()); } else { // Continue onwards ++VertexIndex; } } } float DotPoints(const FIntPoint& V1, const FIntPoint& V2) { return (V1.X * V2.X) + (V1.Y * V2.Y); } struct FDouglasPeuckerSimplifier { FDouglasPeuckerSimplifier(const TArray<FIntPoint>& InSourcePoints, float Epsilon) : SourcePoints(InSourcePoints) , EpsilonSquared(Epsilon * Epsilon) , NumRemoved(0) { OmitPoints.AddZeroed(SourcePoints.Num()); } TArray<FIntPoint> SourcePoints; TArray<bool> OmitPoints; const float EpsilonSquared; int32 NumRemoved; // Removes all points between Index1 and Index2, not including them void RemovePoints(int32 Index1, int32 Index2) { for (int32 Index = Index1 + 1; Index < Index2; ++Index) { OmitPoints[Index] = true; ++NumRemoved; } } void SimplifyPointsInner(int Index1, int Index2) { if (Index2 - Index1 < 2) { return; } // Find furthest point from the V1..V2 line const FVector V1(SourcePoints[Index1].X, 0.0f, SourcePoints[Index1].Y); const FVector V2(SourcePoints[Index2].X, 0.0f, SourcePoints[Index2].Y); const FVector V1V2 = V2 - V1; const float LineScale = 1.0f / V1V2.SizeSquared(); float FarthestDistanceSquared = -1.0f; int32 FarthestIndex = INDEX_NONE; for (int32 Index = Index1; Index < Index2; ++Index) { const FVector VTest(SourcePoints[Index].X, 0.0f, SourcePoints[Index].Y); const FVector V1VTest = VTest - V1; const float t = FMath::Clamp(FVector::DotProduct(V1VTest, V1V2) * LineScale, 0.0f, 1.0f); const FVector ClosestPointOnV1V2 = V1 + t * V1V2; const float DistanceToLineSquared = FVector::DistSquared(ClosestPointOnV1V2, VTest); if (DistanceToLineSquared > FarthestDistanceSquared) { FarthestDistanceSquared = DistanceToLineSquared; FarthestIndex = Index; } } if (FarthestDistanceSquared > EpsilonSquared) { // Too far, subdivide further SimplifyPointsInner(Index1, FarthestIndex); SimplifyPointsInner(FarthestIndex, Index2); } else { // The farthest point wasn't too far, so omit all the points in between RemovePoints(Index1, Index2); } } void Execute(TArray<FIntPoint>& Result) { SimplifyPointsInner(0, SourcePoints.Num() - 1); Result.Empty(SourcePoints.Num() - NumRemoved); for (int32 Index = 0; Index < SourcePoints.Num(); ++Index) { if (!OmitPoints[Index]) { Result.Add(SourcePoints[Index]); } } } }; static void BruteForceSimplifier(TArray<FIntPoint>& Points, float Epsilon) { float FlatEdgeDistanceThreshold = (int)(Epsilon * Epsilon); // Run through twice to remove remnants from staircase artifacts for (int Pass = 0; Pass < 2; ++Pass) { for (int I = 0; I < Points.Num() && Points.Num() > 3; ++I) { int StartRemoveIndex = (I + 1) % Points.Num(); int EndRemoveIndex = StartRemoveIndex; FIntPoint& A = Points[I]; // Keep searching to find if any of the vector rejections fail in subsequent points on the polygon // A B C D E F (eg. when testing A B C, test rejection for BA, CA) // When testing A E F, test rejection for AB-AF, AC-AF, AD-AF, AE-AF // When one of these fails we discard all verts between A and one before the current vertex being tested for (int J = I; J < Points.Num(); ++J) { int IndexC = (J + 2) % Points.Num(); FIntPoint& C = Points[IndexC]; bool bSmallOffsetFailed = false; for (int K = I; K <= J && !bSmallOffsetFailed; ++K) { int IndexB = (K + 1) % Points.Num(); FIntPoint& B = Points[IndexB]; FVector2D CA = C - A; FVector2D BA = B - A; FVector2D Rejection_BA_CA = BA - (FVector2D::DotProduct(BA, CA) / FVector2D::DotProduct(CA, CA)) * CA; float RejectionLengthSquared = Rejection_BA_CA.SizeSquared(); // If any of the points is behind the polyline up till now, it gets rejected. Staircase artefacts are handled in a second pass if (RejectionLengthSquared > FlatEdgeDistanceThreshold || FVector2D::CrossProduct(CA, BA) < 0) { bSmallOffsetFailed = true; break; } } if (bSmallOffsetFailed) { break; } else { EndRemoveIndex = (EndRemoveIndex + 1) % Points.Num(); } } // Remove the vertices that we deemed "too flat" if (EndRemoveIndex > StartRemoveIndex) { Points.RemoveAt(StartRemoveIndex, EndRemoveIndex - StartRemoveIndex); } else if (EndRemoveIndex < StartRemoveIndex) { Points.RemoveAt(StartRemoveIndex, Points.Num() - StartRemoveIndex); Points.RemoveAt(0, EndRemoveIndex); // The search has wrapped around, no more vertices to test break; } } } // Pass } void SimplifyPoints(TArray<FIntPoint>& Points, float Epsilon) { // FDouglasPeuckerSimplifier Simplifier(Points, Epsilon); // Simplifier.Execute(Points); BruteForceSimplifier(Points, Epsilon); } ////////////////////////////////////////////////////////////////////////// // FBoundaryImage struct FBoundaryImage { TArray<int8> Pixels; // Value to return out of bounds int8 OutOfBoundsValue; int32 X0; int32 Y0; int32 Width; int32 Height; FBoundaryImage(const FIntPoint& Pos, const FIntPoint& Size) { OutOfBoundsValue = 0; X0 = Pos.X - 1; Y0 = Pos.Y - 1; Width = Size.X + 2; Height = Size.Y + 2; Pixels.AddZeroed(Width * Height); } int32 GetIndex(int32 X, int32 Y) const { const int32 LocalX = X - X0; const int32 LocalY = Y - Y0; if ((LocalX >= 0) && (LocalX < Width) && (LocalY >= 0) && (LocalY < Height)) { return LocalX + (LocalY * Width); } else { return INDEX_NONE; } } int8 GetPixel(int32 X, int32 Y) const { const int32 Index = GetIndex(X, Y); if (Index != INDEX_NONE) { return Pixels[Index]; } else { return OutOfBoundsValue; } } void SetPixel(int32 X, int32 Y, int8 Value) { const int32 Index = GetIndex(X, Y); if (Index != INDEX_NONE) { Pixels[Index] = Value; } } }; void UPaperSprite::ExtractSourceRegionFromTexturePoint(const FVector2D& SourcePoint) { FIntPoint SourceIntPoint(FMath::RoundToInt(SourcePoint.X), FMath::RoundToInt(SourcePoint.Y)); FIntPoint ClosestValidPoint; FBitmap Bitmap(SourceTexture, 0, 0); if (Bitmap.IsValid() && Bitmap.FoundClosestValidPoint(SourceIntPoint.X, SourceIntPoint.Y, 10, /*out*/ ClosestValidPoint)) { FIntPoint Origin; FIntPoint Dimension; if (Bitmap.HasConnectedRect(ClosestValidPoint.X, ClosestValidPoint.Y, false, /*out*/ Origin, /*out*/ Dimension)) { if (Dimension.X > 0 && Dimension.Y > 0) { SourceUV = FVector2D(Origin.X, Origin.Y); SourceDimension = FVector2D(Dimension.X, Dimension.Y); PostEditChange(); } } } } #endif ////////////////////////////////////////////////////////////////////////// // FSpriteDrawCallRecord void FSpriteDrawCallRecord::BuildFromSprite(const UPaperSprite* Sprite) { if (Sprite != nullptr) { Destination = FVector::ZeroVector; BaseTexture = Sprite->GetBakedTexture(); Sprite->GetBakedAdditionalSourceTextures(/*out*/ AdditionalTextures); Color = FColor::White; RenderVerts = Sprite->BakedRenderData; } } ////////////////////////////////////////////////////////////////////////// // UPaperSprite UPaperSprite::UPaperSprite(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // Default to using physics SpriteCollisionDomain = ESpriteCollisionMode::Use3DPhysics; AlternateMaterialSplitIndex = INDEX_NONE; #if WITH_EDITORONLY_DATA PivotMode = ESpritePivotMode::Center_Center; bSnapPivotToPixelGrid = true; CollisionGeometry.GeometryType = ESpritePolygonMode::TightBoundingBox; CollisionThickness = 10.0f; bTrimmedInSourceImage = false; bRotatedInSourceImage = false; SourceTextureDimension.Set(0, 0); #endif PixelsPerUnrealUnit = 2.56f; static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaskedMaterialRef(TEXT("/Paper2D/MaskedUnlitSpriteMaterial")); DefaultMaterial = MaskedMaterialRef.Object; static ConstructorHelpers::FObjectFinder<UMaterialInterface> OpaqueMaterialRef(TEXT("/Paper2D/OpaqueUnlitSpriteMaterial")); AlternateMaterial = OpaqueMaterialRef.Object; } #if WITH_EDITOR void UPaperSprite::OnObjectReimported(UTexture2D* Texture) { // Check if its our source texture, and if its dimensions have changed // If SourceTetxureDimension == 0, we don't have a previous dimension to work off, so can't // rescale sensibly if (Texture == GetSourceTexture()) { if (NeedRescaleSpriteData()) { RescaleSpriteData(GetSourceTexture()); PostEditChange(); } else if (AtlasGroup != nullptr) { AtlasGroup->PostEditChange(); } } } #endif #if WITH_EDITOR /** Removes all components that use the specified sprite asset from their scenes for the lifetime of the class. */ class FSpriteReregisterContext { public: /** Initialization constructor. */ FSpriteReregisterContext(UPaperSprite* TargetAsset) { // Look at sprite components for (UPaperSpriteComponent* TestComponent : TObjectRange<UPaperSpriteComponent>()) { if (TestComponent->GetSprite() == TargetAsset) { AddComponentToRefresh(TestComponent); } } // Look at flipbook components for (UPaperFlipbookComponent* TestComponent : TObjectRange<UPaperFlipbookComponent>()) { if (UPaperFlipbook* Flipbook = TestComponent->GetFlipbook()) { if (Flipbook->ContainsSprite(TargetAsset)) { AddComponentToRefresh(TestComponent); } } } // Look at grouped sprite components for (UPaperGroupedSpriteComponent* TestComponent : TObjectRange<UPaperGroupedSpriteComponent>()) { if (TestComponent->ContainsSprite(TargetAsset)) { AddComponentToRefresh(TestComponent); } } } protected: void AddComponentToRefresh(UActorComponent* Component) { if (ComponentContexts.Num() == 0) { // wait until resources are released FlushRenderingCommands(); } new (ComponentContexts) FComponentReregisterContext(Component); } private: /** The recreate contexts for the individual components. */ TIndirectArray<FComponentReregisterContext> ComponentContexts; }; void UPaperSprite::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { //@TODO: Determine when this is really needed, as it is seriously expensive! FSpriteReregisterContext ReregisterExistingComponents(this); // Look for changed properties const FName PropertyName = (PropertyChangedEvent.Property != nullptr) ? PropertyChangedEvent.Property->GetFName() : NAME_None; const FName MemberPropertyName = (PropertyChangedEvent.MemberProperty != nullptr) ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None; if (PixelsPerUnrealUnit <= 0.0f) { PixelsPerUnrealUnit = 1.0f; } if (CollisionGeometry.GeometryType == ESpritePolygonMode::Diced) { // Disallow dicing on collision geometry for now CollisionGeometry.GeometryType = ESpritePolygonMode::SourceBoundingBox; } RenderGeometry.PixelsPerSubdivisionX = FMath::Max(RenderGeometry.PixelsPerSubdivisionX, 4); RenderGeometry.PixelsPerSubdivisionY = FMath::Max(RenderGeometry.PixelsPerSubdivisionY, 4); if (MemberPropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, SourceUV)) { SourceUV.X = FMath::Max(FMath::RoundToFloat(SourceUV.X), 0.0f); SourceUV.Y = FMath::Max(FMath::RoundToFloat(SourceUV.Y), 0.0f); } else if (MemberPropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, SourceDimension)) { SourceDimension.X = FMath::Max(FMath::RoundToFloat(SourceDimension.X), 0.0f); SourceDimension.Y = FMath::Max(FMath::RoundToFloat(SourceDimension.Y), 0.0f); } // Update the pivot (roundtripping thru the function will round to a pixel position if that option is enabled) CustomPivotPoint = GetPivotPosition(); bool bRenderDataModified = false; bool bCollisionDataModified = false; bool bBothModified = false; if ((PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, SpriteCollisionDomain)) || (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, BodySetup)) || (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, CollisionGeometry)) ) { bCollisionDataModified = true; } // Properties inside one of the geom structures (we don't know which one) // if ((PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, GeometryType)) || // (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, AlphaThreshold)) || // ) // BoxSize // BoxPosition // Vertices // VertexCount // Polygons // { bBothModified = true; // } if ((PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, SourceUV)) || (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, SourceDimension)) || (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, CustomPivotPoint)) || (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, PivotMode)) ) { bBothModified = true; } if (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, SourceTexture)) { if ((SourceTexture != nullptr) && SourceDimension.IsNearlyZero()) { // If this is a brand new sprite that didn't have a texture set previously, act like we were factoried with the texture SourceUV = FVector2D::ZeroVector; SourceDimension = FVector2D(SourceTexture->GetImportedSize()); SourceTextureDimension = SourceDimension; } bBothModified = true; } if (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, Sockets) || (MemberPropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, Sockets) && PropertyName == GET_MEMBER_NAME_CHECKED(FPaperSpriteSocket, SocketName))) { ValidateSocketNames(); } if (PropertyName == GET_MEMBER_NAME_CHECKED(UPaperSprite, AtlasGroup)) { auto SpriteAssetPtr = PreviousAtlasGroup; FStringAssetReference AtlasGroupStringRef = SpriteAssetPtr.ToStringReference(); UPaperSpriteAtlas* PreviousAtlasGroupPtr = nullptr; if (!AtlasGroupStringRef.ToString().IsEmpty()) { PreviousAtlasGroupPtr = Cast<UPaperSpriteAtlas>(StaticLoadObject(UPaperSpriteAtlas::StaticClass(), nullptr, *AtlasGroupStringRef.ToString(), nullptr, LOAD_None, nullptr)); } if (PreviousAtlasGroupPtr != AtlasGroup) { // Update previous if (PreviousAtlasGroupPtr != nullptr) { PreviousAtlasGroupPtr->PostEditChange(); } // Update cached previous atlas group PreviousAtlasGroup = AtlasGroup; // Rebuild atlas group if (AtlasGroup != nullptr) { AtlasGroup->PostEditChange(); } else { BakedSourceTexture = nullptr; BakedSourceUV = FVector2D(0, 0); bRenderDataModified = true; } } } // The texture dimensions have changed //if (NeedRescaleSpriteData()) //{ // TMP: Disabled, not sure if we want this here // RescaleSpriteData(GetSourceTexture()); // bBothModified = true; //} // Don't do rebuilds during an interactive event to make things more responsive. // They'll always be followed by a ValueSet event at the end to force the change. if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Interactive) { bCollisionDataModified = false; bRenderDataModified = false; bBothModified = false; } if (bCollisionDataModified || bBothModified) { RebuildCollisionData(); } if (bRenderDataModified || bBothModified) { RebuildRenderData(); } Super::PostEditChangeProperty(PropertyChangedEvent); } void UPaperSprite::RescaleSpriteData(UTexture2D* Texture) { Texture->ConditionalPostLoad(); FVector2D PreviousTextureDimension = SourceTextureDimension; FVector2D NewTextureDimension(Texture->GetImportedSize().X, Texture->GetImportedSize().Y); // Don't ever divby0 (no previously stored texture dimensions) // or scale to 0, should be covered by NeedRescaleSpriteData if (NewTextureDimension.X == 0 || NewTextureDimension.Y == 0 || PreviousTextureDimension.X == 0 || PreviousTextureDimension.Y == 0) { return; } const FVector2D& S = NewTextureDimension; const FVector2D& D = PreviousTextureDimension; struct Local { static float NoSnap(const float Value, const float Scale, const float Divisor) { return (Value * Scale) / Divisor; } static FVector2D RescaleNeverSnap(const FVector2D& Value, const FVector2D& Scale, const FVector2D& Divisor) { return FVector2D(NoSnap(Value.X, Scale.X, Divisor.X), NoSnap(Value.Y, Scale.Y, Divisor.Y)); } static FVector2D Rescale(const FVector2D& Value, const FVector2D& Scale, const FVector2D& Divisor) { // Never snap, want to be able to return to original values when rescaled back return RescaleNeverSnap(Value, Scale, Divisor); //return FVector2D(FMath::FloorToFloat(NoSnap(Value.X, Scale.X, Divisor.X)), FMath::FloorToFloat(NoSnap(Value.Y, Scale.Y, Divisor.Y))); } }; // Sockets are in pivot space, convert these to texture space to apply later TArray<FVector2D> RescaledTextureSpaceSocketPositions; for (int32 SocketIndex = 0; SocketIndex < Sockets.Num(); ++SocketIndex) { FPaperSpriteSocket& Socket = Sockets[SocketIndex]; FVector Translation = Socket.LocalTransform.GetTranslation(); FVector2D TextureSpaceSocketPosition = ConvertPivotSpaceToTextureSpace(FVector2D(Translation.X, Translation.Z)); RescaledTextureSpaceSocketPositions.Add(Local::RescaleNeverSnap(TextureSpaceSocketPosition, S, D)); } SourceUV = Local::Rescale(SourceUV, S, D); SourceDimension = Local::Rescale(SourceDimension, S, D); SourceImageDimensionBeforeTrimming = Local::Rescale(SourceImageDimensionBeforeTrimming, S, D); SourceTextureDimension = NewTextureDimension; if (bSnapPivotToPixelGrid) { CustomPivotPoint = Local::Rescale(CustomPivotPoint, S, D); } else { CustomPivotPoint = Local::RescaleNeverSnap(CustomPivotPoint, S, D); } for (int32 GeometryIndex = 0; GeometryIndex < 2; ++GeometryIndex) { FSpriteGeometryCollection& Geometry = (GeometryIndex == 0) ? CollisionGeometry : RenderGeometry; for (FSpriteGeometryShape& Shape : Geometry.Shapes) { Shape.BoxPosition = Local::Rescale(Shape.BoxPosition, S, D); Shape.BoxSize = Local::Rescale(Shape.BoxSize, S, D); for (FVector2D& Vertex : Shape.Vertices) { const FVector2D TextureSpaceVertex = Shape.ConvertShapeSpaceToTextureSpace(Vertex); const FVector2D ScaledTSVertex = Local::Rescale(TextureSpaceVertex, S, D); Vertex = Shape.ConvertTextureSpaceToShapeSpace(ScaledTSVertex); } } } // Apply texture space pivot positions now that pivot space is correctly defined for (int32 SocketIndex = 0; SocketIndex < Sockets.Num(); ++SocketIndex) { const FVector2D PivotSpaceSocketPosition = ConvertTextureSpaceToPivotSpace(RescaledTextureSpaceSocketPositions[SocketIndex]); FPaperSpriteSocket& Socket = Sockets[SocketIndex]; FVector Translation = Socket.LocalTransform.GetTranslation(); Translation.X = PivotSpaceSocketPosition.X; Translation.Z = PivotSpaceSocketPosition.Y; Socket.LocalTransform.SetTranslation(Translation); } } bool UPaperSprite::NeedRescaleSpriteData() { const bool bSupportsRescaling = GetDefault<UPaperRuntimeSettings>()->bResizeSpriteDataToMatchTextures; if (bSupportsRescaling) { if (UTexture2D* Texture = GetSourceTexture()) { Texture->ConditionalPostLoad(); const FIntPoint TextureSize = Texture->GetImportedSize(); const bool bTextureSizeIsZero = (TextureSize.X == 0) || (TextureSize.Y == 0); return !SourceTextureDimension.IsZero() && !bTextureSizeIsZero && ((TextureSize.X != SourceTextureDimension.X) || (TextureSize.Y != SourceTextureDimension.Y)); } } return false; } class FPaperSpriteToBodySetupBuilder : public FSpriteGeometryCollisionBuilderBase { public: FPaperSpriteToBodySetupBuilder(UPaperSprite* InSprite, UBodySetup* InBodySetup) : FSpriteGeometryCollisionBuilderBase(InBodySetup) , MySprite(InSprite) { UnrealUnitsPerPixel = InSprite->GetUnrealUnitsPerPixel(); CollisionThickness = InSprite->GetCollisionThickness(); CollisionDomain = InSprite->GetSpriteCollisionDomain(); } protected: // FSpriteGeometryCollisionBuilderBase interface virtual FVector2D ConvertTextureSpaceToPivotSpace(const FVector2D& Input) const override { return MySprite->ConvertTextureSpaceToPivotSpace(Input); } virtual FVector2D ConvertTextureSpaceToPivotSpaceNoTranslation(const FVector2D& Input) const override { return MySprite->IsRotatedInSourceImage() ? FVector2D(Input.Y, Input.X) : Input; } // End of FSpriteGeometryCollisionBuilderBase protected: UPaperSprite* MySprite; }; void UPaperSprite::RebuildCollisionData() { UBodySetup* OldBodySetup = BodySetup; // Ensure we have the data structure for the desired collision method switch (SpriteCollisionDomain) { case ESpriteCollisionMode::Use3DPhysics: BodySetup = nullptr; if (BodySetup == nullptr) { BodySetup = NewObject<UBodySetup>(this); } break; case ESpriteCollisionMode::Use2DPhysics: BodySetup = nullptr; if (BodySetup == nullptr) { BodySetup = NewObject<UBodySetup2D>(this); } break; case ESpriteCollisionMode::None: BodySetup = nullptr; CollisionGeometry.Reset(); break; } if (SpriteCollisionDomain != ESpriteCollisionMode::None) { BodySetup->CollisionTraceFlag = CTF_UseSimpleAsComplex; switch (CollisionGeometry.GeometryType) { case ESpritePolygonMode::Diced: case ESpritePolygonMode::SourceBoundingBox: // Ignore diced, treat it like SourceBoundingBox, which just uses the loose bounds CreatePolygonFromBoundingBox(CollisionGeometry, /*bUseTightBounds=*/ false); break; case ESpritePolygonMode::TightBoundingBox: // Analyze the texture to tighten the bounds CreatePolygonFromBoundingBox(CollisionGeometry, /*bUseTightBounds=*/ true); break; case ESpritePolygonMode::ShrinkWrapped: // Analyze the texture and rebuild the geometry BuildGeometryFromContours(CollisionGeometry); break; case ESpritePolygonMode::FullyCustom: // Nothing to rebuild, the data is already ready break; default: check(false); // unknown mode }; // Clean up the geometry (converting polygons back to bounding boxes, etc...) CollisionGeometry.ConditionGeometry(); // Take the geometry and add it to the body setup FPaperSpriteToBodySetupBuilder CollisionBuilder(this, BodySetup); CollisionBuilder.ProcessGeometry(CollisionGeometry); CollisionBuilder.Finalize(); // Copy across or initialize the only editable property we expose on the body setup if (OldBodySetup != nullptr) { BodySetup->DefaultInstance.CopyBodyInstancePropertiesFrom(&(OldBodySetup->DefaultInstance)); } else { BodySetup->DefaultInstance.SetCollisionProfileName(UCollisionProfile::BlockAllDynamic_ProfileName); } } } void UPaperSprite::RebuildRenderData() { FSpriteGeometryCollection AlternateGeometry; switch (RenderGeometry.GeometryType) { case ESpritePolygonMode::Diced: case ESpritePolygonMode::SourceBoundingBox: CreatePolygonFromBoundingBox(RenderGeometry, /*bUseTightBounds=*/ false); break; case ESpritePolygonMode::TightBoundingBox: CreatePolygonFromBoundingBox(RenderGeometry, /*bUseTightBounds=*/ true); break; case ESpritePolygonMode::ShrinkWrapped: BuildGeometryFromContours(RenderGeometry); break; case ESpritePolygonMode::FullyCustom: // Do nothing special, the data is already in the polygon break; default: check(false); // unknown mode }; // Determine the texture size UTexture2D* EffectiveTexture = GetBakedTexture(); FVector2D TextureSize(1.0f, 1.0f); if (EffectiveTexture) { EffectiveTexture->ConditionalPostLoad(); TextureSize = FVector2D(EffectiveTexture->GetImportedSize()); } const float InverseWidth = 1.0f / TextureSize.X; const float InverseHeight = 1.0f / TextureSize.Y; // Adjust for the pivot and store in the baked geometry buffer const FVector2D DeltaUV((BakedSourceTexture != nullptr) ? (BakedSourceUV - SourceUV) : FVector2D::ZeroVector); const float UnitsPerPixel = GetUnrealUnitsPerPixel(); if ((RenderGeometry.GeometryType == ESpritePolygonMode::Diced) && (EffectiveTexture != nullptr)) { const int32 AlphaThresholdInt = FMath::Clamp<int32>(RenderGeometry.AlphaThreshold * 255, 0, 255); FAlphaBitmap SourceBitmap(EffectiveTexture); SourceBitmap.ThresholdImageBothWays(AlphaThresholdInt, 255); bool bSeparateOpaqueSections = true; // Dice up the source geometry and sort into translucent and opaque sections RenderGeometry.Shapes.Empty(); const int32 X0 = (int32)SourceUV.X; const int32 Y0 = (int32)SourceUV.Y; const int32 X1 = (int32)(SourceUV.X + SourceDimension.X); const int32 Y1 = (int32)(SourceUV.Y + SourceDimension.Y); for (int32 Y = Y0; Y < Y1; Y += RenderGeometry.PixelsPerSubdivisionY) { const int32 TileHeight = FMath::Min(RenderGeometry.PixelsPerSubdivisionY, Y1 - Y); for (int32 X = X0; X < X1; X += RenderGeometry.PixelsPerSubdivisionX) { const int32 TileWidth = FMath::Min(RenderGeometry.PixelsPerSubdivisionX, X1 - X); if (!SourceBitmap.IsRegionEmpty(X, Y, X + TileWidth - 1, Y + TileHeight - 1)) { FIntPoint Origin(X, Y); FIntPoint Dimension(TileWidth, TileHeight); SourceBitmap.TightenBounds(Origin, Dimension); bool bOpaqueSection = false; if (bSeparateOpaqueSections) { if (SourceBitmap.IsRegionEqual(Origin.X, Origin.Y, Origin.X + Dimension.X - 1, Origin.Y + Dimension.Y - 1, 255)) { bOpaqueSection = true; } } const FVector2D BoxCenter = FVector2D(Origin) + (FVector2D(Dimension) * 0.5f); if (bOpaqueSection) { AlternateGeometry.AddRectangleShape(BoxCenter, Dimension); } else { RenderGeometry.AddRectangleShape(BoxCenter, Dimension); } } } } } // Triangulate the render geometry TArray<FVector2D> TriangluatedPoints; RenderGeometry.Triangulate(/*out*/ TriangluatedPoints, /*bIncludeBoxes=*/ true); // Triangulate the alternate render geometry, if present if (AlternateGeometry.Shapes.Num() > 0) { TArray<FVector2D> AlternateTriangluatedPoints; AlternateGeometry.Triangulate(/*out*/ AlternateTriangluatedPoints, /*bIncludeBoxes=*/ true); AlternateMaterialSplitIndex = TriangluatedPoints.Num(); TriangluatedPoints.Append(AlternateTriangluatedPoints); RenderGeometry.Shapes.Append(AlternateGeometry.Shapes); } else { AlternateMaterialSplitIndex = INDEX_NONE; } // Bake the verts BakedRenderData.Empty(TriangluatedPoints.Num()); for (int32 PointIndex = 0; PointIndex < TriangluatedPoints.Num(); ++PointIndex) { const FVector2D& SourcePos = TriangluatedPoints[PointIndex]; const FVector2D PivotSpacePos = ConvertTextureSpaceToPivotSpace(SourcePos); const FVector2D UV(SourcePos + DeltaUV); new (BakedRenderData) FVector4(PivotSpacePos.X * UnitsPerPixel, PivotSpacePos.Y * UnitsPerPixel, UV.X * InverseWidth, UV.Y * InverseHeight); } check((BakedRenderData.Num() % 3) == 0); // Swap the generated vertices so they end up in counterclockwise order for (int32 SVT = 0; SVT < TriangluatedPoints.Num(); SVT += 3) { Swap(BakedRenderData[SVT + 2], BakedRenderData[SVT + 0]); } } void UPaperSprite::FindTextureBoundingBox(float AlphaThreshold, /*out*/ FVector2D& OutBoxPosition, /*out*/ FVector2D& OutBoxSize) { // Create an initial guess at the bounds based on the source rectangle int32 LeftBound = (int32)SourceUV.X; int32 RightBound = (int32)(SourceUV.X + SourceDimension.X - 1); int32 TopBound = (int32)SourceUV.Y; int32 BottomBound = (int32)(SourceUV.Y + SourceDimension.Y - 1); const int32 AlphaThresholdInt = FMath::Clamp<int32>(AlphaThreshold * 255, 0, 255); FBitmap SourceBitmap(SourceTexture, AlphaThresholdInt); if (SourceBitmap.IsValid()) { // Make sure the initial bounds starts in the texture LeftBound = FMath::Clamp(LeftBound, 0, SourceBitmap.Width-1); RightBound = FMath::Clamp(RightBound, 0, SourceBitmap.Width-1); TopBound = FMath::Clamp(TopBound, 0, SourceBitmap.Height-1); BottomBound = FMath::Clamp(BottomBound, 0, SourceBitmap.Height-1); // Pull it in from the top while ((TopBound < BottomBound) && SourceBitmap.IsRowEmpty(LeftBound, RightBound, TopBound)) { ++TopBound; } // Pull it in from the bottom while ((BottomBound > TopBound) && SourceBitmap.IsRowEmpty(LeftBound, RightBound, BottomBound)) { --BottomBound; } // Pull it in from the left while ((LeftBound < RightBound) && SourceBitmap.IsColumnEmpty(LeftBound, TopBound, BottomBound)) { ++LeftBound; } // Pull it in from the right while ((RightBound > LeftBound) && SourceBitmap.IsColumnEmpty(RightBound, TopBound, BottomBound)) { --RightBound; } } OutBoxSize.X = RightBound - LeftBound + 1; OutBoxSize.Y = BottomBound - TopBound + 1; OutBoxPosition.X = LeftBound; OutBoxPosition.Y = TopBound; } // Get a divisor ("pixel" size) from the "detail" parameter // Size is fed in for possible changes later static int32 GetDivisorFromDetail(const FIntPoint& Size, float Detail) { //@TODO: Consider MaxSize somehow when deciding divisor //int32 MaxSize = FMath::Max(Size.X, Size.Y); return FMath::Lerp(8, 1, FMath::Clamp(Detail, 0.0f, 1.0f)); } void UPaperSprite::BuildGeometryFromContours(FSpriteGeometryCollection& GeomOwner) { // First trim the image to the tight fitting bounding box (the other pixels can't matter) FVector2D InitialBoxSizeFloat; FVector2D InitialBoxPosFloat; FindTextureBoundingBox(GeomOwner.AlphaThreshold, /*out*/ InitialBoxPosFloat, /*out*/ InitialBoxSizeFloat); const FIntPoint InitialPos((int32)InitialBoxPosFloat.X, (int32)InitialBoxPosFloat.Y); const FIntPoint InitialSize((int32)InitialBoxSizeFloat.X, (int32)InitialBoxSizeFloat.Y); // Find the contours TArray< TArray<FIntPoint> > Contours; // DK: FindContours only returns positive contours, i.e. outsides // Contour generation is simplified in FindContours by downscaling the detail prior to generating contour data FindContours(InitialPos, InitialSize, GeomOwner.AlphaThreshold, GeomOwner.DetailAmount, SourceTexture, /*out*/ Contours); // Convert the contours into geometry GeomOwner.Shapes.Empty(); for (int32 ContourIndex = 0; ContourIndex < Contours.Num(); ++ContourIndex) { TArray<FIntPoint>& Contour = Contours[ContourIndex]; // Scale the simplification epsilon by the size we know the pixels will be int Divisor = GetDivisorFromDetail(InitialSize, GeomOwner.DetailAmount); SimplifyPoints(Contour, GeomOwner.SimplifyEpsilon * Divisor); if (Contour.Num() > 0) { FSpriteGeometryShape& NewShape = *new (GeomOwner.Shapes) FSpriteGeometryShape(); NewShape.ShapeType = ESpriteShapeType::Polygon; NewShape.Vertices.Empty(Contour.Num()); // Add the points for (int32 PointIndex = 0; PointIndex < Contour.Num(); ++PointIndex) { new (NewShape.Vertices) FVector2D(NewShape.ConvertTextureSpaceToShapeSpace(Contour[PointIndex])); } // Recenter them const FVector2D AverageCenterFloat = NewShape.GetPolygonCentroid(); const FVector2D AverageCenterSnapped(FMath::RoundToInt(AverageCenterFloat.X), FMath::RoundToInt(AverageCenterFloat.Y)); NewShape.SetNewPivot(AverageCenterSnapped); // Get intended winding NewShape.bNegativeWinding = !PaperGeomTools::IsPolygonWindingCCW(NewShape.Vertices); } } } static void TraceContour(TArray<FIntPoint>& Result, const TArray<FIntPoint>& Points) { const int PointCount = Points.Num(); if (PointCount < 2) { return; } int CurrentX = (int)Points[0].X; int CurrentY = (int)Points[0].Y; int CurrentDirection = 0; int FirstDx = (int)Points[1].X - CurrentX; int FirstDy = (int)Points[1].Y - CurrentY; if (FirstDx == 1 && FirstDy == 0) CurrentDirection = 0; else if (FirstDx == 1 && FirstDy == 1) CurrentDirection = 1; else if (FirstDx == 0 && FirstDy == 1) CurrentDirection = 1; else if (FirstDx == -1 && FirstDy == 1) CurrentDirection = 2; else if (FirstDx == -1 && FirstDy == 0) CurrentDirection = 2; else if (FirstDx == -1 && FirstDy == -1) CurrentDirection = 3; else if (FirstDx == 0 && FirstDy == -1) CurrentDirection = 3; else if (FirstDx == 1 && FirstDy == -1) CurrentDirection = 0; int CurrentPointIndex = 0; const int StartX = CurrentX; const int StartY = CurrentY; const int StartDirection = CurrentDirection; static const int DirectionDx[] = { 1, 0, -1, 0 }; static const int DirectionDy[] = { 0, 1, 0, -1 }; bool bFinished = false; while (!bFinished) { const FIntPoint& NextPoint = Points[(CurrentPointIndex + 1) % PointCount]; const int NextDx = (int)NextPoint.X - CurrentX; const int NextDy = (int)NextPoint.Y - CurrentY; int LeftDirection = (CurrentDirection + 3) % 4; int CurrentDx = DirectionDx[CurrentDirection]; int CurrentDy = DirectionDy[CurrentDirection]; int LeftDx = DirectionDx[LeftDirection]; int LeftDy = DirectionDy[LeftDirection]; bool bDidMove = true; if (NextDx != 0 || NextDy != 0) { if (NextDx == LeftDx && NextDy == LeftDy) { // Space to the left, turn left and move forwards CurrentDirection = LeftDirection; CurrentX += LeftDx; CurrentY += LeftDy; } else { // Wall to the left. Add the corner vertex to our output. Result.Add(FIntPoint((int)((float)CurrentX + 0.5f + (float)(CurrentDx + LeftDx) * 0.5f), (int)((float)CurrentY + 0.5f + (float)(CurrentDy + LeftDy) * 0.5f))); if (NextDx == CurrentDx && NextDy == CurrentDy) { // Move forward CurrentX += CurrentDx; CurrentY += CurrentDy; } else if (NextDx == CurrentDx + LeftDx && NextDy == CurrentDy + LeftDy) { // Move forward, turn left, move forwards again CurrentX += CurrentDx; CurrentY += CurrentDy; CurrentDirection = LeftDirection; CurrentX += LeftDx; CurrentY += LeftDy; } else { // Turn right CurrentDirection = (CurrentDirection + 1) % 4; bDidMove = false; } } } if (bDidMove) { ++CurrentPointIndex; } if (CurrentX == StartX && CurrentY == StartY && CurrentDirection == StartDirection) { bFinished = true; } } } void UPaperSprite::FindContours(const FIntPoint& ScanPos, const FIntPoint& ScanSize, float AlphaThreshold, float Detail, UTexture2D* Texture, TArray< TArray<FIntPoint> >& OutPoints) { OutPoints.Empty(); if ((ScanSize.X <= 0) || (ScanSize.Y <= 0)) { return; } // Neighborhood array (clockwise starting at -X,-Y; assuming prev is at -X) const int32 NeighborX[] = {-1, 0,+1,+1,+1, 0,-1,-1}; const int32 NeighborY[] = {-1,-1,-1, 0,+1,+1,+1, 0}; // 0 1 2 3 4 5 6 7 // 0 1 2 // 7 3 // 6 5 4 const int32 StateMutation[] = { 5, //from0 6, //from1 7, //from2 0, //from3 1, //from4 2, //from5 3, //from6 4, //from7 }; int32 AlphaThresholdInt = FMath::Clamp<int32>(AlphaThreshold * 255, 0, 255); FBitmap FullSizeBitmap(Texture, AlphaThresholdInt); if (FullSizeBitmap.IsValid()) { const int32 DownsampleAmount = GetDivisorFromDetail(ScanSize, Detail); FBitmap SourceBitmap((ScanSize.X + DownsampleAmount - 1) / DownsampleAmount, (ScanSize.Y + DownsampleAmount - 1) / DownsampleAmount, 0); for (int32 Y = 0; Y < ScanSize.Y; ++Y) { for (int32 X = 0; X < ScanSize.X; ++X) { SourceBitmap.SetPixel(X / DownsampleAmount, Y / DownsampleAmount, SourceBitmap.GetPixel(X / DownsampleAmount, Y / DownsampleAmount) | FullSizeBitmap.GetPixel(ScanPos.X + X, ScanPos.Y + Y)); } } const int32 LeftBound = 0; const int32 RightBound = SourceBitmap.Width - 1; const int32 TopBound = 0; const int32 BottomBound = SourceBitmap.Height - 1; //checkSlow((LeftBound >= 0) && (TopBound >= 0) && (RightBound < SourceBitmap.Width) && (BottomBound < SourceBitmap.Height)); // Create the 'output' boundary image FBoundaryImage BoundaryImage(FIntPoint(0, 0), FIntPoint(SourceBitmap.Width, SourceBitmap.Height)); bool bInsideBoundary = false; for (int32 Y = TopBound - 1; Y < BottomBound + 2; ++Y) { for (int32 X = LeftBound - 1; X < RightBound + 2; ++X) { const bool bAlreadyTaggedAsBoundary = BoundaryImage.GetPixel(X, Y) > 0; const bool bPixelInsideBounds = (X >= LeftBound && X <= RightBound && Y >= TopBound && Y <= BottomBound); const bool bIsFilledPixel = bPixelInsideBounds && SourceBitmap.GetPixel(X, Y) != 0; if (bInsideBoundary) { if (!bIsFilledPixel) { // We're leaving the known boundary bInsideBoundary = false; } } else { if (bAlreadyTaggedAsBoundary) { // We're re-entering a known boundary bInsideBoundary = true; } else if (bIsFilledPixel) { // Create the output chain we'll build from the boundary image //TArray<FIntPoint>& Contour = *new (OutPoints) TArray<FIntPoint>(); TArray<FIntPoint> Contour; // Moving into an undiscovered boundary BoundaryImage.SetPixel(X, Y, 1); new (Contour) FIntPoint(X, Y); // Current pixel int32 NeighborPhase = 0; int32 PX = X; int32 PY = Y; int32 EnteredStartingSquareCount = 0; int32 SinglePixelCounter = 0; for (;;) { // Test pixel (clockwise from the current pixel) const int32 CX = PX + NeighborX[NeighborPhase]; const int32 CY = PY + NeighborY[NeighborPhase]; const bool bTestPixelInsideBounds = (CX >= LeftBound && CX <= RightBound && CY >= TopBound && CY <= BottomBound); const bool bTestPixelPasses = bTestPixelInsideBounds && SourceBitmap.GetPixel(CX, CY) != 0; //UE_LOG(LogPaper2D, Log, TEXT("Outer P(%d,%d), C(%d,%d) Ph%d %s"), // PX, PY, CX, CY, NeighborPhase, bTestPixelPasses ? TEXT("[BORDER]") : TEXT("[]")); if (bTestPixelPasses) { // Move to the next pixel // Check to see if we closed the loop if ((CX == X) && (CY == Y)) { // // If we went thru the boundary pixel more than two times, or // // entered it from the same way we started, then we're done // ++EnteredStartingSquareCount; // if ((EnteredStartingSquareCount > 2) || (NeighborPhase == 0)) // { //@TODO: Not good enough, will early out too soon some of the time! bInsideBoundary = true; break; } // } BoundaryImage.SetPixel(CX, CY, NeighborPhase+1); new (Contour) FIntPoint(CX, CY); PX = CX; PY = CY; NeighborPhase = StateMutation[NeighborPhase]; SinglePixelCounter = 0; //NeighborPhase = (NeighborPhase + 1) % 8; } else { NeighborPhase = (NeighborPhase + 1) % 8; ++SinglePixelCounter; if (SinglePixelCounter > 8) { // Went all the way around the neighborhood; it's an island of a single pixel break; } } } // Trace the contour shape creating polygon edges TArray<FIntPoint>& ContourPoly = *new (OutPoints)TArray<FIntPoint>(); TraceContour(/*out*/ContourPoly, Contour); // Remove collinear points from the result RemoveCollinearPoints(/*inout*/ ContourPoly); if (!PaperGeomTools::IsPolygonWindingCCW(ContourPoly)) { // Remove newly added polygon, we don't support holes just yet OutPoints.RemoveAt(OutPoints.Num() - 1); } else { for (int ContourPolyIndex = 0; ContourPolyIndex < ContourPoly.Num(); ++ContourPolyIndex) { // Rescale and recenter contour poly FIntPoint RescaledPoint = ScanPos + ContourPoly[ContourPolyIndex] * DownsampleAmount; // Make sure rescaled point doesn't exceed the original max bounds RescaledPoint.X = FMath::Min(RescaledPoint.X, ScanPos.X + ScanSize.X); RescaledPoint.Y = FMath::Min(RescaledPoint.Y, ScanPos.Y + ScanSize.Y); ContourPoly[ContourPolyIndex] = RescaledPoint; } } } } } } } } void UPaperSprite::CreatePolygonFromBoundingBox(FSpriteGeometryCollection& GeomOwner, bool bUseTightBounds) { FVector2D BoxSize; FVector2D BoxPosition; if (bUseTightBounds) { FindTextureBoundingBox(GeomOwner.AlphaThreshold, /*out*/ BoxPosition, /*out*/ BoxSize); } else { BoxSize = SourceDimension; BoxPosition = SourceUV; } // Recenter the box BoxPosition += BoxSize * 0.5f; // Put the bounding box into the geometry array GeomOwner.Shapes.Empty(); GeomOwner.AddRectangleShape(BoxPosition, BoxSize); } void UPaperSprite::ExtractRectsFromTexture(UTexture2D* Texture, TArray<FIntRect>& OutRects) { FBitmap SpriteTextureBitmap(Texture, 0, 0); SpriteTextureBitmap.ExtractRects(/*out*/ OutRects); } void UPaperSprite::InitializeSprite(const FSpriteAssetInitParameters& InitParams) { if (InitParams.bOverridePixelsPerUnrealUnit) { PixelsPerUnrealUnit = InitParams.PixelsPerUnrealUnit; } if (InitParams.DefaultMaterialOverride != nullptr) { DefaultMaterial = InitParams.DefaultMaterialOverride; } if (InitParams.AlternateMaterialOverride != nullptr) { AlternateMaterial = InitParams.AlternateMaterialOverride; } SourceTexture = InitParams.Texture; if (SourceTexture != nullptr) { SourceTextureDimension.Set(SourceTexture->GetImportedSize().X, SourceTexture->GetImportedSize().Y); } else { SourceTextureDimension.Set(0, 0); } AdditionalSourceTextures = InitParams.AdditionalTextures; SourceUV = InitParams.Offset; SourceDimension = InitParams.Dimension; RebuildCollisionData(); RebuildRenderData(); } void UPaperSprite::SetTrim(bool bTrimmed, const FVector2D& OriginInSourceImage, const FVector2D& SourceImageDimension) { this->bTrimmedInSourceImage = bTrimmed; this->OriginInSourceImageBeforeTrimming = OriginInSourceImage; this->SourceImageDimensionBeforeTrimming = SourceImageDimension; RebuildRenderData(); RebuildCollisionData(); } void UPaperSprite::SetRotated(bool bRotated) { this->bRotatedInSourceImage = bRotated; RebuildRenderData(); RebuildCollisionData(); } void UPaperSprite::SetPivotMode(ESpritePivotMode::Type InPivotMode, FVector2D InCustomTextureSpacePivot) { PivotMode = InPivotMode; CustomPivotPoint = InCustomTextureSpacePivot; RebuildRenderData(); RebuildCollisionData(); } FVector2D UPaperSprite::ConvertTextureSpaceToPivotSpace(FVector2D Input) const { const FVector2D Pivot = GetPivotPosition(); const float X = Input.X - Pivot.X; const float Y = -Input.Y + Pivot.Y; return bRotatedInSourceImage ? FVector2D(-Y, X) : FVector2D(X, Y); } FVector2D UPaperSprite::ConvertPivotSpaceToTextureSpace(FVector2D Input) const { const FVector2D Pivot = GetPivotPosition(); if (bRotatedInSourceImage) { Swap(Input.X, Input.Y); Input.Y = -Input.Y; } const float X = Input.X + Pivot.X; const float Y = -Input.Y + Pivot.Y; return FVector2D(X, Y); } FVector UPaperSprite::ConvertTextureSpaceToPivotSpace(FVector Input) const { const FVector2D Pivot = GetPivotPosition(); const float X = Input.X - Pivot.X; const float Z = -Input.Z + Pivot.Y; return FVector(X, Input.Y, Z); } FVector UPaperSprite::ConvertPivotSpaceToTextureSpace(FVector Input) const { const FVector2D Pivot = GetPivotPosition(); const float X = Input.X + Pivot.X; const float Z = -Input.Z + Pivot.Y; return FVector(X, Input.Y, Z); } FVector UPaperSprite::ConvertTextureSpaceToWorldSpace(const FVector2D& SourcePoint) const { const float UnitsPerPixel = GetUnrealUnitsPerPixel(); const FVector2D SourcePointInUU = ConvertTextureSpaceToPivotSpace(SourcePoint) * UnitsPerPixel; return (PaperAxisX * SourcePointInUU.X) + (PaperAxisY * SourcePointInUU.Y); } FVector2D UPaperSprite::ConvertWorldSpaceToTextureSpace(const FVector& WorldPoint) const { const FVector ProjectionX = WorldPoint.ProjectOnTo(PaperAxisX); const FVector ProjectionY = WorldPoint.ProjectOnTo(PaperAxisY); const float XValue = FMath::Sign(ProjectionX | PaperAxisX) * ProjectionX.Size() * PixelsPerUnrealUnit; const float YValue = FMath::Sign(ProjectionY | PaperAxisY) * ProjectionY.Size() * PixelsPerUnrealUnit; return ConvertPivotSpaceToTextureSpace(FVector2D(XValue, YValue)); } FVector2D UPaperSprite::ConvertWorldSpaceDeltaToTextureSpace(const FVector& WorldSpaceDelta, bool bIgnoreRotation) const { const FVector ProjectionX = WorldSpaceDelta.ProjectOnTo(PaperAxisX); const FVector ProjectionY = WorldSpaceDelta.ProjectOnTo(PaperAxisY); float XValue = FMath::Sign(ProjectionX | PaperAxisX) * ProjectionX.Size() * PixelsPerUnrealUnit; float YValue = FMath::Sign(ProjectionY | PaperAxisY) * ProjectionY.Size() * PixelsPerUnrealUnit; // Undo pivot space rotation, ignoring pivot position if (bRotatedInSourceImage && !bIgnoreRotation) { Swap(XValue, YValue); XValue = -XValue; } return FVector2D(XValue, YValue); } FTransform UPaperSprite::GetPivotToWorld() const { const FVector Translation(0, 0, 0); const FVector Scale3D(GetUnrealUnitsPerPixel()); return FTransform(FRotator::ZeroRotator, Translation, Scale3D); } FVector2D UPaperSprite::GetRawPivotPosition() const { FVector2D TopLeftUV = SourceUV; FVector2D Dimension = SourceDimension; if (bTrimmedInSourceImage) { TopLeftUV = SourceUV - OriginInSourceImageBeforeTrimming; Dimension = SourceImageDimensionBeforeTrimming; } if (bRotatedInSourceImage) { switch (PivotMode) { case ESpritePivotMode::Top_Left: return FVector2D(TopLeftUV.X + Dimension.X, TopLeftUV.Y); case ESpritePivotMode::Top_Center: return FVector2D(TopLeftUV.X + Dimension.X, TopLeftUV.Y + Dimension.Y * 0.5f); case ESpritePivotMode::Top_Right: return FVector2D(TopLeftUV.X + Dimension.X, TopLeftUV.Y + Dimension.Y); case ESpritePivotMode::Center_Left: return FVector2D(TopLeftUV.X + Dimension.X * 0.5f, TopLeftUV.Y); case ESpritePivotMode::Center_Center: return FVector2D(TopLeftUV.X + Dimension.X * 0.5f, TopLeftUV.Y + Dimension.Y * 0.5f); case ESpritePivotMode::Center_Right: return FVector2D(TopLeftUV.X + Dimension.X * 0.5f, TopLeftUV.Y + Dimension.Y); case ESpritePivotMode::Bottom_Left: return TopLeftUV; case ESpritePivotMode::Bottom_Center: return FVector2D(TopLeftUV.X, TopLeftUV.Y + Dimension.Y * 0.5f); case ESpritePivotMode::Bottom_Right: return FVector2D(TopLeftUV.X, TopLeftUV.Y + Dimension.Y); default: case ESpritePivotMode::Custom: return CustomPivotPoint; break; }; } else { switch (PivotMode) { case ESpritePivotMode::Top_Left: return TopLeftUV; case ESpritePivotMode::Top_Center: return FVector2D(TopLeftUV.X + Dimension.X * 0.5f, TopLeftUV.Y); case ESpritePivotMode::Top_Right: return FVector2D(TopLeftUV.X + Dimension.X, TopLeftUV.Y); case ESpritePivotMode::Center_Left: return FVector2D(TopLeftUV.X, TopLeftUV.Y + Dimension.Y * 0.5f); case ESpritePivotMode::Center_Center: return FVector2D(TopLeftUV.X + Dimension.X * 0.5f, TopLeftUV.Y + Dimension.Y * 0.5f); case ESpritePivotMode::Center_Right: return FVector2D(TopLeftUV.X + Dimension.X, TopLeftUV.Y + Dimension.Y * 0.5f); case ESpritePivotMode::Bottom_Left: return FVector2D(TopLeftUV.X, TopLeftUV.Y + Dimension.Y); case ESpritePivotMode::Bottom_Center: return FVector2D(TopLeftUV.X + Dimension.X * 0.5f, TopLeftUV.Y + Dimension.Y); case ESpritePivotMode::Bottom_Right: return TopLeftUV + Dimension; default: case ESpritePivotMode::Custom: return CustomPivotPoint; break; }; } } FVector2D UPaperSprite::GetPivotPosition() const { FVector2D RawPivot = GetRawPivotPosition(); if (bSnapPivotToPixelGrid) { RawPivot.X = FMath::RoundToFloat(RawPivot.X); RawPivot.Y = FMath::RoundToFloat(RawPivot.Y); } return RawPivot; } void UPaperSprite::GetAssetRegistryTags(TArray<FAssetRegistryTag>& OutTags) const { Super::GetAssetRegistryTags(OutTags); if (AtlasGroup != nullptr) { OutTags.Add(FAssetRegistryTag(TEXT("AtlasGroupGUID"), AtlasGroup->AtlasGUID.ToString(EGuidFormats::Digits), FAssetRegistryTag::TT_Hidden)); } } #endif bool UPaperSprite::GetPhysicsTriMeshData(FTriMeshCollisionData* OutCollisionData, bool InUseAllTriData) { //@TODO: Probably want to support this return false; } bool UPaperSprite::ContainsPhysicsTriMeshData(bool InUseAllTriData) const { //@TODO: Probably want to support this return false; } FBoxSphereBounds UPaperSprite::GetRenderBounds() const { FBox BoundingBox(ForceInit); for (int32 VertexIndex = 0; VertexIndex < BakedRenderData.Num(); ++VertexIndex) { const FVector4& VertXYUV = BakedRenderData[VertexIndex]; const FVector Vert((PaperAxisX * VertXYUV.X) + (PaperAxisY * VertXYUV.Y)); BoundingBox += Vert; } // Make the whole thing a single unit 'deep' const FVector HalfThicknessVector = 0.5f * PaperAxisZ; BoundingBox += -HalfThicknessVector; BoundingBox += HalfThicknessVector; return FBoxSphereBounds(BoundingBox); } FPaperSpriteSocket* UPaperSprite::FindSocket(FName SocketName) { for (int32 SocketIndex = 0; SocketIndex < Sockets.Num(); ++SocketIndex) { FPaperSpriteSocket& Socket = Sockets[SocketIndex]; if (Socket.SocketName == SocketName) { return &Socket; } } return nullptr; } void UPaperSprite::QuerySupportedSockets(TArray<FComponentSocketDescription>& OutSockets) const { for (int32 SocketIndex = 0; SocketIndex < Sockets.Num(); ++SocketIndex) { const FPaperSpriteSocket& Socket = Sockets[SocketIndex]; new (OutSockets) FComponentSocketDescription(Socket.SocketName, EComponentSocketType::Socket); } } #if WITH_EDITOR void UPaperSprite::ValidateSocketNames() { TSet<FName> SocketNames; struct Local { static FName GetUniqueName(const TSet<FName>& InSocketNames, FName Name) { int Counter = Name.GetNumber(); FName TestName; do { TestName = Name; TestName.SetNumber(++Counter); } while (InSocketNames.Contains(TestName)); return TestName; } }; bool bHasChanged = false; for (int32 SocketIndex = 0; SocketIndex < Sockets.Num(); ++SocketIndex) { FPaperSpriteSocket& Socket = Sockets[SocketIndex]; if (Socket.SocketName.IsNone()) { Socket.SocketName = Local::GetUniqueName(SocketNames, FName(TEXT("Socket"))); bHasChanged = true; } else if (SocketNames.Contains(Socket.SocketName)) { Socket.SocketName = Local::GetUniqueName(SocketNames, Socket.SocketName); bHasChanged = true; } // Add the corrected name SocketNames.Add(Socket.SocketName); } if (bHasChanged) { PostEditChange(); } } #endif #if WITH_EDITOR void UPaperSprite::RemoveSocket(FName SocketNameToDelete) { Sockets.RemoveAll([=](const FPaperSpriteSocket& Socket){ return Socket.SocketName == SocketNameToDelete; }); } #endif void UPaperSprite::Serialize(FArchive& Ar) { Super::Serialize(Ar); Ar.UsingCustomVersion(FPaperCustomVersion::GUID); } void UPaperSprite::PostLoad() { Super::PostLoad(); const int32 PaperVer = GetLinkerCustomVersion(FPaperCustomVersion::GUID); #if !WITH_EDITORONLY_DATA if (PaperVer < FPaperCustomVersion::LatestVersion) { UE_LOG(LogPaper2D, Warning, TEXT("Stale UPaperSprite asset '%s' with version %d detected in a cooked build (latest version is %d). Please perform a full recook."), *GetPathName(), PaperVer, (int32)FPaperCustomVersion::LatestVersion); } #else if (UTexture2D* EffectiveTexture = GetBakedTexture()) { EffectiveTexture->ConditionalPostLoad(); } bool bRebuildCollision = false; bool bRebuildRenderData = false; if (PaperVer < FPaperCustomVersion::AddTransactionalToClasses) { SetFlags(RF_Transactional); } if (PaperVer < FPaperCustomVersion::RefactorPolygonStorageToSupportShapes) { UpdateGeometryToBeBoxPositionRelative(CollisionGeometry); UpdateGeometryToBeBoxPositionRelative(RenderGeometry); } if (PaperVer < FPaperCustomVersion::AddPivotSnapToPixelGrid) { bSnapPivotToPixelGrid = false; } if (PaperVer < FPaperCustomVersion::FixTangentGenerationForFrontFace) { bRebuildRenderData = true; } if (PaperVer < FPaperCustomVersion::AddPixelsPerUnrealUnit) { PixelsPerUnrealUnit = 1.0f; bRebuildCollision = true; bRebuildRenderData = true; } else if (PaperVer < FPaperCustomVersion::FixIncorrectCollisionOnSourceRotatedSprites) { bRebuildCollision = true; } if ((PaperVer < FPaperCustomVersion::AddDefaultCollisionProfileInSpriteAsset) && (BodySetup != nullptr)) { BodySetup->DefaultInstance.SetCollisionProfileName(UCollisionProfile::BlockAllDynamic_ProfileName); } if ((PaperVer >= FPaperCustomVersion::AddSourceTextureSize) && NeedRescaleSpriteData()) { RescaleSpriteData(GetSourceTexture()); bRebuildCollision = true; bRebuildRenderData = true; } if (bRebuildCollision) { RebuildCollisionData(); } if (bRebuildRenderData) { RebuildRenderData(); } #endif } UTexture2D* UPaperSprite::GetBakedTexture() const { return (BakedSourceTexture != nullptr) ? BakedSourceTexture : SourceTexture; } void UPaperSprite::GetBakedAdditionalSourceTextures(FAdditionalSpriteTextureArray& OutTextureList) const { OutTextureList = AdditionalSourceTextures; } UMaterialInterface* UPaperSprite::GetMaterial(int32 MaterialIndex) const { if (MaterialIndex == 0) { return GetDefaultMaterial(); } else if (MaterialIndex == 1) { return GetAlternateMaterial(); } else { return nullptr; } } int32 UPaperSprite::GetNumMaterials() const { return (AlternateMaterialSplitIndex != INDEX_NONE) ? 2 : 1; } ////////////////////////////////////////////////////////////////////////// // FSpriteGeometryCollection void FSpriteGeometryCollection::AddRectangleShape(FVector2D Position, FVector2D Size) { const FVector2D HalfSize = Size * 0.5f; FSpriteGeometryShape& NewShape = *new (Shapes) FSpriteGeometryShape(); new (NewShape.Vertices) FVector2D(-HalfSize.X, -HalfSize.Y); new (NewShape.Vertices) FVector2D(+HalfSize.X, -HalfSize.Y); new (NewShape.Vertices) FVector2D(+HalfSize.X, +HalfSize.Y); new (NewShape.Vertices) FVector2D(-HalfSize.X, +HalfSize.Y); NewShape.ShapeType = ESpriteShapeType::Box; NewShape.BoxSize = Size; NewShape.BoxPosition = Position; } void FSpriteGeometryCollection::AddCircleShape(FVector2D Position, FVector2D Size) { FSpriteGeometryShape& NewShape = *new (Shapes) FSpriteGeometryShape(); NewShape.ShapeType = ESpriteShapeType::Circle; NewShape.BoxSize = Size; NewShape.BoxPosition = Position; } void FSpriteGeometryCollection::Reset() { Shapes.Empty(); GeometryType = ESpritePolygonMode::TightBoundingBox; } void FSpriteGeometryCollection::Triangulate(TArray<FVector2D>& Target, bool bIncludeBoxes) const { Target.Empty(); TArray<FVector2D> AllGeneratedTriangles; // AOS -> Validate -> SOA TArray<bool> PolygonsNegativeWinding; // do these polygons have negative winding? TArray<TArray<FVector2D> > ValidPolygonTriangles; PolygonsNegativeWinding.Empty(Shapes.Num()); ValidPolygonTriangles.Empty(Shapes.Num()); bool bSourcePolygonHasHoles = false; // Correct polygon winding for additive and subtractive polygons // Invalid polygons (< 3 verts) removed from this list for (int32 PolygonIndex = 0; PolygonIndex < Shapes.Num(); ++PolygonIndex) { const FSpriteGeometryShape& SourcePolygon = Shapes[PolygonIndex]; if ((SourcePolygon.ShapeType == ESpriteShapeType::Polygon) || (bIncludeBoxes && (SourcePolygon.ShapeType == ESpriteShapeType::Box))) { if (SourcePolygon.Vertices.Num() >= 3) { TArray<FVector2D> TextureSpaceVertices; SourcePolygon.GetTextureSpaceVertices(/*out*/ TextureSpaceVertices); TArray<FVector2D>& FixedVertices = *new (ValidPolygonTriangles) TArray<FVector2D>(); PaperGeomTools::CorrectPolygonWinding(/*out*/ FixedVertices, TextureSpaceVertices, SourcePolygon.bNegativeWinding); PolygonsNegativeWinding.Add(SourcePolygon.bNegativeWinding); } if (SourcePolygon.bNegativeWinding) { bSourcePolygonHasHoles = true; } } } // Check if polygons overlap, or have inconsistent winding, or edges overlap if (!PaperGeomTools::ArePolygonsValid(ValidPolygonTriangles)) { return; } // Merge each additive and associated subtractive polygons to form a list of polygons in CCW winding ValidPolygonTriangles = PaperGeomTools::ReducePolygons(ValidPolygonTriangles, PolygonsNegativeWinding); // Triangulate the polygons for (int32 PolygonIndex = 0; PolygonIndex < ValidPolygonTriangles.Num(); ++PolygonIndex) { TArray<FVector2D> Generated2DTriangles; if (PaperGeomTools::TriangulatePoly(Generated2DTriangles, ValidPolygonTriangles[PolygonIndex], bAvoidVertexMerging)) { AllGeneratedTriangles.Append(Generated2DTriangles); } } // This doesn't work when polys have holes as edges will likely form a loop around the poly if (!bSourcePolygonHasHoles && !bAvoidVertexMerging && ((ValidPolygonTriangles.Num() > 1) && (AllGeneratedTriangles.Num() > 1))) { TArray<FVector2D> TrianglesCopy = AllGeneratedTriangles; AllGeneratedTriangles.Empty(); PaperGeomTools::RemoveRedundantTriangles(/*out*/ AllGeneratedTriangles, TrianglesCopy); } Target.Append(AllGeneratedTriangles); } bool AreVectorsParallel(const FVector2D& Vector1, const FVector2D& Vector2, float Threshold = KINDA_SMALL_NUMBER) { const float DotProduct = FVector2D::DotProduct(Vector1, Vector2); const float LengthProduct = Vector1.Size() * Vector2.Size(); return FMath::IsNearlyEqual(FMath::Abs(DotProduct / LengthProduct), 1.0f, Threshold); } bool AreVectorsPerpendicular(const FVector2D& Vector1, const FVector2D& Vector2, float Threshold = KINDA_SMALL_NUMBER) { const float DotProduct = FVector2D::DotProduct(Vector1, Vector2); return FMath::IsNearlyEqual(DotProduct, 0.0f, Threshold); } bool FSpriteGeometryCollection::ConditionGeometry() { bool bModifiedGeometry = false; for (FSpriteGeometryShape& Shape : Shapes) { if ((Shape.ShapeType == ESpriteShapeType::Polygon) && (Shape.Vertices.Num() == 4)) { const FVector2D& A = Shape.Vertices[0]; const FVector2D& B = Shape.Vertices[1]; const FVector2D& C = Shape.Vertices[2]; const FVector2D& D = Shape.Vertices[3]; const FVector2D AB = B - A; const FVector2D BC = C - B; const FVector2D CD = D - C; const FVector2D DA = A - D; if (AreVectorsPerpendicular(AB, BC) && AreVectorsPerpendicular(CD, DA) && AreVectorsParallel(AB, CD) && AreVectorsParallel(BC, DA)) { // Checking in local space, so we still want the rotation to be 0 here const bool bMeetsRotationConstraint = FMath::IsNearlyEqual(AB.Y, 0.0f); if (bMeetsRotationConstraint) { const FVector2D NewPivotTextureSpace = Shape.GetPolygonCentroid(); Shape.SetNewPivot(NewPivotTextureSpace); Shape.BoxSize = FVector2D(AB.Size(), DA.Size()); Shape.ShapeType = ESpriteShapeType::Box; bModifiedGeometry = true; } } } } return bModifiedGeometry; } ////////////////////////////////////////////////////////////////////////// // FSpriteGeometryCollisionBuilderBase FSpriteGeometryCollisionBuilderBase::FSpriteGeometryCollisionBuilderBase(UBodySetup* InBodySetup) : MyBodySetup(InBodySetup) , UnrealUnitsPerPixel(1.0f) , CollisionThickness(64.0f) , ZOffsetAmount(0.0f) , CollisionDomain(ESpriteCollisionMode::Use3DPhysics) { check(MyBodySetup); } void FSpriteGeometryCollisionBuilderBase::ProcessGeometry(const FSpriteGeometryCollection& InGeometry) { // Add geometry to the body setup AddBoxCollisionShapesToBodySetup(InGeometry); AddPolygonCollisionShapesToBodySetup(InGeometry); AddCircleCollisionShapesToBodySetup(InGeometry); } void FSpriteGeometryCollisionBuilderBase::Finalize() { // Rebuild the body setup #if WITH_RUNTIME_PHYSICS_COOKING || WITH_EDITOR MyBodySetup->InvalidatePhysicsData(); #endif MyBodySetup->CreatePhysicsMeshes(); } void FSpriteGeometryCollisionBuilderBase::AddBoxCollisionShapesToBodySetup(const FSpriteGeometryCollection& InGeometry) { // Bake all of the boxes to the body setup for (const FSpriteGeometryShape& Shape : InGeometry.Shapes) { if (Shape.ShapeType == ESpriteShapeType::Box) { // Determine the box size and center in pivot space const FVector2D& BoxSizeInTextureSpace = Shape.BoxSize; const FVector2D CenterInTextureSpace = Shape.BoxPosition; const FVector2D CenterInPivotSpace = ConvertTextureSpaceToPivotSpace(CenterInTextureSpace); // Convert from pixels to uu const FVector2D BoxSizeInPivotSpace = ConvertTextureSpaceToPivotSpaceNoTranslation(BoxSizeInTextureSpace); const FVector2D BoxSize2D = BoxSizeInPivotSpace * UnrealUnitsPerPixel; const FVector2D CenterInScaledSpace = CenterInPivotSpace * UnrealUnitsPerPixel; // Create a new box primitive switch (CollisionDomain) { case ESpriteCollisionMode::Use3DPhysics: { const FVector BoxPos3D = (PaperAxisX * CenterInScaledSpace.X) + (PaperAxisY * CenterInScaledSpace.Y) + (PaperAxisZ * ZOffsetAmount); const FVector BoxSize3D = (PaperAxisX * BoxSize2D.X) + (PaperAxisY * BoxSize2D.Y) + (PaperAxisZ * CollisionThickness); // Create a new box primitive FKBoxElem& Box = *new (MyBodySetup->AggGeom.BoxElems) FKBoxElem(FMath::Abs(BoxSize3D.X), FMath::Abs(BoxSize3D.Y), FMath::Abs(BoxSize3D.Z)); Box.Center = BoxPos3D; Box.Orientation = FQuat(FRotator(Shape.Rotation, 0.0f, 0.0f)); } break; case ESpriteCollisionMode::Use2DPhysics: { UBodySetup2D* BodySetup2D = CastChecked<UBodySetup2D>(MyBodySetup); // Create a new box primitive FBoxElement2D& Box = *new (BodySetup2D->AggGeom2D.BoxElements) FBoxElement2D(); Box.Width = FMath::Abs(BoxSize2D.X); Box.Height = FMath::Abs(BoxSize2D.Y); Box.Center.X = CenterInScaledSpace.X; Box.Center.Y = CenterInScaledSpace.Y; Box.Angle = Shape.Rotation; } break; default: check(false); break; } } } } void FSpriteGeometryCollisionBuilderBase::AddPolygonCollisionShapesToBodySetup(const FSpriteGeometryCollection& InGeometry) { // Rebuild the runtime geometry for polygons TArray<FVector2D> CollisionData; InGeometry.Triangulate(/*out*/ CollisionData, /*bIncludeBoxes=*/ false); // Adjust the collision data to be relative to the pivot and scaled from pixels to uu for (FVector2D& Point : CollisionData) { Point = ConvertTextureSpaceToPivotSpace(Point) * UnrealUnitsPerPixel; } //@TODO: Use this guy instead: DecomposeMeshToHulls //@TODO: Merge triangles that are convex together! // Bake it to the runtime structure switch (CollisionDomain) { case ESpriteCollisionMode::Use3DPhysics: { UBodySetup* BodySetup3D = MyBodySetup; const FVector HalfThicknessVector = PaperAxisZ * 0.5f * CollisionThickness; int32 RunningIndex = 0; for (int32 TriIndex = 0; TriIndex < CollisionData.Num() / 3; ++TriIndex) { FKConvexElem& ConvexTri = *new (BodySetup3D->AggGeom.ConvexElems) FKConvexElem(); ConvexTri.VertexData.Empty(6); for (int32 Index = 0; Index < 3; ++Index) { const FVector2D& Pos2D = CollisionData[RunningIndex++]; const FVector Pos3D = (PaperAxisX * Pos2D.X) + (PaperAxisY * Pos2D.Y) + (PaperAxisZ * ZOffsetAmount); new (ConvexTri.VertexData) FVector(Pos3D - HalfThicknessVector); new (ConvexTri.VertexData) FVector(Pos3D + HalfThicknessVector); } ConvexTri.UpdateElemBox(); } } break; case ESpriteCollisionMode::Use2DPhysics: { UBodySetup2D* BodySetup2D = CastChecked<UBodySetup2D>(MyBodySetup); int32 RunningIndex = 0; for (int32 TriIndex = 0; TriIndex < CollisionData.Num() / 3; ++TriIndex) { FConvexElement2D& ConvexTri = *new (BodySetup2D->AggGeom2D.ConvexElements) FConvexElement2D(); ConvexTri.VertexData.Empty(3); for (int32 Index = 0; Index < 3; ++Index) { const FVector2D& Pos2D = CollisionData[RunningIndex++]; new (ConvexTri.VertexData) FVector2D(Pos2D); } } } break; default: check(false); break; } } void FSpriteGeometryCollisionBuilderBase::AddCircleCollisionShapesToBodySetup(const FSpriteGeometryCollection& InGeometry) { // Bake all of the boxes to the body setup for (const FSpriteGeometryShape& Shape : InGeometry.Shapes) { if (Shape.ShapeType == ESpriteShapeType::Circle) { // Determine the box size and center in pivot space const FVector2D& CircleSizeInTextureSpace = Shape.BoxSize; const FVector2D& CenterInTextureSpace = Shape.BoxPosition; const FVector2D CenterInPivotSpace = ConvertTextureSpaceToPivotSpace(CenterInTextureSpace); // Convert from pixels to uu const FVector2D CircleSizeInPivotSpace = ConvertTextureSpaceToPivotSpaceNoTranslation(CircleSizeInTextureSpace); const FVector2D CircleSize2D = CircleSizeInPivotSpace * UnrealUnitsPerPixel; const FVector2D CenterInScaledSpace = CenterInPivotSpace * UnrealUnitsPerPixel; //@TODO: Neither Box2D nor PhysX support ellipses, currently forcing to be circular, but should we instead convert to an n-gon? const float AverageDiameter = (FMath::Abs(CircleSize2D.X) + FMath::Abs(CircleSize2D.Y)) * 0.5f; const float AverageRadius = AverageDiameter * 0.5f; // Create a new circle/sphere primitive switch (CollisionDomain) { case ESpriteCollisionMode::Use3DPhysics: { // Create a new box primitive FKSphereElem& Sphere = *new (MyBodySetup->AggGeom.SphereElems) FKSphereElem(AverageRadius); Sphere.Center = (PaperAxisX * CenterInScaledSpace.X) + (PaperAxisY * CenterInScaledSpace.Y) + (PaperAxisZ * ZOffsetAmount); } break; case ESpriteCollisionMode::Use2DPhysics: { // Create a new box primitive UBodySetup2D* BodySetup2D = CastChecked<UBodySetup2D>(MyBodySetup); FCircleElement2D& Circle = *new (BodySetup2D->AggGeom2D.CircleElements) FCircleElement2D(); Circle.Radius = AverageRadius; Circle.Center.X = CenterInScaledSpace.X; Circle.Center.Y = CenterInScaledSpace.Y; } break; default: check(false); break; } } } } FVector2D FSpriteGeometryCollisionBuilderBase::ConvertTextureSpaceToPivotSpace(const FVector2D& Input) const { return Input; } FVector2D FSpriteGeometryCollisionBuilderBase::ConvertTextureSpaceToPivotSpaceNoTranslation(const FVector2D& Input) const { return Input; }
30.715832
236
0.724775
[ "geometry", "render", "object", "shape", "vector" ]
6d82e5f541ff8720fbf6a10c178e453b7482feda
1,149
cpp
C++
910.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
910.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
910.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #define fi first #define se second #define pb push_back #define mp make_pair #define pi acos(-1.0) #define eps 1e-9 using namespace std; int dp[30][40]; pair<int,int> jalur[30]; char posisi[2],kiri[2],kanan[2],status[2]; bool special[30]; int n,m,x,y,z; int jalan(int pos, int langkah) { if(dp[pos][langkah]==-1) { if((langkah==m)&&(special[pos])) dp[pos][langkah]=1; else { dp[pos][langkah]=0; if (langkah<m) dp[pos][langkah]+=jalan(jalur[pos].fi,langkah+1)+jalan(jalur[pos].se,langkah+1); } } return(dp[pos][langkah]); } int main() { while(scanf("%d",&n)!=EOF) { memset(dp,-1,sizeof(dp)); memset(special,false,sizeof(special)); for(x=0;x<n;x++) { scanf("%s %s %s %s",posisi,kiri,kanan,status); jalur[posisi[0]-'A']=mp(kiri[0]-'A',kanan[0]-'A'); if(status[0]=='x') special[posisi[0]-'A']=true; } scanf("%d",&m); printf("%d\n",jalan(0,0)); } return 0; }
19.474576
85
0.59443
[ "vector" ]
6d896632ef0b3ce439c8ac4d12eacf8aae62ddb9
424
cpp
C++
UVa Online Judge (UVa)/Volume 101/10107 - What is the Median.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 101/10107 - What is the Median.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 101/10107 - What is the Median.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
2
2018-11-06T19:37:56.000Z
2018-11-09T19:05:46.000Z
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int main() { long n; vector <long> v; while( scanf("%ld", &n)==1 ) { v.push_back(n); sort(v.begin(), v.end()); long len = v.size(), result; if( len&1 ) result = v[((len+1)/2)-1]; else result = (v[((len+1)/2)-1] + v[(len+1)/2])/2; printf("%ld\n", result); } return 0; }
16.96
58
0.481132
[ "vector" ]
6d89871b93609cb6d569b5a11a58ef5c479ab4d8
7,483
cpp
C++
src/chollian.cpp
YongTaek/ChollianWallPaper
cc0cc47d78216c1373ea032bdd8841fdf94c3f3f
[ "MIT" ]
null
null
null
src/chollian.cpp
YongTaek/ChollianWallPaper
cc0cc47d78216c1373ea032bdd8841fdf94c3f3f
[ "MIT" ]
null
null
null
src/chollian.cpp
YongTaek/ChollianWallPaper
cc0cc47d78216c1373ea032bdd8841fdf94c3f3f
[ "MIT" ]
null
null
null
// // Created by Jino on 2021/07/14. // #include <filesystem> #include <QSystemTrayIcon> #include <QMenu> #include <QtGui/QActionGroup> #include <QTimer> #include <QtConcurrent/QtConcurrent> #include "about.h" #include "downloader.h" #include "chollian.h" #include "logger.h" Chollian::Chollian() : m_color(Color::True), m_imgType(ImageType::FullDome), m_resolution(Resolution(2880, 1800)), m_is_automatically_update(false){ LOG("Chollian Wallpaper started"); LOG("RESOURCE_PATH : " + m_RESOURCE_PATH); if(!std::filesystem::exists(m_RESOURCE_PATH)){ LOG(m_RESOURCE_PATH + " directory does not exists; Create it"); std::filesystem::create_directory(m_RESOURCE_PATH); } QSystemTrayIcon *trayIcon = new QSystemTrayIcon(this); trayIcon->setToolTip("Tray!"); // Create menu items QMenu *menu = new QMenu(this); QAction *about_action = menu->addAction("About(TBD)"); menu->addSection(""); m_update_wallpaper_action = menu->addAction("Update wallpaper now"); m_auto_update_action = menu->addAction("Update wallpaper every 10 minutes"); menu->addSection("Type"); QAction *type_fulldome_action = menu->addAction("Full Dome"); QAction *type_eastasia_action = menu->addAction("East Asia (experimental)"); menu->addSection("Colors"); QAction *color_rgb_true_action = menu->addAction("RGB True"); QAction *color_natural_action = menu->addAction("Natural"); menu->addSection("Resolution"); QMenu *res_menu = menu->addMenu("Resolution"); QActionGroup *res_action_group = new QActionGroup(this); generate_resolution_menus(res_menu, res_action_group, res_list_4_3); res_menu->addSeparator(); generate_resolution_menus(res_menu, res_action_group, res_list_16_9); res_menu->addSeparator(); generate_resolution_menus(res_menu, res_action_group, res_list_16_10); menu->addSeparator(); QAction *quit_action = menu->addAction("Quit"); // Set menu items (exclusive, range, etc) QActionGroup *set_type_group = new QActionGroup(this); QActionGroup *set_color_group = new QActionGroup(this); set_type_group->setExclusive(true); set_type_group->addAction(type_fulldome_action); set_type_group->addAction(type_eastasia_action); type_fulldome_action->setCheckable(true); type_fulldome_action->setChecked(true); type_eastasia_action->setCheckable(true); set_color_group->setExclusive(true); set_color_group->addAction(color_rgb_true_action); set_color_group->addAction(color_natural_action); color_rgb_true_action->setCheckable(true); color_rgb_true_action->setChecked(true); color_natural_action->setCheckable(true); m_auto_update_action->setCheckable(true); m_auto_update_action->setChecked(false); res_action_group->setExclusive(true); m_about_window = new About(); // Connect menu items with slot connect(about_action, &QAction::triggered, this, [this](){ this->m_about_window->show(); }); connect(m_update_wallpaper_action, &QAction::triggered, this, [this](){change_wallpaper_slot(m_imgType, m_color, m_resolution);}); connect(m_auto_update_action, &QAction::triggered, this, [this](){switch_automatically_update_slot();}); connect(type_fulldome_action, &QAction::triggered, this, [this](){set_type_slot(ImageType::FullDome);}); connect(type_eastasia_action, &QAction::triggered, this, [this](){set_type_slot(ImageType::EastAsia);}); connect(color_rgb_true_action, &QAction::triggered, this, [this](){set_color_slot(Color::True);}); connect(color_natural_action, &QAction::triggered, this, [this](){set_color_slot(Color::Natural);}); connect(quit_action, &QAction::triggered, this, [this](){quit_slot();}); trayIcon->setContextMenu(menu); trayIcon->show(); trayIcon->setIcon(QIcon(QString::fromStdString(m_RESOURCE_PATH + "icon.png"))); // Generate timer m_timer = new QTimer(this); connect(m_timer, &QTimer::timeout, this, [this](){change_wallpaper_slot(m_imgType, m_color, m_resolution);}); } void Chollian::change_wallpaper_slot(ImageType imgType, Color color, Resolution resolution) { LOG("Task started"); auto _ = QtConcurrent::task([this, imgType, color, resolution]{ enable_button(false); UTCTime utcTime; utcTime.adjust_target_time(); const std::string url = url_generator_chollian(imgType, color, utcTime); LOG("Generated url : " + url); const std::string img_binary = image_downloader(url); LOG("Downloaded binary size : " + std::to_string(img_binary.length())); // Stop if downloaded data is reasonably small if(img_binary.length() < 200000){ LOG("Skip updating wallpaper"); return; } const std::string filename = generate_filename(utcTime, color, imgType, resolution.first, resolution.second); Image img = Image(img_binary); img.to_any_resolution(resolution.first, resolution.second, 100); if(std::filesystem::exists(m_RESOURCE_PATH)){ img.write_png(m_RESOURCE_PATH + filename); LOG("Save image as "+ m_RESOURCE_PATH + filename); } else{ LOG("RESOURCE_PATH not exists : "+ m_RESOURCE_PATH); return; } img.set_as_wallpaper(m_RESOURCE_PATH + filename); LOG("Wallpaper updated"); // Clean up previously stored images for (const auto &entry : std::filesystem::directory_iterator(m_RESOURCE_PATH)){ const std::string entry_filename = entry.path().filename().string(); if(entry_filename.compare(filename) && entry_filename.compare("icon.png") && entry_filename.compare("log.txt")){ std::filesystem::remove(entry); } } enable_button(true); LOG("Task ended"); }).spawn(); } void Chollian::switch_automatically_update_slot(){ if(!m_is_automatically_update){ LOG("Automatic update enabled"); // Turn on automatic update // 1. Update now // 2. Set `m_is_automatically_update` true // 3. Start timer change_wallpaper_slot(m_imgType, m_color, m_resolution); m_is_automatically_update = true; // Update per 10 minutes m_timer->start(600000); } else{ LOG("Automatic update disabled"); // Turn off automatic update // 1. Set `m_is_automatically_update` false // 2. Stop timer m_is_automatically_update = false; m_timer->stop(); } } void Chollian::generate_resolution_menus(QMenu *res_menu, QActionGroup *res_action_group, const std::vector<Resolution> &res_list){ for(Resolution res : res_list){ const std::string title = std::to_string(res.first)+" x "+std::to_string(res.second); QAction *tmp_res_action = res_menu->addAction(QString::fromStdString(title)); connect(tmp_res_action, &QAction::triggered, this, [this, res](){ set_resolution_slot(res);}); tmp_res_action->setCheckable(true); tmp_res_action->setChecked(false); if(res == m_resolution){ tmp_res_action->setChecked(true); } res_action_group->addAction(tmp_res_action); } } void Chollian::enable_button(bool enable){ m_update_wallpaper_action->setEnabled(enable); m_auto_update_action->setEnabled(enable); }
38.374359
134
0.680743
[ "vector" ]
6d89c5d91b2203c4236accce28fb5cc781d3b57b
7,416
cpp
C++
tests/Unit/Evolution/DgSubcell/Test_PrepareNeighborData.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
tests/Unit/Evolution/DgSubcell/Test_PrepareNeighborData.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
tests/Unit/Evolution/DgSubcell/Test_PrepareNeighborData.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <cstddef> #include <iterator> #include <utility> #include <vector> #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/DataVector.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "DataStructures/Variables.hpp" #include "DataStructures/VariablesTag.hpp" #include "Domain/LogicalCoordinates.hpp" #include "Domain/Structure/Direction.hpp" #include "Domain/Structure/DirectionMap.hpp" #include "Domain/Structure/Element.hpp" #include "Domain/Structure/ElementId.hpp" #include "Domain/Structure/OrientationMap.hpp" #include "Domain/Structure/OrientationMapHelpers.hpp" #include "Domain/Tags.hpp" #include "Evolution/DgSubcell/Mesh.hpp" #include "Evolution/DgSubcell/PrepareNeighborData.hpp" #include "Evolution/DgSubcell/Projection.hpp" #include "Evolution/DgSubcell/RdmpTciData.hpp" #include "Evolution/DgSubcell/Tags/DataForRdmpTci.hpp" #include "Evolution/DgSubcell/Tags/Inactive.hpp" #include "Evolution/DgSubcell/Tags/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Spectral.hpp" #include "Utilities/Gsl.hpp" #include "Utilities/Literals.hpp" #include "Utilities/TMPL.hpp" namespace { struct GhostZoneSize : db::SimpleTag { using type = size_t; }; struct Var1 : db::SimpleTag { using type = Scalar<DataVector>; }; template <size_t Dim> struct Metavariables { static constexpr size_t volume_dim = Dim; struct system { using variables_tag = ::Tags::Variables<tmpl::list<Var1>>; }; struct SubcellOptions { template <typename DbTagsList> static size_t ghost_zone_size(const db::DataBox<DbTagsList>& box) { return db::get<GhostZoneSize>(box); } struct GhostDataToSlice { using return_tags = tmpl::list<>; using argument_tags = tmpl::list<evolution::dg::subcell::Tags::Inactive< typename system::variables_tag>>; template <typename T> static Variables<tmpl::list<evolution::dg::subcell::Tags::Inactive<Var1>>> apply(const T& subcell_vars) { T subcell_vars_to_send = subcell_vars; get(get<evolution::dg::subcell::Tags::Inactive<Var1>>( subcell_vars_to_send)) *= 2.0; return subcell_vars_to_send; } }; }; }; template <size_t Dim> Element<Dim> create_element() { DirectionMap<Dim, Neighbors<Dim>> neighbors{}; for (size_t i = 0; i < 2 * Dim; ++i) { // only populate some directions with neighbors to test that we can handle // that case correctly. This is needed for DG-subcell at external boundaries if (i % 2 == 0) { neighbors[gsl::at(Direction<Dim>::all_directions(), i)] = Neighbors<Dim>{{ElementId<Dim>{i + 1, {}}}, {}}; if constexpr (Dim == 3) { if (i == 2) { neighbors[gsl::at(Direction<Dim>::all_directions(), i)] = Neighbors<Dim>{ {ElementId<Dim>{i + 1, {}}}, OrientationMap<Dim>{std::array{ Direction<Dim>::lower_xi(), Direction<Dim>::lower_eta(), Direction<Dim>::upper_zeta()}}}; } } } } return Element<Dim>{ElementId<Dim>{0, {}}, neighbors}; } template <size_t Dim> std::vector<Direction<Dim>> expected_neighbor_directions() { std::vector<Direction<Dim>> neighbor_directions{}; for (size_t i = 0; i < 2 * Dim; ++i) { // only populate some directions with neighbors to test that we can handle // that case correctly. This is needed for DG-subcell at external boundaries if (i % 2 == 0) { neighbor_directions.push_back( gsl::at(Direction<Dim>::all_directions(), i)); } } return neighbor_directions; } template <size_t Dim> void test() { using variables_tag = ::Tags::Variables<tmpl::list<Var1>>; const Mesh<Dim> dg_mesh{5, Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto}; const Mesh<Dim> subcell_mesh = evolution::dg::subcell::fd::mesh(dg_mesh); const Element<Dim> element = create_element<Dim>(); Variables<tmpl::list<Var1>> vars{dg_mesh.number_of_grid_points(), 0.0}; get(get<Var1>(vars)) = get<0>(logical_coordinates(dg_mesh)); Variables<tmpl::list<evolution::dg::subcell::Tags::Inactive<Var1>>> inactive_vars{subcell_mesh.number_of_grid_points()}; inactive_vars = evolution::dg::subcell::fd::project(vars, dg_mesh, subcell_mesh.extents()); const size_t ghost_zone_size = 2; auto box = db::create< tmpl::list<GhostZoneSize, evolution::dg::subcell::Tags::Mesh<Dim>, domain::Tags::Element<Dim>, variables_tag, evolution::dg::subcell::Tags::Inactive<variables_tag>, evolution::dg::subcell::Tags::DataForRdmpTci>>( ghost_zone_size, subcell_mesh, element, vars, inactive_vars, evolution::dg::subcell::RdmpTciData{}); const auto data_for_neighbors = evolution::dg::subcell::prepare_neighbor_data<Metavariables<Dim>>( make_not_null(&box)); const auto& rdmp_tci_data = db::get<evolution::dg::subcell::Tags::DataForRdmpTci>(box); CHECK_ITERABLE_APPROX(rdmp_tci_data.min_variables_values, std::vector<double>{-1.0}); CHECK_ITERABLE_APPROX(rdmp_tci_data.max_variables_values, std::vector<double>{1.0}); // Set all directions to false, enable the desired ones below DirectionMap<Dim, bool> directions_to_slice{}; for (const auto& direction : Direction<Dim>::all_directions()) { directions_to_slice[direction] = false; } REQUIRE(data_for_neighbors.size() == Dim); const size_t num_ghost_points = subcell_mesh.slice_away(0).number_of_grid_points() * ghost_zone_size; for (const auto& direction : expected_neighbor_directions<Dim>()) { REQUIRE(data_for_neighbors.contains(direction)); REQUIRE(data_for_neighbors.at(direction).size() == num_ghost_points + 2); directions_to_slice[direction] = true; } // do same operation as GhostDataToSlice get(get<evolution::dg::subcell::Tags::Inactive<Var1>>(inactive_vars)) *= 2.0; auto expected_neighbor_data = evolution::dg::subcell::slice_data(inactive_vars, subcell_mesh.extents(), ghost_zone_size, directions_to_slice); if constexpr (Dim == 3) { const auto direction = expected_neighbor_directions<Dim>()[1]; Index<Dim> slice_extents = subcell_mesh.extents(); slice_extents[direction.dimension()] = ghost_zone_size; expected_neighbor_data.at(direction) = orient_variables(expected_neighbor_data.at(direction), slice_extents, element.neighbors().at(direction).orientation()); } for (const auto& direction : expected_neighbor_directions<Dim>()) { const auto& data_in_direction = data_for_neighbors.at(direction); CHECK_ITERABLE_APPROX( expected_neighbor_data.at(direction), std::vector<double>(data_in_direction.begin(), std::prev(data_in_direction.end(), 2))); CHECK(*std::prev(data_in_direction.end(), 2) == approx(1.0)); CHECK(*std::prev(data_in_direction.end(), 1) == approx(-1.0)); } } } // namespace SPECTRE_TEST_CASE("Unit.Evolution.Subcell.PrepareNeighborData", "[Evolution][Unit]") { test<1>(); test<2>(); test<3>(); }
37.836735
80
0.675971
[ "mesh", "vector" ]
6d89f66249ae948810fc451e77cc610fbeaa7409
12,836
cpp
C++
src/cryptonote_core/miner.cpp
cmonsol/digitalmoney
6973a2426d490580659ae8234a799f0bcc9b84ba
[ "MIT" ]
null
null
null
src/cryptonote_core/miner.cpp
cmonsol/digitalmoney
6973a2426d490580659ae8234a799f0bcc9b84ba
[ "MIT" ]
null
null
null
src/cryptonote_core/miner.cpp
cmonsol/digitalmoney
6973a2426d490580659ae8234a799f0bcc9b84ba
[ "MIT" ]
null
null
null
// Copyright (c) 2011-2015 The Cryptonote developers // Copyright (c) 2014-2015 XDN developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sstream> #include <numeric> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/interprocess/detail/atomic.hpp> #include <boost/limits.hpp> #include <boost/utility/value_init.hpp> #include "misc_language.h" #include "include_base_utils.h" #include "cryptonote_basic_impl.h" #include "cryptonote_format_utils.h" #include "file_io_utils.h" #include "common/command_line.h" #include "crypto/hash.h" #include "crypto/random.h" #include "string_coding.h" #include "storages/portable_storage_template_helper.h" using namespace epee; #include "miner.h" #include <thread> #include <future> namespace cryptonote { miner::miner(const Currency& currency, i_miner_handler* phandler): m_currency(currency), m_stop(1), m_template(boost::value_initialized<Block>()), m_template_no(0), m_diffic(0), m_thread_index(0), m_phandler(phandler), m_pausers_count(0), m_threads_total(0), m_starter_nonce(0), m_last_hr_merge_time(0), m_hashes(0), m_do_print_hashrate(false), m_do_mining(false), m_current_hash_rate(0) { } //----------------------------------------------------------------------------------------------------- miner::~miner() { stop(); } //----------------------------------------------------------------------------------------------------- bool miner::set_block_template(const Block& bl, const difficulty_type& di) { CRITICAL_REGION_LOCAL(m_template_lock); m_template = bl; m_diffic = di; ++m_template_no; m_starter_nonce = crypto::rand<uint32_t>(); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_block_chain_update() { if (!is_mining()) { return true; } return request_block_template(); } //----------------------------------------------------------------------------------------------------- bool miner::request_block_template() { Block bl = AUTO_VAL_INIT(bl); difficulty_type di = AUTO_VAL_INIT(di); uint64_t height; cryptonote::blobdata extra_nonce; if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size()) { extra_nonce = m_extra_messages[m_config.current_extra_message_index]; } if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce)) { LOG_ERROR("Failed to get_block_template(), stopping mining"); return false; } set_block_template(bl, di); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_idle() { m_update_block_template_interval.do_call([&](){ if(is_mining())request_block_template(); return true; }); m_update_merge_hr_interval.do_call([&](){ merge_hr(); return true; }); return true; } //----------------------------------------------------------------------------------------------------- void miner::do_print_hashrate(bool do_hr) { m_do_print_hashrate = do_hr; } //----------------------------------------------------------------------------------------------------- void miner::merge_hr() { if(m_last_hr_merge_time && is_mining()) { m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1)); CRITICAL_REGION_LOCAL(m_last_hash_rates_lock); m_last_hash_rates.push_back(m_current_hash_rate); if(m_last_hash_rates.size() > 19) m_last_hash_rates.pop_front(); if(m_do_print_hashrate) { uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0); float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size()); std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << ENDL; } } m_last_hr_merge_time = misc_utils::get_tick_count(); m_hashes = 0; } bool miner::init(const MinerConfig& config) { if (!config.extraMessages.empty()) { std::string buff; bool r = file_io_utils::load_file_to_string(config.extraMessages, buff); CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << config.extraMessages); std::vector<std::string> extra_vec; boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on ); m_extra_messages.resize(extra_vec.size()); for(size_t i = 0; i != extra_vec.size(); i++) { string_tools::trim(extra_vec[i]); if(!extra_vec[i].size()) continue; std::string buff = string_encoding::base64_decode(extra_vec[i]); if(buff != "0") m_extra_messages[i] = buff; } m_config_folder_path = boost::filesystem::path(config.extraMessages).parent_path().string(); m_config = AUTO_VAL_INIT(m_config); epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + "/" + cryptonote::parameters::MINER_CONFIG_FILE_NAME); LOG_PRINT_L0("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index); } if(!config.startMining.empty()) { if (!m_currency.parseAccountAddressString(config.startMining, m_mine_address)) { LOG_ERROR("Target account address " << config.startMining << " has wrong format, starting daemon canceled"); return false; } m_threads_total = 1; m_do_mining = true; if(config.miningThreads > 0) { m_threads_total = config.miningThreads; } } return true; } //----------------------------------------------------------------------------------------------------- bool miner::is_mining() { return !m_stop; } //----------------------------------------------------------------------------------------------------- bool miner::start(const AccountPublicAddress& adr, size_t threads_count, const boost::thread::attributes& attrs) { m_mine_address = adr; m_threads_total = static_cast<uint32_t>(threads_count); m_starter_nonce = crypto::rand<uint32_t>(); CRITICAL_REGION_LOCAL(m_threads_lock); if(is_mining()) { LOG_ERROR("Starting miner but it's already started"); return false; } if(!m_threads.empty()) { LOG_ERROR("Unable to start miner because there are active mining threads"); return false; } if(!m_template_no) request_block_template();//lets update block template boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0); boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0); for(size_t i = 0; i != threads_count; i++) { m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this))); } LOG_PRINT_L0("Mining has started with " << threads_count << " threads, good luck!" ) return true; } //----------------------------------------------------------------------------------------------------- uint64_t miner::get_speed() { if(is_mining()) return m_current_hash_rate; else return 0; } //----------------------------------------------------------------------------------------------------- void miner::send_stop_signal() { boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1); } //----------------------------------------------------------------------------------------------------- bool miner::stop() { send_stop_signal(); CRITICAL_REGION_LOCAL(m_threads_lock); BOOST_FOREACH(boost::thread& th, m_threads) th.join(); m_threads.clear(); LOG_PRINT_L0("Mining has been stopped, " << m_threads.size() << " finished" ); return true; } //----------------------------------------------------------------------------------------------------- bool miner::find_nonce_for_given_block(crypto::cn_context &context, Block& bl, const difficulty_type& diffic) { unsigned nthreads = std::thread::hardware_concurrency(); if (nthreads > 0 && diffic > 5) { std::vector<std::future<void>> threads(nthreads); std::atomic<uint32_t> foundNonce; std::atomic<bool> found(false); uint32_t startNonce = crypto::rand<uint32_t>(); for (unsigned i = 0; i < nthreads; ++i) { threads[i] = std::async(std::launch::async, [&, i]() { crypto::cn_context localctx; crypto::hash h; Block lb(bl); // copy to local block for (uint32_t nonce = startNonce + i; !found; nonce += nthreads) { lb.nonce = nonce; if (!get_block_longhash(localctx, lb, h)) { return; } if (check_hash(h, diffic)) { foundNonce = nonce; found = true; return; } } }); } for (auto& t : threads) { t.wait(); } if (found) { bl.nonce = foundNonce.load(); } return found; } else { for (; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) { crypto::hash h; if (!get_block_longhash(context, bl, h)) { return false; } if (check_hash(h, diffic)) { return true; } } } return false; } //----------------------------------------------------------------------------------------------------- void miner::on_synchronized() { if(m_do_mining) { boost::thread::attributes attrs; attrs.set_stack_size(THREAD_STACK_SIZE); start(m_mine_address, m_threads_total, attrs); } } //----------------------------------------------------------------------------------------------------- void miner::pause() { CRITICAL_REGION_LOCAL(m_miners_count_lock); ++m_pausers_count; if(m_pausers_count == 1 && is_mining()) LOG_PRINT_L2("MINING PAUSED"); } //----------------------------------------------------------------------------------------------------- void miner::resume() { CRITICAL_REGION_LOCAL(m_miners_count_lock); --m_pausers_count; if(m_pausers_count < 0) { m_pausers_count = 0; LOG_PRINT_RED_L0("Unexpected miner::resume() called"); } if(!m_pausers_count && is_mining()) LOG_PRINT_L2("MINING RESUMED"); } //----------------------------------------------------------------------------------------------------- bool miner::worker_thread() { uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index); LOG_PRINT_L0("Miner thread was started ["<< th_local_index << "]"); log_space::log_singletone::set_thread_log_prefix(std::string("[miner ") + std::to_string(th_local_index) + "]"); uint32_t nonce = m_starter_nonce + th_local_index; difficulty_type local_diff = 0; uint32_t local_template_ver = 0; crypto::cn_context context; Block b; while(!m_stop) { if(m_pausers_count)//anti split workaround { misc_utils::sleep_no_w(100); continue; } if(local_template_ver != m_template_no) { CRITICAL_REGION_BEGIN(m_template_lock); b = m_template; local_diff = m_diffic; CRITICAL_REGION_END(); local_template_ver = m_template_no; nonce = m_starter_nonce + th_local_index; } if(!local_template_ver)//no any set_block_template call { LOG_PRINT_L2("Block template not set yet"); epee::misc_utils::sleep_no_w(1000); continue; } b.nonce = nonce; crypto::hash h; if (!m_stop && !get_block_longhash(context, b, h)) { LOG_ERROR("Failed to get block long hash"); m_stop = true; } if (!m_stop && check_hash(h, local_diff)) { //we lucky! ++m_config.current_extra_message_index; LOG_PRINT_GREEN("Found block for difficulty: " << local_diff, LOG_LEVEL_0); if(!m_phandler->handle_block_found(b)) { --m_config.current_extra_message_index; }else { //success update, lets update config epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + cryptonote::parameters::MINER_CONFIG_FILE_NAME); } } nonce+=m_threads_total; ++m_hashes; } LOG_PRINT_L0("Miner thread stopped ["<< th_local_index << "]"); return true; } //----------------------------------------------------------------------------------------------------- }
32.744898
139
0.547756
[ "vector" ]
6d8a847d66e58c3b442c15b3ae2345a94260c7ce
25,857
cxx
C++
src/libmime/received.cxx
check-spelling/rspamd
9c933b1803ae7a2665a5b12ddda06f3126cb870b
[ "Apache-2.0" ]
null
null
null
src/libmime/received.cxx
check-spelling/rspamd
9c933b1803ae7a2665a5b12ddda06f3126cb870b
[ "Apache-2.0" ]
null
null
null
src/libmime/received.cxx
check-spelling/rspamd
9c933b1803ae7a2665a5b12ddda06f3126cb870b
[ "Apache-2.0" ]
1
2022-02-20T17:41:48.000Z
2022-02-20T17:41:48.000Z
/*- * Copyright 2021 Vsevolod Stakhov * * 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 <mempool_vars_internal.h> #include "config.h" #include "libserver/url.h" #include "lua/lua_common.h" #include "libserver/cfg_file.h" #include "mime_string.hxx" #include "smtp_parsers.h" #include "message.h" #include "received.hxx" #include "frozen/string.h" #include "frozen/unordered_map.h" namespace rspamd::mime { enum class received_part_type { RSPAMD_RECEIVED_PART_FROM, RSPAMD_RECEIVED_PART_BY, RSPAMD_RECEIVED_PART_FOR, RSPAMD_RECEIVED_PART_WITH, RSPAMD_RECEIVED_PART_ID, RSPAMD_RECEIVED_PART_UNKNOWN, }; struct received_part { received_part_type type; mime_string data; std::vector<mime_string> comments; explicit received_part(received_part_type t) : type(t), data(received_char_filter) {} }; static inline auto received_part_set_or_append(const gchar *begin, gsize len, mime_string &dest) -> void { if (len == 0) { return; } dest.append(begin, len); dest.trim(" \t"); } static auto received_process_part(const std::string_view &data, received_part_type type, std::ptrdiff_t &last, received_part &npart) -> bool { auto obraces = 0, ebraces = 0; auto seen_tcpinfo = false; enum _parse_state { skip_spaces, in_comment, read_data, read_tcpinfo, all_done } state, next_state; /* In this function, we just process comments and data separately */ const auto *p = data.data(); const auto *end = p + data.size(); const auto *c = p; state = skip_spaces; next_state = read_data; while (p < end) { switch (state) { case skip_spaces: if (!g_ascii_isspace(*p)) { c = p; state = next_state; } else { p++; } break; case in_comment: if (*p == '(') { obraces++; } else if (*p == ')') { ebraces++; if (ebraces >= obraces) { if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) { if (p > c) { npart.comments.emplace_back(received_char_filter); auto &comment = npart.comments.back(); received_part_set_or_append(c, p - c, comment); } } p++; c = p; state = skip_spaces; next_state = read_data; continue; } } p++; break; case read_data: if (*p == '(') { if (p > c) { if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) { received_part_set_or_append(c, p - c, npart.data); } } state = in_comment; obraces = 1; ebraces = 0; p++; c = p; } else if (g_ascii_isspace (*p)) { if (p > c) { if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) { received_part_set_or_append(c, p - c, npart.data); } } state = skip_spaces; next_state = read_data; c = p; } else if (*p == ';') { /* It is actually delimiter of date part if not in the comments */ if (p > c) { if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) { received_part_set_or_append(c, p - c, npart.data); } } state = all_done; continue; } else if (npart.data.size() > 0) { /* We have already received data and find something with no ( */ if (!seen_tcpinfo && type == received_part_type::RSPAMD_RECEIVED_PART_FROM) { /* Check if we have something special here, such as TCPinfo */ if (*c == '[') { state = read_tcpinfo; p++; } else { state = all_done; continue; } } else { state = all_done; continue; } } else { p++; } break; case read_tcpinfo: if (*p == ']') { received_part_set_or_append(c, p - c + 1, npart.data); seen_tcpinfo = TRUE; state = skip_spaces; next_state = read_data; c = p; } p++; break; case all_done: if (p > data.data()) { last = p - data.data(); return true; } else { /* Empty element */ return false; } break; } } /* Leftover */ switch (state) { case read_data: if (p > c) { if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) { received_part_set_or_append(c, p - c, npart.data); } last = p - data.data(); return true; } break; case skip_spaces: if (p > data.data()) { last = p - data.data(); return true; } default: break; } return false; } template <std::size_t N> constexpr auto lit_compare_lowercase(const char lit[N], const char *in) -> bool { for (auto i = 0; i < N; i ++) { if (lc_map[(unsigned char)in[i]] != lit[i]) { return false; } } return true; } static auto received_spill(const std::string_view &in, std::ptrdiff_t &date_pos) -> std::vector<received_part> { std::vector<received_part> parts; std::ptrdiff_t pos = 0; auto seen_from = false, seen_by = false; const auto *p = in.data(); const auto *end = p + in.size(); auto skip_spaces = [&p, end]() { while (p < end && g_ascii_isspace (*p)) { p++; } }; skip_spaces(); /* Skip SMTP comments */ if (*p == '(') { auto obraces = 0, ebraces = 0; while (p < end) { if (*p == ')') { ebraces ++; } else if (*p == '(') { obraces ++; } p ++; if (obraces == ebraces) { /* Skip spaces after */ skip_spaces(); break; } } } auto len = end - p; if (len == 0) { return parts; } auto maybe_process_part = [&](received_part_type what) -> bool { parts.emplace_back(what); auto &rcvd_part = parts.back(); auto chunk = std::string_view{p, (std::size_t)(end - p)}; if (!received_process_part(chunk, what, pos, rcvd_part)) { parts.pop_back(); return false; } return true; }; if (len > 4 && lit_compare_lowercase<4>("from", p)) { p += sizeof("from") - 1; /* We can now store from part */ if (!maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_FROM)) { /* Do not accept malformed from */ return {}; } g_assert (pos != 0); p += pos; len = end > p ? end - p : 0; seen_from = true; } if (len > 2 && lit_compare_lowercase<2>("by", p)) { p += sizeof("by") - 1; if (!maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_BY)) { return {}; } g_assert (pos != 0); p += pos; len = end > p ? end - p : 0; seen_by = true; } if (!seen_from && !seen_by) { /* Useless received */ return {}; } while (p < end) { bool got_part = false; if (*p == ';') { /* We are at the date separator, stop here */ date_pos = p - in.data() + 1; break; } else { if (len > sizeof("with") && lit_compare_lowercase<4>("with", p)) { p += sizeof("with") - 1; got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_WITH); } else if (len > sizeof("for") && lit_compare_lowercase<3>("for", p)) { p += sizeof("for") - 1; got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_FOR); } else if (len > sizeof("id") && lit_compare_lowercase<2>("id", p)) { p += sizeof("id") - 1; got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_ID); } else { while (p < end) { if (!(g_ascii_isspace (*p) || *p == '(' || *p == ';')) { p++; } else { break; } } if (p == end) { return {}; } else if (*p == ';') { date_pos = p - in.data() + 1; break; } else { got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN); } } if (!got_part) { p++; len = end > p ? end - p : 0; } else { g_assert (pos != 0); p += pos; len = end > p ? end - p : 0; } } } return parts; } #define RSPAMD_INET_ADDRESS_PARSE_RECEIVED \ (rspamd_inet_address_parse_flags)(RSPAMD_INET_ADDRESS_PARSE_REMOTE|RSPAMD_INET_ADDRESS_PARSE_NO_UNIX) static auto received_process_rdns(rspamd_mempool_t *pool, const std::string_view &in, mime_string &dest) -> bool { auto seen_dot = false; const auto *p = in.data(); const auto *end = p + in.size(); if (in.empty()) { return false; } if (*p == '[' && *(end - 1) == ']' && in.size() > 2) { /* We have enclosed ip address */ auto *addr = rspamd_parse_inet_address_pool(p + 1, (end - p) - 2, pool, RSPAMD_INET_ADDRESS_PARSE_RECEIVED); if (addr) { const gchar *addr_str; if (rspamd_inet_address_get_port(addr) != 0) { addr_str = rspamd_inet_address_to_string_pretty(addr); } else { addr_str = rspamd_inet_address_to_string(addr); } dest.assign_copy(std::string_view{addr_str}); return true; } } auto hlen = 0u; while (p < end) { if (!g_ascii_isspace(*p) && rspamd_url_is_domain(*p)) { if (*p == '.') { seen_dot = true; } hlen++; } else { break; } p++; } if (hlen > 0) { if (p == end || (seen_dot && (g_ascii_isspace(*p) || *p == '[' || *p == '('))) { /* All data looks like a hostname */ dest.assign_copy(std::string_view{in.data(), hlen}); return true; } } return false; } static auto received_process_host_tcpinfo(rspamd_mempool_t *pool, received_header &rh, const std::string_view &in) -> bool { rspamd_inet_addr_t *addr = nullptr; auto ret = false; if (in.empty()) { return false; } if (in[0] == '[') { /* Likely Exim version */ auto brace_pos = in.find(']'); if (brace_pos != std::string_view::npos) { auto substr_addr = in.substr(1, brace_pos - 1); addr = rspamd_parse_inet_address_pool(substr_addr.data(), substr_addr.size(), pool, RSPAMD_INET_ADDRESS_PARSE_RECEIVED); if (addr) { rh.addr = addr; rh.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(addr))); } } } else { if (g_ascii_isxdigit(in[0])) { /* Try to parse IP address */ addr = rspamd_parse_inet_address_pool(in.data(), in.size(), pool, RSPAMD_INET_ADDRESS_PARSE_RECEIVED); if (addr) { rh.addr = addr; rh.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(addr))); } } if (!addr) { /* Try canonical Postfix version: rdns [ip] */ auto obrace_pos = in.find('['); if (obrace_pos != std::string_view::npos) { auto ebrace_pos = in.rfind(']'); if (ebrace_pos != std::string_view::npos && ebrace_pos > obrace_pos) { auto substr_addr = in.substr(obrace_pos + 1, ebrace_pos - obrace_pos - 1); addr = rspamd_parse_inet_address_pool(substr_addr.data(), substr_addr.size(), pool, RSPAMD_INET_ADDRESS_PARSE_RECEIVED); if (addr) { rh.addr = addr; rh.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(addr))); /* Process with rDNS */ auto rdns_substr = in.substr(0, obrace_pos); if (received_process_rdns(pool,rdns_substr,rh.real_hostname)) { ret = true; } } } } else { /* Hostname or some crap, sigh... */ if (received_process_rdns(pool, in, rh.real_hostname)) { ret = true; } } } } return ret; } static void received_process_from(rspamd_mempool_t *pool, const received_part &rpart, received_header &rh) { if (rpart.data.size() > 0) { /* We have seen multiple cases: * - [ip] (hostname/unknown [real_ip]) * - helo (hostname/unknown [real_ip]) * - [ip] * - hostname * - hostname ([ip]:port helo=xxx) * Maybe more... */ auto seen_ip_in_data = false; if (!rpart.comments.empty()) { /* We can have info within comment as part of RFC */ received_process_host_tcpinfo( pool, rh, rpart.comments[0].as_view()); } if (rh.real_ip.size() == 0) { /* Try to do the same with data */ if (received_process_host_tcpinfo( pool, rh, rpart.data.as_view())) { seen_ip_in_data = true; } } if (!seen_ip_in_data) { if (rh.real_ip.size() != 0) { /* Get anounced hostname (usually helo) */ received_process_rdns(pool, rpart.data.as_view(), rh.from_hostname); } else { received_process_host_tcpinfo(pool, rh, rpart.data.as_view()); } } } else { /* rpart->dlen = 0 */ if (!rpart.comments.empty()) { received_process_host_tcpinfo( pool, rh, rpart.comments[0].as_view()); } } } static auto received_header_parse(received_header_chain &chain, rspamd_mempool_t *pool, const std::string_view &in, struct rspamd_mime_header *hdr) -> bool { std::ptrdiff_t date_pos = -1; static constexpr const auto protos_map = frozen::make_unordered_map<frozen::string, received_flags>({ {"smtp", received_flags::SMTP}, {"esmtp", received_flags::ESMTP}, {"esmtpa", received_flags::ESMTPA | received_flags::AUTHENTICATED}, {"esmtpsa", received_flags::ESMTPSA | received_flags::SSL | received_flags::AUTHENTICATED}, {"esmtps", received_flags::ESMTPS | received_flags::SSL}, {"lmtp", received_flags::LMTP}, {"imap", received_flags::IMAP}, {"imaps", received_flags::IMAP | received_flags::SSL}, {"http", received_flags::HTTP}, {"https", received_flags::HTTP | received_flags::SSL}, {"local", received_flags::LOCAL} }); auto parts = received_spill(in, date_pos); if (parts.empty()) { return false; } auto &rh = chain.new_received(); rh.flags = received_flags::UNKNOWN; rh.hdr = hdr; for (const auto &part : parts) { switch (part.type) { case received_part_type::RSPAMD_RECEIVED_PART_FROM: received_process_from(pool, part, rh); break; case received_part_type::RSPAMD_RECEIVED_PART_BY: received_process_rdns(pool, part.data.as_view(), rh.by_hostname); break; case received_part_type::RSPAMD_RECEIVED_PART_WITH: if (part.data.size() > 0) { auto proto_flag_it = protos_map.find(part.data.as_view()); if (proto_flag_it != protos_map.end()) { rh.flags = proto_flag_it->second; } } break; case received_part_type::RSPAMD_RECEIVED_PART_FOR: rh.for_mbox.assign_copy(part.data); rh.for_addr = rspamd_email_address_from_smtp(rh.for_mbox.data(), rh.for_mbox.size()); break; default: /* Do nothing */ break; } } if (!rh.real_hostname.empty() && rh.from_hostname.empty()) { rh.from_hostname.assign_copy(rh.real_hostname); } if (date_pos > 0 && date_pos < in.size()) { auto date_sub = in.substr(date_pos); rh.timestamp = rspamd_parse_smtp_date((const unsigned char*)date_sub.data(), date_sub.size(), nullptr); } return true; } static auto received_maybe_fix_task(struct rspamd_task *task) -> bool { auto *recv_chain_ptr = static_cast<received_header_chain *>(MESSAGE_FIELD(task, received_headers)); if (recv_chain_ptr) { auto need_recv_correction = false; auto top_recv_maybe = recv_chain_ptr->get_received(0); if (top_recv_maybe.has_value()) { auto &top_recv = top_recv_maybe.value().get(); const auto *raddr = top_recv.addr; if (top_recv.real_ip.size() == 0 || (task->cfg && task->cfg->ignore_received)) { need_recv_correction = true; } else if (!(task->flags & RSPAMD_TASK_FLAG_NO_IP) && task->from_addr) { if (!raddr) { need_recv_correction = true; } else { if (rspamd_inet_address_compare(raddr, task->from_addr, FALSE) != 0) { need_recv_correction = true; } } } if (need_recv_correction && !(task->flags & RSPAMD_TASK_FLAG_NO_IP) && task->from_addr) { msg_debug_task ("the first received seems to be" " not ours, prepend it with fake one"); auto &trecv = recv_chain_ptr->new_received(received_header_chain::append_type::append_head); trecv.flags |= received_flags::ARTIFICIAL; if (task->flags & RSPAMD_TASK_FLAG_SSL) { trecv.flags |= received_flags::SSL; } if (task->auth_user) { trecv.flags |= received_flags::AUTHENTICATED; } trecv.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(task->from_addr))); const auto *mta_name = (const char*)rspamd_mempool_get_variable(task->task_pool, RSPAMD_MEMPOOL_MTA_NAME); if (mta_name) { trecv.by_hostname.assign_copy(std::string_view(mta_name)); } trecv.addr = rspamd_inet_address_copy(task->from_addr); if (task->hostname) { trecv.real_hostname.assign_copy(std::string_view(task->hostname)); trecv.from_hostname.assign_copy(trecv.real_hostname); } return true; } /* Extract data from received header if we were not given IP */ if (!need_recv_correction && (task->flags & RSPAMD_TASK_FLAG_NO_IP) && (task->cfg && !task->cfg->ignore_received)) { if (!top_recv.real_ip.empty()) { if (!rspamd_parse_inet_address (&task->from_addr, top_recv.real_ip.data(), top_recv.real_ip.size(), RSPAMD_INET_ADDRESS_PARSE_NO_UNIX)) { msg_warn_task ("cannot get IP from received header: '%s'", top_recv.real_ip.data()); task->from_addr = nullptr; } } if (!top_recv.real_hostname.empty()) { task->hostname = top_recv.real_hostname.data(); } return true; } } } return false; } static auto received_export_to_lua(received_header_chain *chain, lua_State *L) -> bool { if (chain == nullptr) { return false; } lua_createtable(L, chain->size(), 0); auto push_flag = [L](const received_header &rh, received_flags fl, const char *name) { lua_pushboolean(L, !!(rh.flags & fl)); lua_setfield(L, -2, name); }; auto i = 1; for (const auto &rh : chain->as_vector()) { lua_createtable (L, 0, 10); if (rh.hdr && rh.hdr->decoded) { rspamd_lua_table_set(L, "raw", rh.hdr->decoded); } lua_createtable(L, 0, 3); push_flag(rh, received_flags::ARTIFICIAL, "artificial"); push_flag(rh, received_flags::AUTHENTICATED, "authenticated"); push_flag(rh, received_flags::SSL, "ssl"); lua_setfield(L, -2, "flags"); auto push_nullable_string = [L](const mime_string &st, const char *field) { if (st.empty()) { lua_pushnil(L); } else { lua_pushlstring(L, st.data(), st.size()); } lua_setfield(L, -2, field); }; push_nullable_string(rh.from_hostname, "from_hostname"); push_nullable_string(rh.real_hostname, "real_hostname"); push_nullable_string(rh.real_ip, "from_ip"); push_nullable_string(rh.by_hostname, "by_hostname"); push_nullable_string(rh.for_mbox, "for"); if (rh.addr) { rspamd_lua_ip_push(L, rh.addr); } else { lua_pushnil(L); } lua_setfield(L, -2, "real_ip"); lua_pushstring(L, received_protocol_to_string(rh.flags)); lua_setfield(L, -2, "proto"); lua_pushinteger(L, rh.timestamp); lua_setfield(L, -2, "timestamp"); lua_rawseti(L, -2, i++); } return true; } } // namespace rspamd::mime bool rspamd_received_header_parse(struct rspamd_task *task, const char *data, size_t sz, struct rspamd_mime_header *hdr) { auto *recv_chain_ptr = static_cast<rspamd::mime::received_header_chain *> (MESSAGE_FIELD(task, received_headers)); if (recv_chain_ptr == nullptr) { /* This constructor automatically registers dtor in mempool */ recv_chain_ptr = new rspamd::mime::received_header_chain(task); MESSAGE_FIELD(task, received_headers) = (void *)recv_chain_ptr; } return rspamd::mime::received_header_parse(*recv_chain_ptr, task->task_pool, std::string_view{data, sz}, hdr); } bool rspamd_received_maybe_fix_task(struct rspamd_task *task) { return rspamd::mime::received_maybe_fix_task(task); } bool rspamd_received_export_to_lua(struct rspamd_task *task, lua_State *L) { return rspamd::mime::received_export_to_lua( static_cast<rspamd::mime::received_header_chain *>(MESSAGE_FIELD(task, received_headers)), L); } /* Tests part */ #define DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL #include "doctest/doctest.h" TEST_SUITE("received") { TEST_CASE("parse received") { using namespace std::string_view_literals; using map_type = robin_hood::unordered_flat_map<std::string_view, std::string_view>; std::vector<std::pair<std::string_view, map_type>> cases{ // Simple received {"from smtp11.mailtrack.pl (smtp11.mailtrack.pl [185.243.30.90])"sv, { {"real_ip", "185.243.30.90"}, {"real_hostname", "smtp11.mailtrack.pl"}, {"from_hostname", "smtp11.mailtrack.pl"} } }, // Real Postfix IPv6 received {"from server.chat-met-vreemden.nl (unknown [IPv6:2a01:7c8:aab6:26d:5054:ff:fed1:1da2])\n" "\t(using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits))\n" "\t(Client did not present a certificate)\n" "\tby mx1.freebsd.org (Postfix) with ESMTPS id CF0171862\n" "\tfor <test@example.com>; Mon, 6 Jul 2015 09:01:20 +0000 (UTC)\n" "\t(envelope-from upwest201diana@outlook.com)"sv, { {"real_ip", "2a01:7c8:aab6:26d:5054:ff:fed1:1da2"}, {"from_hostname", "server.chat-met-vreemden.nl"}, {"by_hostname", "mx1.freebsd.org"}, {"for_mbox", "<test@example.com>"} } }, // Exim IPv4 received {"from localhost ([127.0.0.1]:49019 helo=hummus.csx.cam.ac.uk)\n" " by hummus.csx.cam.ac.uk with esmtp (Exim 4.91-pdpfix1)\n" " (envelope-from <exim-dev-bounces@exim.org>)\n" " id 1fZ55o-0006DP-3H\n" " for <xxx@xxx.xxx>; Sat, 30 Jun 2018 02:54:28 +0100"sv, { {"from_hostname", "localhost"}, {"real_ip", "127.0.0.1"}, {"for_mbox", "<xxx@xxx.xxx>"}, {"by_hostname", "hummus.csx.cam.ac.uk"}, } }, // Exim IPv6 received {"from smtp.spodhuis.org ([2a02:898:31:0:48:4558:736d:7470]:38689\n" " helo=mx.spodhuis.org)\n" " by hummus.csx.cam.ac.uk with esmtpsa (TLSv1.3:TLS_AES_256_GCM_SHA384:256)\n" " (Exim 4.91-pdpfix1+cc) (envelope-from <xxx@exim.org>)\n" " id 1fZ55k-0006CO-9M\n" " for exim-dev@exim.org; Sat, 30 Jun 2018 02:54:24 +0100"sv, { {"from_hostname", "smtp.spodhuis.org"}, {"real_ip", "2a02:898:31:0:48:4558:736d:7470"}, {"for_mbox", "exim-dev@exim.org"}, {"by_hostname", "hummus.csx.cam.ac.uk"}, } }, // Haraka received {"from aaa.cn ([1.1.1.1]) by localhost.localdomain (Haraka/2.8.18) with " "ESMTPA id 349C9C2B-491A-4925-A687-3EF14038C344.1 envelope-from <huxin@xxx.com> " "(authenticated bits=0); Tue, 03 Jul 2018 14:18:13 +0200"sv, { {"from_hostname", "aaa.cn"}, {"real_ip", "1.1.1.1"}, {"by_hostname", "localhost.localdomain"}, } }, // Invalid by {"from [192.83.172.101] (HELLO 148.251.238.35) (148.251.238.35) " "by guovswzqkvry051@sohu.com with gg login " "by AOL 6.0 for Windows US sub 008 SMTP ; Tue, 03 Jul 2018 09:01:47 -0300"sv, { {"from_hostname", "192.83.172.101"}, {"real_ip", "192.83.172.101"}, } }, // Invalid hostinfo {"from example.com ([]) by example.com with ESMTP id 2019091111 ;" " Thu, 26 Sep 2019 11:19:07 +0200"sv, { {"by_hostname", "example.com"}, {"from_hostname", "example.com"}, {"real_hostname", "example.com"}, } }, // Different real and announced hostnames + broken crap {"from 171-29.br (1-1-1-1.z.com.br [1.1.1.1]) by x.com.br (Postfix) " "with;ESMTP id 44QShF6xj4z1X for <hey@y.br>; Thu, 21 Mar 2019 23:45:46 -0300 " ": <g @yi.br>"sv, { {"real_ip", "1.1.1.1"}, {"from_hostname", "171-29.br"}, {"real_hostname", "1-1-1-1.z.com.br"}, {"by_hostname", "x.com.br"}, } }, // Different real and announced ips + no hostname {"from [127.0.0.1] ([127.0.0.2]) by smtp.gmail.com with ESMTPSA id xxxololo"sv, { {"real_ip", "127.0.0.2"}, {"from_hostname", "127.0.0.1"}, {"by_hostname", "smtp.gmail.com"}, } }, // Different real and hostanes {"from 185.118.166.127 (steven2.zhou01.pserver.ru [185.118.166.127]) " "by mail.832zsu.cn (Postfix) with ESMTPA id AAD722133E34"sv, { {"real_ip", "185.118.166.127"}, {"from_hostname", "185.118.166.127"}, {"real_hostname", "steven2.zhou01.pserver.ru"}, {"by_hostname", "mail.832zsu.cn"}, } }, // \0 in received must be filtered {"from smtp11.mailt\0rack.pl (smtp11.mail\0track.pl [1\085.243.30.90])"sv, { {"real_ip", "185.243.30.90"}, {"real_hostname", "smtp11.mailtrack.pl"}, {"from_hostname", "smtp11.mailtrack.pl"} } }, // No from part {"by mail.832zsu.cn (Postfix) with ESMTPA id AAD722133E34"sv, { {"by_hostname", "mail.832zsu.cn"}, } }, // From part is in the comment {"(from asterisk@localhost)\n" " by pbx.xxx.com (8.14.7/8.14.7/Submit) id 076Go4wD014562;\n" " Thu, 6 Aug 2020 11:50:04 -0500"sv, { {"by_hostname", "pbx.xxx.com"}, } }, }; rspamd_mempool_t *pool = rspamd_mempool_new_default("rcvd test", 0); for (auto &&c : cases) { SUBCASE(c.first.data()) { rspamd::mime::received_header_chain chain; auto ret = rspamd::mime::received_header_parse(chain, pool, c.first, nullptr); CHECK(ret == true); auto &&rh = chain.get_received(0); CHECK(rh.has_value()); auto res = rh.value().get().as_map(); for (const auto &expected : c.second) { CHECK_MESSAGE(res.contains(expected.first), expected.first.data()); CHECK(res[expected.first] == expected.second); } for (const auto &existing : res) { CHECK_MESSAGE(c.second.contains(existing.first), existing.first.data()); CHECK(c.second[existing.first] == existing.second); } } } rspamd_mempool_delete(pool); } }
24.934426
102
0.625479
[ "vector" ]
6d8de9c07b8324d2e7118a30017acf0e74f1d796
130,458
cpp
C++
SampleProject/Builds/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs77.cpp
frenchmajorcsminor/MapsSDK-Unity
0b3c0713d63279bd9fa62837fa7559d7f3cbd439
[ "MIT" ]
null
null
null
SampleProject/Builds/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs77.cpp
frenchmajorcsminor/MapsSDK-Unity
0b3c0713d63279bd9fa62837fa7559d7f3cbd439
[ "MIT" ]
null
null
null
SampleProject/Builds/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs77.cpp
frenchmajorcsminor/MapsSDK-Unity
0b3c0713d63279bd9fa62837fa7559d7f3cbd439
[ "MIT" ]
null
null
null
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <limits> #include "vm/CachedCCWBase.h" #include "utils/New.h" // UnityEngine.Networking.NetworkSystem.PeerInfoMessage[] struct PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A; // UnityEngine.Networking.NetworkSystem.PeerInfoPlayer[] struct PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1; // UnityEngine.Events.PersistentCall[] struct PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8; // UnityEngine.Networking.PlayerController[] struct PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202; // System.Net.Http.Headers.ProductHeaderValue[] struct ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF; // System.Net.Http.Headers.ProductInfoHeaderValue[] struct ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746; // System.Diagnostics.Tracing.PropertyAnalysis[] struct PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188; // System.Reflection.PropertyInfo[] struct PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A; // Microsoft.MixedReality.Toolkit.Utilities.ProximityLight[] struct ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6; // UnityEngine.Networking.QosType[] struct QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC; struct IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB; struct IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA; struct IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Windows.Foundation.Collections.IIterable`1<System.Object> struct NOVTABLE IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) = 0; }; // Windows.Foundation.Collections.IVectorView`1<System.Object> struct NOVTABLE IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) = 0; }; // Windows.UI.Xaml.Interop.IBindableIterable struct NOVTABLE IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) = 0; }; // Windows.UI.Xaml.Interop.IBindableVector struct NOVTABLE IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() = 0; }; // System.Object // System.Collections.Generic.List`1<UnityEngine.Networking.NetworkSystem.PeerInfoMessage> struct List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64, ____items_1)); } inline PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A* get__items_1() const { return ____items_1; } inline PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A** get_address_of__items_1() { return &____items_1; } inline void set__items_1(PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_StaticFields, ____emptyArray_5)); } inline PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A* get__emptyArray_5() const { return ____emptyArray_5; } inline PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(PeerInfoMessageU5BU5D_t80FABE57B63348BD531E5A0C1F9EFE4A1077A19A* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Networking.NetworkSystem.PeerInfoPlayer> struct List_1_t9D140A08FB942235B9F31C470AEEC435BF441454 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t9D140A08FB942235B9F31C470AEEC435BF441454, ____items_1)); } inline PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1* get__items_1() const { return ____items_1; } inline PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1** get_address_of__items_1() { return &____items_1; } inline void set__items_1(PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t9D140A08FB942235B9F31C470AEEC435BF441454, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t9D140A08FB942235B9F31C470AEEC435BF441454, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t9D140A08FB942235B9F31C470AEEC435BF441454, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_StaticFields, ____emptyArray_5)); } inline PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1* get__emptyArray_5() const { return ____emptyArray_5; } inline PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(PeerInfoPlayerU5BU5D_t5DE72B6244230DD9324DAA472EB577DF30A144A1* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Events.PersistentCall> struct List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E, ____items_1)); } inline PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8* get__items_1() const { return ____items_1; } inline PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8** get_address_of__items_1() { return &____items_1; } inline void set__items_1(PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_StaticFields, ____emptyArray_5)); } inline PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8* get__emptyArray_5() const { return ____emptyArray_5; } inline PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(PersistentCallU5BU5D_tD75161239574F577A13288CD351BE2B65DEEABF8* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Networking.PlayerController> struct List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23, ____items_1)); } inline PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202* get__items_1() const { return ____items_1; } inline PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202** get_address_of__items_1() { return &____items_1; } inline void set__items_1(PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_StaticFields, ____emptyArray_5)); } inline PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202* get__emptyArray_5() const { return ____emptyArray_5; } inline PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(PlayerControllerU5BU5D_t90DE31F741DF86DB874B2BAB2B90E57C80BEB202* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Net.Http.Headers.ProductHeaderValue> struct List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27, ____items_1)); } inline ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF* get__items_1() const { return ____items_1; } inline ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_StaticFields, ____emptyArray_5)); } inline ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF* get__emptyArray_5() const { return ____emptyArray_5; } inline ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ProductHeaderValueU5BU5D_t91F8E8691DF069B4300E23FA98141730A9F6BBCF* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Net.Http.Headers.ProductInfoHeaderValue> struct List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876, ____items_1)); } inline ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746* get__items_1() const { return ____items_1; } inline ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_StaticFields, ____emptyArray_5)); } inline ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746* get__emptyArray_5() const { return ____emptyArray_5; } inline ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ProductInfoHeaderValueU5BU5D_tB56573AB1A4B6CA025F527DCCFF8A99F8B8F6746* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Diagnostics.Tracing.PropertyAnalysis> struct List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9, ____items_1)); } inline PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188* get__items_1() const { return ____items_1; } inline PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188** get_address_of__items_1() { return &____items_1; } inline void set__items_1(PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_StaticFields, ____emptyArray_5)); } inline PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188* get__emptyArray_5() const { return ____emptyArray_5; } inline PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(PropertyAnalysisU5BU5D_tE6638E721F7DEF91FA37025E8F23D6FD2EF7C188* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Reflection.PropertyInfo> struct List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521, ____items_1)); } inline PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A* get__items_1() const { return ____items_1; } inline PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A** get_address_of__items_1() { return &____items_1; } inline void set__items_1(PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_StaticFields, ____emptyArray_5)); } inline PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A* get__emptyArray_5() const { return ____emptyArray_5; } inline PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(PropertyInfoU5BU5D_tE59E95F68533BDA98ABBBEACB6A99BF2C7A4A26A* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<Microsoft.MixedReality.Toolkit.Utilities.ProximityLight> struct List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121, ____items_1)); } inline ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6* get__items_1() const { return ____items_1; } inline ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_StaticFields, ____emptyArray_5)); } inline ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6* get__emptyArray_5() const { return ____emptyArray_5; } inline ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ProximityLightU5BU5D_tD9EA566D14E857042641E4A378C21D09948510E6* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Networking.QosType> struct List_1_t146E41614BC10ED6410A7DB377E4B440D565915C : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t146E41614BC10ED6410A7DB377E4B440D565915C, ____items_1)); } inline QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC* get__items_1() const { return ____items_1; } inline QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC** get_address_of__items_1() { return &____items_1; } inline void set__items_1(QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t146E41614BC10ED6410A7DB377E4B440D565915C, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t146E41614BC10ED6410A7DB377E4B440D565915C, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t146E41614BC10ED6410A7DB377E4B440D565915C, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_StaticFields, ____emptyArray_5)); } inline QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC* get__emptyArray_5() const { return ____emptyArray_5; } inline QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(QosTypeU5BU5D_tBD18D4433BE0BAE4E84DB8FBD5AAED31E234ADEC* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif il2cpp_hresult_t IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue); il2cpp_hresult_t IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue); il2cpp_hresult_t IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable** comReturnValue); il2cpp_hresult_t IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue); il2cpp_hresult_t IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(RuntimeObject* __this, Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue); il2cpp_hresult_t IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable* ___value1); il2cpp_hresult_t IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable* ___value1); il2cpp_hresult_t IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0); il2cpp_hresult_t IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(RuntimeObject* __this, Il2CppIInspectable* ___value0); il2cpp_hresult_t IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable** comReturnValue); il2cpp_hresult_t IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(RuntimeObject* __this, Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue); il2cpp_hresult_t IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue); // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Networking.NetworkSystem.PeerInfoMessage> struct List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t652CB14BCB37B53525BA819CB69CAB0680059A64_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Networking.NetworkSystem.PeerInfoPlayer> struct List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC { inline List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(2); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[1] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; *iidCount = 2; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t9D140A08FB942235B9F31C470AEEC435BF441454(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t9D140A08FB942235B9F31C470AEEC435BF441454_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Events.PersistentCall> struct List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t0AA6B1123983D70EF4686E9230A4AE3DC192BB3E_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Networking.PlayerController> struct List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t9B51907D678DE298D43D3C0145BE8A0BB9C6BD23_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Net.Http.Headers.ProductHeaderValue> struct List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t6C24F1F02C5782B86B66A6539B9C36772CFD0F27_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Net.Http.Headers.ProductInfoHeaderValue> struct List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t1C2D8D12CF00CD88F5713BAFCA3B09384DFF1876_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Diagnostics.Tracing.PropertyAnalysis> struct List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_tBEBB5482A4BC53228DC48B4E63129118D3FF13F9_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Reflection.PropertyInfo> struct List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t6D217E5C7E8FD2DA6CE90941A9E364AEFB622521_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<Microsoft.MixedReality.Toolkit.Utilities.ProximityLight> struct List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t7122A1096830814697EF24FEA6BB2F0EBACAE121_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Networking.QosType> struct List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC { inline List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(2); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[1] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; *iidCount = 2; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t146E41614BC10ED6410A7DB377E4B440D565915C(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t146E41614BC10ED6410A7DB377E4B440D565915C_ComCallableWrapper(obj)); }
49.415909
416
0.848978
[ "object" ]
6d91e63cad44338fb47bf49a03f3038f9e8e9a3b
880
cpp
C++
559_Maximum_Depth_of_N-ary_Tree.cpp
Gauawa12/GFG-codes
c790efb783c463187dcfce4b7155d9f86227dbed
[ "MIT" ]
null
null
null
559_Maximum_Depth_of_N-ary_Tree.cpp
Gauawa12/GFG-codes
c790efb783c463187dcfce4b7155d9f86227dbed
[ "MIT" ]
null
null
null
559_Maximum_Depth_of_N-ary_Tree.cpp
Gauawa12/GFG-codes
c790efb783c463187dcfce4b7155d9f86227dbed
[ "MIT" ]
null
null
null
Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example, given a 3-ary tree: We should return its max depth, which is 3. Note: The depth of the tree is at most 1000. The total number of nodes is at most 5000. Sol: /* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: int maxDepth(Node* root) { int ans=0; if(!root) { ans=0; return ans; } for(int i=0;i<root->children.size();i++) { ans=max(ans,maxDepth(root->children[i])); } return ans+1; } };
16
114
0.563636
[ "vector" ]
6d9301b7b7e9dbd04d70c4dea37c105cddd549c7
4,039
cpp
C++
oneflow/core/job_rewriter/lamb_optm.cpp
ncnnnnn/oneflow
f6e81f65eed1d87c3125e7a78247cfaa72220020
[ "Apache-2.0" ]
2
2021-09-10T00:19:49.000Z
2021-11-16T11:27:20.000Z
oneflow/core/job_rewriter/lamb_optm.cpp
duijiudanggecl/oneflow
d2096ae14cf847509394a3b717021e2bd1d72f62
[ "Apache-2.0" ]
null
null
null
oneflow/core/job_rewriter/lamb_optm.cpp
duijiudanggecl/oneflow
d2096ae14cf847509394a3b717021e2bd1d72f62
[ "Apache-2.0" ]
1
2021-11-10T07:57:01.000Z
2021-11-10T07:57:01.000Z
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/job_rewriter/optimizer.h" #include "oneflow/core/framework/framework.h" namespace oneflow { namespace { std::string GenVariableOutputLbn(const OperatorConf& op_conf) { CHECK(op_conf.has_variable_conf()); return GenLogicalBlobName(op_conf.name(), op_conf.variable_conf().out()); } OperatorConf GenerateLAMBHelperVariableOpConf(const VariableOp& op, const std::string& name, const float initial_value) { OperatorConf helper_variable_op(op.op_conf()); helper_variable_op.set_name(op.op_name() + "-" + name); helper_variable_op.mutable_variable_conf()->set_out("out"); InitializerConf constant_initializer; constant_initializer.mutable_constant_conf()->set_value(initial_value); *(helper_variable_op.mutable_variable_conf()->mutable_initializer()) = constant_initializer; helper_variable_op.set_scope_symbol_id(op.op_conf().scope_symbol_id()); return helper_variable_op; } void SetScalarShapeAndSbpConf(OperatorConf* op_conf) { op_conf->mutable_variable_conf()->mutable_shape()->clear_dim(); op_conf->mutable_variable_conf()->mutable_shape()->add_dim(1); op_conf->mutable_variable_conf()->mutable_split_axis()->clear_value(); CHECK_NE(op_conf->name(), std::string("")); } void GenerateOptimizerOpConf(JobPassCtx* ctx, const VariableOp& op, const ParallelConf& parallel_conf, JobBuilder* job_builder, const LogicalBlobId& diff_lbi_of_var_out) { const auto& train_conf = job_builder->job().job_conf().train_conf(); const NormalModelUpdateOpUserConf& model_update_conf = train_conf.model_update_conf(); OperatorConf m_var = GenerateLAMBHelperVariableOpConf(op, "m", 0.f); OperatorConf v_var = GenerateLAMBHelperVariableOpConf(op, "v", 0.f); job_builder->AddOps(parallel_conf, {m_var, v_var}); OperatorConf beta1_t_var; OperatorConf beta2_t_var; const LambModelUpdateConf& lamb_conf = model_update_conf.lamb_conf(); beta1_t_var = GenerateLAMBHelperVariableOpConf(op, "beta1_t", lamb_conf.beta1()); SetScalarShapeAndSbpConf(&beta1_t_var); beta2_t_var = GenerateLAMBHelperVariableOpConf(op, "beta2_t", lamb_conf.beta2()); SetScalarShapeAndSbpConf(&beta2_t_var); job_builder->AddOps(parallel_conf, {beta1_t_var, beta2_t_var}); user_op::UserOpConfWrapperBuilder lamb_update_op_builder(op.op_name() + "_optimizer"); lamb_update_op_builder.OpTypeName("lamb_update") .Input("m", GenVariableOutputLbn(m_var)) .Input("v", GenVariableOutputLbn(v_var)) .Input("beta1_t", GenVariableOutputLbn(beta1_t_var)) .Input("beta2_t", GenVariableOutputLbn(beta2_t_var)) .Input("model", GenLogicalBlobName(op.BnInOp2Lbi("out"))) .Input("model_diff", GenLogicalBlobName(diff_lbi_of_var_out)) .Input("learning_rate", train_conf.primary_lr_lbn()) .Attr<float>("beta1", lamb_conf.beta1()) .Attr<float>("beta2", lamb_conf.beta2()) .Attr<float>("epsilon", lamb_conf.epsilon()) .Attr<float>("weight_decay", GetOptimizerWeightDecayRate(model_update_conf, op)) .ScopeSymbolId(op.op_conf().scope_symbol_id()); SetDynamicLossScaleSkipIf(ctx, &lamb_update_op_builder); const auto lamb_update_op = lamb_update_op_builder.Build(); job_builder->AddOps(parallel_conf, {lamb_update_op.op_conf()}); } } // namespace REGISTER_OPTIMIZER(NormalModelUpdateOpUserConf::kLambConf, &GenerateOptimizerOpConf); } // namespace oneflow
45.897727
94
0.755137
[ "model" ]
6d935fedc6a60d155d7f71c4f4690b673d4c02cd
982
cpp
C++
C++/0847-Shortest-Path-Visiting-All-Nodes/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0847-Shortest-Path-Visiting-All-Nodes/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0847-Shortest-Path-Visiting-All-Nodes/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: int shortestPathLength(vector<vector<int>>& graph) { int n = graph.size(); int target = (1 << n) - 1; queue<pair<int, int>> frontier; for(int i = 0; i < n; ++i) frontier.push({i, 1 << i}); int step = 0; set<pair<int, int>> seen; while (!frontier.empty()) { int sz = frontier.size(); int node, state; for(int i = 0; i < sz; ++i) { tie(node, state) = frontier.front(); if (state == target) return step; frontier.pop(); for(int nei : graph[node]) { int new_state = state | (1 << nei); if (seen.find({nei, new_state}) == seen.end()) { seen.insert({nei, new_state}); frontier.push({nei, new_state}); } } } ++step; } return step; } };
32.733333
68
0.412424
[ "vector" ]
6d93b7fda5369c5375c6a4093cab2006840edbee
108,813
cpp
C++
libpharos/defuse.cpp
JanWielemaker/pharos
8789a3a5ef4e6094ce0b989d8d987d1fe2102d3e
[ "RSA-MD" ]
3
2015-07-15T08:43:56.000Z
2021-02-28T17:53:52.000Z
libpharos/defuse.cpp
sei-ccohen/pharos
78d08494a5c0bffff3789cae7acc538303b1926c
[ "RSA-MD" ]
null
null
null
libpharos/defuse.cpp
sei-ccohen/pharos
78d08494a5c0bffff3789cae7acc538303b1926c
[ "RSA-MD" ]
null
null
null
// Copyright 2015-2019 Carnegie Mellon University. See LICENSE file for terms. #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #include <boost/range/adaptor/map.hpp> // #include <boost/property_map/property_map.hpp> // #include <boost/graph/properties.hpp> // #include <boost/graph/copy.hpp> #include "defuse.hpp" #include "sptrack.hpp" #include "badcode.hpp" #include "limit.hpp" #include "riscops.hpp" #include "misc.hpp" #include "util.hpp" #include "options.hpp" #include "cdg.hpp" #include "masm.hpp" namespace pharos { // In practice five iterations was all that was needed for the worst of the functions that // actually produced results (ever) in the Objdigger test suite. This limit might become // optional if we can find and fix the remaining convergence bugs. #define MAX_LOOP 5 // Enable convergence algorithm debugging, but not full state debugging. // #define CONVERGE_DEBUG // Enable full state debugging (for merge logic etc). // #define STATE_DEBUG #ifdef CONVERGE_DEBUG #define DSTREAM OINFO #else #define DSTREAM SDEBUG #endif // ========================================================================================= // Basic Block Analysis methods // ========================================================================================= BlockAnalysis::BlockAnalysis(DUAnalysis & _du, const ControlFlowGraph& cfg, CFGVertex _vertex, bool _entry) : du(_du), vertex(_vertex), entry(_entry) { block = get(boost::vertex_name, cfg, vertex); address = block->get_address(); iterations = 0; pending = true; // The meaning of this boolean has evolved gradually. It used to include blocks that were bad // because they had no proper control flow predecessors, but that's not handled by which CFG // we're using for the analysis (with certain blocks excluded completely). This boolean // still marks blocks that don't appear to be legitimate code. It's unclear whether we // really want this however. In the less rigorous analysis, we already checked this when we // filtered the pharos CFG, and perhaps we don't want to filter at all for the more rigorous // analysis? The next commit may attempt to remove this boolean entirely. bad = check_for_bad_code(du.ds, block); // Create entry condition variables for this block. Pre-computing this is a bit problematic // because it kind of prevents us from adding additional predecessors as we analyze. Perhaps // we should create these as we ask for them? Or as we add predecessors? The number of // these conditions is one less than the number of incoming edges. size_t degree = boost::in_degree(vertex, cfg); size_t num_conds = degree ? degree - 1 : 0; conditions.reserve(num_conds); // assume every block can be entered entry_condition = SymbolicValue::treenode_instance(Rose::BinaryAnalysis::SymbolicExpr::makeBoolean(true)); exit_condition = SymbolicValue::treenode_instance(Rose::BinaryAnalysis::SymbolicExpr::makeBoolean(true)); size_t i = 0; for (const SgAsmBlock *pblock : cfg_in_bblocks(cfg, vertex)) { if (i == num_conds) { break; } ++i; // Create the incomplete variable auto cv = SymbolicValue::incomplete(1); // Generate a name for the variable. This tries to give it a name based on the address of // the instruction that branched to this block. auto & bstmts = pblock->get_statementList(); rose_addr_t addr; if (bstmts.empty()) { addr = pblock->get_address(); } else { auto & last_statement = bstmts.back(); assert(last_statement); addr = last_statement->get_address(); } cv->set_comment("Cond_from_" + addr_str(addr)); // Add the variable to the list conditions.push_back(cv); } } // New algorithm discussed with Duggan merges all instruction acceses into the DUAnalysis // accesses map in one pass, utilizing move semantics and other optimizations. void DUAnalysis::update_accesses( SgAsmX86Instruction *insn, SymbolicRiscOperatorsPtr& rops) { auto it = accesses.find(insn); if (it == accesses.end()) { accesses[insn] = std::move(rops->insn_accesses); // Clear vector to avoid accessing moved elements. } else { for (auto && aa : rops->insn_accesses) { auto ait = std::find(it->second.begin(), it->second.end(), aa); #if 1 // This code if order does matter (it may still). if (ait != it->second.end()) { #if 0 // Enable some debugging about the cases that we are discarding. AbstractAccess& oaa = *ait; if (!aa.exact_match(oaa)) { OINFO << "Insn " << debug_instruction(insn) << " accesses:" << LEND; if (!(aa.value->get_expression()->isEquivalentTo(oaa.value->get_expression()))) { OINFO << " Value1: " << aa << LEND; OINFO << " Value2: " << oaa << LEND; } else { OINFO << " Instruction counts " << aa.latest_writers.size() << " vs " << oaa.latest_writers.size() << LEND; for (auto writer : aa.latest_writers) { OINFO << " LW1: " << debug_instruction(writer) << LEND; } for (auto writer : oaa.latest_writers) { OINFO << " LW2: " << debug_instruction(writer) << LEND; } } } #endif // Remove the existing access with a similar "key", because it should be older in terms // of the iteration algorithm. We'll add the new access to replace it before returning. it->second.erase(ait); } it->second.push_back(std::move(aa)); #else // This code if order doesn't matter (it may still). if (ait == it->second.end()) { it->second.push_back(std::move(aa)); } else { *ait = std::move(aa); } #endif } } // Clear vector to avoid accessing moved elements. rops->insn_accesses.clear(); } // Record the reads and writes performed by each instruction in the form of a list of abstract // accesses for each instruction. Create and update the depends_on map for each instruction. // Finally, record reads and writes for all global variables. // // This method updates all_regs, du.accesses, du.depends_on, and du.dependents_of. void BlockAnalysis::record_dependencies( SgAsmX86Instruction *insn, const SymbolicStatePtr& cstate) { SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(du.dispatcher->get_operators()); du.update_accesses(insn, rops); //du.print_accesses(insn); // Debugging // Ensure that there's always an entry in the depends_on map for this instruction. if (du.depends_on.find(insn) == du.depends_on.end()) { du.depends_on[insn] = DUChain(); } AbstractAccessVector all_regs; SDEBUG << "insn accesses size=" << du.accesses[insn].size() << LEND; for (const AbstractAccess & aa : du.accesses[insn]) { // Reads if (aa.isRead) { // ---------------------------------------------------------------------------------- // Register reads // ---------------------------------------------------------------------------------- if (aa.is_reg()) { // Update list of all registers. all_regs.push_back(aa); // Build the def-use chains RegisterDescriptor rd = aa.register_descriptor; // Skip the instruction pointer, since every instruction reads it. // The writes to EIP are kept now so that they can be inspected for branch conditions. if (rd == du.ds.get_ip_reg()) continue; SymbolicValuePtr sv = cstate->read_register(rd); if (aa.latest_writers.size() == 0) { std::string regname = unparseX86Register(rd, NULL); SDEBUG << "Warning: Use of uninitialized register " << regname << " by " << debug_instruction(insn) << LEND; Definition reg_def(NULL, aa); du.depends_on[insn].insert(reg_def); // Should probably be add_dependency_pair(insn, NULL, aa); } else { for (SgAsmInstruction* winsn : aa.latest_writers) { // Create a use-chain entry SgAsmX86Instruction *definer = isSgAsmX86Instruction(winsn); du.add_dependency_pair(insn, definer, aa); } } } // ---------------------------------------------------------------------------------- // Memory reads // ---------------------------------------------------------------------------------- else { // Find the corresponding data value for this address // InsnSet modifiers; // We're looking for global fixed memory reads here... if (aa.memory_address->is_number() && aa.memory_address->get_width() <= 64 && !insn_is_control_flow(insn)) { rose_addr_t known_addr = aa.memory_address->get_number(); // We're only interested in constants that are likely to be memory addresses. if (possible_global_address(known_addr)) { const ImportDescriptor *id = du.ds.get_import(known_addr); if (id == NULL) { GlobalMemoryDescriptor* gmd = du.ds.get_rw_global(known_addr); // add_read() if (gmd == NULL) { SDEBUG << "Unexpected global memory read from address " << addr_str(known_addr) << " at " << debug_instruction(insn) << LEND; } else { gmd->add_read(insn, aa.size); } } // When we read memory in the import table, it's often the because we've loaded the // address of the import into a register, and then called the value pointed to by // the register. } } // If there are no latest writers for this address, add a NULL definer. if (aa.latest_writers.size() == 0) { du.add_dependency_pair(insn, NULL, aa); SDEBUG << "--> Memory read at " << *(aa.memory_address) << " of " << *(aa.value) << " from NULL definer." << LEND; } else { for (SgAsmInstruction *winsn : aa.latest_writers) { SgAsmX86Instruction *definer = isSgAsmX86Instruction(winsn); du.add_dependency_pair(insn, definer, aa); SDEBUG << "--> Memory read at " << *(aa.memory_address) << " of " << *(aa.value) << " definer is " << debug_instruction(definer) << LEND; } } } } // Writes else { // ---------------------------------------------------------------------------------- // Memory writes // ---------------------------------------------------------------------------------- if (!aa.is_reg()) { // We're looking for global fixed memory writes here... if (aa.memory_address->is_number() && aa.memory_address->get_width() <= 64) { rose_addr_t known_addr = aa.memory_address->get_number(); // We're only interested in constants that are likely to be memory addresses. if (possible_global_address(known_addr)) { const ImportDescriptor *id = du.ds.get_import(known_addr); if (id == NULL) { GlobalMemoryDescriptor* gmd = du.ds.get_rw_global(known_addr); // add_write() if (gmd == NULL) { // This message is really debugging for a case that Cory is interested in, not // something that's useful to general users, so he moved it back to SDEBUG. :-( SDEBUG << "Unexpected global memory write to address " << addr_str(known_addr) << " at " << debug_instruction(insn) << LEND; } else { // Always record that there was a write to the global variable. gmd->add_write(insn, aa.size); // Record the possible value (which will only be saved if it's a new value). gmd->add_value(aa.value); } } // This is where we used to test for overwrites of imports, that's now more clearly // (but perhaps less cleanly) in RiscOps::readMemory(). } } } } } } // Reformat the exception to make it more readable, and then emit it as a warning. void handle_semantics_exception(SgAsmX86Instruction *insn, const SemanticsException &e) { // This is a hackish kludge to make the exception readable. There are different kinds of // exception generated, but they're so long that they're pretty much unreadable. They've // also go two copies of the offending instruction in an unpleasant format. It's a mess, // and Cory should talk with Robb Matzke about it... #if 1 // First transform the exception into a string. std::stringstream ss; ss << e; std::string newerror = ss.str(); // Then chop off: "Rose::BinaryAnalysis::InstructionSemantics::BaseSemantics::Exception: " if (newerror.size() > 70) { newerror = newerror.substr(70); } // Then remove eveything after the first occurence of "0x" size_t pos = newerror.find(" 0x", 0); if (pos != std::string::npos) { newerror = newerror.substr(0, pos); } // Then emit a more reasonable error. This message should really be at log level // "error", but in an effort to reduce the amount of spew for general users, Cory // downgraded it to log level "warning" until we're able to reduce the frequency of the // message. SWARN << "Semantics exception: " << newerror << " " << debug_instruction(insn) << LEND; #else // This produces unreasonably ugly messages. SWARN << e << LEND; #endif } // Check to see whether the call or jump instruction goes to some invalid code (e.g. because // the target of the jump have been obfuscated). This happens fairly frequently in malware, so // we should avoid doing stupid things when it occurs. This is some seriously ancient code // written by Wes. It's still useful, but it definitely needs some attention and improvements. bool BlockAnalysis::check_for_invalid_code(SgAsmX86Instruction *insn, size_t i) { // Get the instruction list (again). This is a little messy, but then again, so is this // whole method. const SgAsmStatementPtrList &insns = block->get_statementList(); // This should really be insn_is_branch(insn).. if (((insn->get_kind() >= x86_ja && insn->get_kind() <= x86_js) || insn->get_kind() == x86_call) && i < insns.size()-1) { SgAsmStatementPtrList ri; // The size_t i, is the current instruction in the basic block being analyzed. for (size_t qq = i+1; qq < insns.size(); qq++) ri.push_back(insns[qq]); BadCodeMetrics bc(du.ds); size_t repeated = 0, deadstores = 0, badjmps = 0, unusualInsns = 0; SDEBUG << "Testing possible jmp to packed section " << debug_instruction(insn) << LEND; auto & branchesToPackedSections = du.getJmps2UnpackedCode(); if (branchesToPackedSections.find(insn) != branchesToPackedSections.end() || bc.isBadCode(ri, &repeated, &unusualInsns, &deadstores, &badjmps)) { branchesToPackedSections.insert(insn); OINFO << "Skipping " << debug_instruction(insn) << " - Dead Stores: " << deadstores << " Repeated Insns: " << repeated << " Bad Cond Jumps: " << badjmps << " Unusual Insns: " << unusualInsns << LEND; return true; } } return false; } LimitCode BlockAnalysis::analyze(bool with_context) { // This limit is not well tested. But I know that we've encountered huge basic blocks of // thousands of instructions that made this function not perform well. ResourceLimit block_limit; get_global_limits().set_limits(block_limit, PharosLimits::limit_type::BASE); LimitCode rstatus = block_limit.check(); DSTREAM << "Emulating block " << addr_str(address) << LEND; SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote( du.dispatcher->get_operators()); size_t arch_bits = du.ds.get_arch_bits(); RegisterDescriptor eiprd = du.ds.get_ip_reg(); RegisterDescriptor esprd = du.ds.get_stack_reg(); const SgAsmStatementPtrList &insns = block->get_statementList(); for (size_t i=0; i<insns.size(); ++i) { SgAsmX86Instruction *insn = isSgAsmX86Instruction(insns[i]); if (insn == NULL) continue; block_limit.increment_counter(); rose_addr_t iaddr = insn->get_address(); STRACE << "eval bblock insn addr " << iaddr << " => " << debug_instruction(insn, 5, NULL) << LEND; // Get the state just before evaluating the instruction SymbolicStatePtr cstate = rops->get_sstate()->sclone(); if (with_context && insn_is_call(insn)) { SDEBUG << "Stack value before call is " << *rops->read_register(esprd) << LEND; CallDescriptor* cd = du.ds.get_rw_call(insn->get_address()); // set_state() assert(cd != NULL); cd->set_state(cstate); } try { // Evaluate the instruction SymbolicValuePtr iaddrptr = SymbolicValue::constant_instance(arch_bits, iaddr); // Another forced EIP hack. Possibly not needed in ROSE2 port? rops->writeRegister(eiprd, iaddrptr); SDEBUG << "Insn: " << debug_instruction(insn) << LEND; du.dispatcher->processInstruction(insn); SymbolicStatePtr pstate = rops->get_sstate(); if (with_context) { if (check_for_invalid_code(insn, i)) { handle_stack_delta(block, insn, cstate, true); // A jump/call to invalid code should be the last instruction in the block anayway. break; } if (insn_is_call(insn)) du.update_call_targets(insn, rops); handle_stack_delta(block, insn, cstate, false); du.make_call_dependencies(insn, cstate); record_dependencies(insn, cstate); } rstatus = block_limit.check(); // If we've reached our limit, stop processing instructions. if (rstatus != LimitSuccess) { SERROR << "Basic block " << addr_str(address) << " " << block_limit.get_message() << LEND; break; } } catch (const SemanticsException &e) { handle_semantics_exception(insn, e); if (with_context) handle_stack_delta(block, insn, cstate, true); } } DSTREAM << "Evaluation of basic block at " << addr_str(address) << " took " << block_limit.get_relative_clock().count() << " seconds." << LEND; return rstatus; } // A horrible hackish workaround to various bugs in ROSE. :-( Basically because ROSE doesn't // update the instruction succesors correctly we need to call bb_get_successors for lst // instruction in each basic block, and insn->get_sucessors for all others. This is indepedent // of whether the instruction is a call or not and other logic that we need... This code can // be eliminated once we have a consistent interface. bool is_last_insn_in_bb(SgAsmBlock *bb, SgAsmX86Instruction* insn) { SgAsmStatementPtrList & insns = bb->get_statementList(); SgAsmX86Instruction *last_insn = isSgAsmX86Instruction(insns[insns.size() - 1]); if (insn == last_insn) return true; return false; } AddrSet get_hinky_successors(SgAsmBlock *bb, SgAsmX86Instruction* insn, bool last) { AddrSet result; bool complete; if (last) { for (auto expr_value : bb->get_successors()) { result.insert(rose_addr_t(expr_value->get_value())); } } else { for (auto succ : insn->getSuccessors(&complete)) { result.insert(succ); } } return result; } void BlockAnalysis::handle_stack_delta(SgAsmBlock *bb, SgAsmX86Instruction* insn, SymbolicStatePtr& before_state, bool downgrade) { rose_addr_t iaddr = insn->get_address(); const CallDescriptor* cd = du.ds.get_call(iaddr); SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote( du.dispatcher->get_operators()); SymbolicStatePtr after_state = rops->get_sstate(); // We'll need to know the delta for this instruction. StackDelta olddelta = du.sp_tracker.get_delta(iaddr); SDEBUG << "Stack delta=" << olddelta << " insn=" << debug_instruction(insn) << LEND; // By default, we have wrong knowledge of the stack pointer. StackDelta newdelta(0, ConfidenceWrong); // Get the stack register descriptor. size_t arch_bits = du.ds.get_arch_bits(); size_t arch_bytes = du.ds.get_arch_bytes(); RegisterDescriptor esprd = du.ds.get_stack_reg(); // Are confident in our current knowledge of the stack pointer based on emulation? With // value sets and the current flawed merging algorithm based on defining instructions, // I'm not sure that this test is really sufficient, but that fix will have to wait. SymbolicValuePtr before_esp = before_state->read_register(esprd); SymbolicValuePtr after_esp = after_state->read_register(esprd); //SDEBUG << "Before state ESP:" << *before_esp << LEND; //SDEBUG << "After state ESP:" << *after_esp << LEND; boost::optional<int64_t> opt_before_const = before_esp->get_stack_const(); boost::optional<int64_t> opt_after_const = after_esp->get_stack_const(); if (opt_after_const && *opt_after_const != CONFUSED) { // What was the change in the emulator state from before this instruction to after this // instruction? int adjdelta = -(*opt_after_const); // We can only be as confident as our previous delta, and never more. I'm still a // little unclear about whether it's correct to assume a "certain" confidence and allow // the solve flow equation iteratively code to downgrade that confidence, or whether we // somehow need to be working our way up from guesses to certain. newdelta = StackDelta(adjdelta, olddelta.confidence); // Something strange happened here. When reviewing this code, BOTH conditions were found // to perform the same computaion, with the only difference being that this condition also // printed a warning. This code is equaivalent, but I'm unsure if it's correct anymore. if (!opt_before_const) { SINFO << "Regained confidence in stack value at " << addr_str(insn->get_address()) << " new delta=" << newdelta << LEND; } } // If the stack pointer was known going into this instruction, and is not now, we've // just lost track of it, and that's noteworthy. Warn about it. else { if (opt_before_const) { SWARN << "Lost track of stack pointer: " << debug_instruction(insn) << LEND; } } // Start by figuring out what the fall thru address is. rose_addr_t fallthru = insn_get_fallthru(insn); // Now that we've established our delta and confidence following this instruction, that // becomes the stack delta for each of the succesors for this instruction (not counting the // external target of a call). We don't really care if the list of sucessors is complete, // only that the addreses listed really are successors. // Duggan sugegsts that this loop shouldn't be over successors at all, but rather our current // best understanding of the call targets (from Parititioner 2 or perhaps our call descriptors). bool last = is_last_insn_in_bb(bb, insn); for (rose_addr_t target : get_hinky_successors(bb, insn, last)) { if (last) { // Here we need to interate over the basic block successors instead of the instruction // successors due to some inconsisntency in the way they're handled. In particular, the // sucessors on the call instruction are not updated correctly when a partitioner config is // used. SDEBUG << "Successor for last instruction in basic block is: " << addr_str(target) << LEND; // This is the "normal" call handling, which sets the stack delta for the fall thru // instruction after the call. We want to run this code when the instruction is a call, // the target we're considering is not the fallthru address, and the target is not in the // current function. The fallthru ought to b...???? // contains_insn_at(). // This might still be a little broken for cases in which the finally handler has a // non-zero delta, which we haven't computed yet, and can't set correctly. if (insn_is_call(insn)) { if (target == fallthru) { // Ask the stack tracker what the delta for this call was. StackDelta calldelta = du.get_call_delta(iaddr); GenericConfidence newconfidence = calldelta.confidence; // Downgrade confidence if required. if (newdelta.confidence < newconfidence) newconfidence = newdelta.confidence; // The additional minus 4 is to compensate for the pushed return adddress which is // already changed in the state, but is not included in the call delta. StackDelta fallthrudelta = StackDelta(newdelta.delta - calldelta.delta - arch_bytes, newconfidence); SDEBUG << "New fall thru delta is: " << fallthrudelta << LEND; // Update the state to account for the return instruction that we did not emulate. // Exactly the best way to accomplish this is a little unclear. We'd like something // that is clear and does not produce any unintended side effects related to definers // and modifiers. // Cory's not really sure if a COPY is needed here, but it seems safer than not. SymbolicValuePtr oldesp = after_state->read_register(esprd)->scopy(); auto dvalue = calldelta.delta + arch_bytes; TreeNodePtr sum = oldesp->get_expression() + dvalue; if (cd && calldelta.confidence == ConfidenceMissing) { auto sdv = cd->get_stack_delta_variable(); if (sdv) { using Rose::BinaryAnalysis::SymbolicExpr::OP_ADD; sum = InternalNode::create(arch_bits, OP_ADD, sum, sdv, Rose::BinaryAnalysis::SmtSolverPtr()); } } SymbolicValuePtr newesp = SymbolicValue::promote(oldesp->copy()); newesp->set_expression(sum); SDEBUG << "Adding oldesp=" << *oldesp << " to dvalue=" << dvalue << LEND; SDEBUG << "Yielding newesp=" << *newesp << LEND; rops->writeRegister(esprd, newesp); // Update the stack tracker and report on our actions. du.update_delta(fallthru, fallthrudelta); SDEBUG << "Setting stack delta following call to " << fallthrudelta << " insnaddr=" << addr_str(fallthru) << LEND; // We're handled this case. continue; } // If it's a call to an external address, we don't need to do anything at all. We'll // handle initialize the delta to zero when we process that function. if (!du.current_function->contains_insn_at(target)) continue; } } // In all other cases, we want to propagate our new "after" delta to all of our sucessors. // The most common case is that the instruction is in the middle of a basic block (e.g. not // the last instruction in the block). Another fairly common case is a jump table that // jumps to multiple addresses within the function, and all of the successors should start // with our stack delta. // An unusual case is when a function "calls" to a basic block contained within itself. // Normal ROSE processing for CALL/RET pairs would have put the call in the middle of a // basic block if it was obvious that the return address was popped off the stack. The // situation we're talking about is slightly more complex, where the function is calling to // itself and actually returning, but for some reason we've figured out that it is NOT a // real function. The common example is finally handlers in C++ code. The behavior is // still the same though, which is to propagate our stack delta. STRACE << "Setting stack delta=" << newdelta << " insnaddr=" << addr_str(target) << LEND; du.update_delta(target, newdelta); } // In cases where we've failed to process the instructio correctly, we now want to downgrade // the confidence to guess. Historically, this logic has been called after the normal // processing above, but it appears that this might just simply overwrite all of the work // we've done previously. We should probably investigate this case a little more carefully, // and move this code to the _top_ of this function if that's really true. if (downgrade) { // Forcibly downgrade the confidence to guess since we didn't emulate correctly. This // should probably be handled as a minimum confidence parameter to handle stack delta or // something like that. StackDelta osd = du.sp_tracker.get_delta(iaddr); if (osd.confidence > ConfidenceGuess) { osd.confidence = ConfidenceGuess; du.update_delta(iaddr, osd); } } } // ========================================================================================= // ========================================================================================= // This is not a method in DUAnalysis, because I don't want to have to have a handle to the // Analysis object to dump the definitions. It would be nicer if the DUChain map had a method // on it do this, but a global function will do for now. void print_definitions(DUChain duc) { for (const Definition & d : duc) { // Some arbitrary indentation. OINFO << " "; std::cout.width(30); OINFO << std::left << d.access.str(); OINFO << " <=== "; if (d.definer == NULL) OINFO << "[no defining instruction]" << LEND; else OINFO << debug_instruction(d.definer) << LEND; } } // ========================================================================================= // Definition and Usage Analysis // ========================================================================================= DUAnalysis::DUAnalysis(DescriptorSet& ds_, FunctionDescriptor & f) : sp_tracker(ds_), rops_callbacks(ds_), ds(ds_) { // We've always got a real function to analyze. const ProgOptVarMap& vm = ds.get_arguments(); propagate_conditions = (vm.count("propagate-conditions") > 0); current_function = &f; output_valid = false; all_returns = false; // Currently hard coded to do the traditional style of analysis. rigor = false; // The RiscOps can be obtained from the dispatcher once it's created. SymbolicRiscOperatorsPtr rops; auto ip = ds.get_partitioner().instructionProvider(); if (rigor) { // This is the new bit that instantiates the list-based memory state instead of the map based state. SymbolicRegisterStatePtr rstate = SymbolicRegisterState::instance(ip); SymbolicMemoryListStatePtr mstate = SymbolicMemoryListState::instance(); SymbolicStatePtr state = SymbolicState::instance(rstate, mstate); rops = SymbolicRiscOperators::instance(ds, state, &rops_callbacks); } else { SymbolicRegisterStatePtr rstate = SymbolicRegisterState::instance(ip); SymbolicMemoryMapStatePtr mstate = SymbolicMemoryMapState::instance(); SymbolicStatePtr state = SymbolicState::instance(rstate, mstate); rops = SymbolicRiscOperators::instance(ds, state, &rops_callbacks); } size_t arch_bits = ds.get_arch_bits(); dispatcher = RoseDispatcherX86::instance(rops, arch_bits, NULL); // Configure the limit analysis. The func_limit instance is local, but we still need to // configure the global limits of the analysis of all functions as well. get_global_limits().set_limits(func_limit, PharosLimits::limit_type::FUNC); // Now go do the analysis. if (rigor) { status = analyze_basic_blocks_independently(); } else { status = solve_flow_equation_iteratively(); } } // For debugging accessess void DUAnalysis::print_accesses(SgAsmX86Instruction* insn) const { OINFO << "Instruction accesses for: " << debug_instruction(insn) << LEND; auto iter = accesses.find(insn); if (iter == accesses.end()) { OERROR << "Instruction " << addr_str(insn->get_address()) << " has no accesses!" << LEND; } else { for (const AbstractAccess & aa : iter->second) { OINFO << " " << aa.str() << LEND; } } } // For debugging dependencies void DUAnalysis::print_dependencies() const { OINFO << "Dependencies (Inst I, value read by I <=== instruction that defined value):" << LEND; for (const Insn2DUChainMap::value_type &p : depends_on) { OINFO << debug_instruction(p.first) << LEND; print_definitions(p.second); } } // For debugging dependents void DUAnalysis::print_dependents() const { OINFO << "Dependents (Inst I, value defined by I <=== instruction that read value):" << LEND; for (const Insn2DUChainMap::value_type &p : dependents_of) { OINFO << debug_instruction(p.first) << LEND; print_definitions(p.second); } } const AbstractAccess* DUAnalysis::get_the_write(SgAsmX86Instruction* insn) const { auto writes = get_writes(insn); auto i = std::begin(writes); if (i == std::end(writes)) return NULL; const AbstractAccess *aa = &*i; if (++i != std::end(writes)) { SERROR << "Instruction: " << debug_instruction(insn) << " had more than the expected single write." << LEND; } return aa; } const AbstractAccess* DUAnalysis::get_first_mem_write(SgAsmX86Instruction* insn) const { auto mem_writes = get_mem_writes(insn); auto i = std::begin(mem_writes); if (i == std::end(mem_writes)) return NULL; return &*i; } // Is the abstract access in the provided instruction truly an uninitialized read? Some // operations, such as "AND X, 0" read X, but not in the sense intended. This code attempts to // detect that condition by also confirming that the value read was not used in a write expression // in the same instruction. If it was a fake read then there won't be a reference to the read value. // // In the case that this code was written for, the solution turned out to also require reading // our hybrid definers/writers out of the latest_writers field on the abstract access. bool DUAnalysis::fake_read(SgAsmX86Instruction* insn, const AbstractAccess& aa) const { // And here's why this algorithm got a function of it's own. There's the mildly complex case // of "AND X, 0" and other simplification identities that don't really result in true reads. // We're going to test for that case now by also confirming that there are no writes (for // this instruction) which include the value read. There would have to be a write involving // the read value or it wasn't really used. // This approach is a little lazy but I didn't want to have to write my own visitor class to // look for a specific subexpression. // JSG updated this with Robb M's guideance on searching for a subexpression. using VisitAction = Rose::BinaryAnalysis::SymbolicExpr::VisitAction; using Visitor = Rose::BinaryAnalysis::SymbolicExpr::Visitor; TreeNodePtr read_tn = aa.value->get_expression(); // The visitor needed to search for the fake read (subexpression) struct SubxVisitor : Visitor { TreeNodePtr needle_; SubxVisitor(const TreeNodePtr &needle) : needle_(needle) { } VisitAction preVisit(const TreeNodePtr &expr) { if (expr->isEquivalentTo(needle_)) { return Rose::BinaryAnalysis::SymbolicExpr::TERMINATE; } return Rose::BinaryAnalysis::SymbolicExpr::CONTINUE; } VisitAction postVisit(const TreeNodePtr&) { return Rose::BinaryAnalysis::SymbolicExpr::CONTINUE; } }; for (const AbstractAccess& waa : get_writes(insn)) { TreeNodePtr write_tn = waa.value->get_expression(); SubxVisitor read_subx(read_tn); // search if this write includes the read. If it does, then it is not fake if (write_tn->depthFirstTraversal(read_subx) == Rose::BinaryAnalysis::SymbolicExpr::TERMINATE) { // The read was somewhere in the write, so the value was _truly_ read, and we've already // established that it was initialized by someone else, so it's not a truly uninitialized // read. return false; } } // read read value was not there GDEBUG << " The read in " << debug_instruction(insn) << " was a fake read of: " << *(aa.value) << LEND; return true; } // Safely make a matching pair of dependency links. Hopefully this doesn't perform too poorly. // If it does, there are probably some optimizations that can be made using iterators that // would help. void DUAnalysis::add_dependency_pair(SgAsmX86Instruction *i1, SgAsmX86Instruction *i2, AbstractAccess access) { // Make new DUChains if needed. if (i1 != NULL && depends_on.find(i1) == depends_on.end()) depends_on[i1] = DUChain(); if (i2 != NULL && dependents_of.find(i2) == dependents_of.end()) dependents_of[i2] = DUChain(); // Add the matching entries. // i1 reads the aloc defined by i2. i2 defines the aloc read by i1. if (i1 != NULL) depends_on[i1].insert(Definition(i2, access)); if (i2 != NULL) dependents_of[i2].insert(Definition(i1, access)); } // Has our emulation of the instructions leading up to this call revealed where it calls to? // Specifically the pattern "mov esi, [import]" and "call esi" requires this code to determine // that ESI contains the address of an import table entry. void DUAnalysis::update_call_targets(SgAsmX86Instruction* insn, SymbolicRiscOperatorsPtr& rops) { SgAsmExpressionPtrList &ops = insn->get_operandList()->get_operands(); assert(ops.size() > 0); // Are we a call to register instruction? SgAsmDirectRegisterExpression *ref = isSgAsmDirectRegisterExpression(ops[0]); if (ref != NULL) { RegisterDescriptor rd = ref->get_descriptor(); // Read the current value out of the register. SymbolicValuePtr regval = SymbolicValue::promote(rops->readRegister(rd)); SDEBUG << "Call instruction: " << debug_instruction(insn) << " calls to: " << *regval << LEND; // If the outermost value has the loader defined bit then either itself or one of its // children has the loader defined bit set. Check all possible values to figure out which // one(s) have the bit. if (regval->is_loader_defined()) { SDEBUG << "Call is to loader defined value: " << *regval << LEND; for (const TreeNodePtr& tn : regval->get_possible_values()) { SymbolicValuePtr v = SymbolicValue::treenode_instance(tn); if (v->is_loader_defined()) { ds.update_import_target(v, insn); } } } } } SymbolicValuePtr create_return_value(SgAsmX86Instruction* insn, size_t bits, bool return_code) { // Decide how to label the return value. Maybe we shouldn't do this anymore, but Cory knows // that we're currently checking this comment in other places in the code, and it's not // harmful, so he's currently leaving the functionality in place. std::string cmt = ""; // We should probably be deciding whether this is a "return value" by inspecting the calling // convention rather than taking an explicit parameter from the caller. if (return_code) { // A standard return code (aka EAX). This should be expanded to include ST0 and EDX in // some cases. cmt = str(boost::format("RC_of_0x%X") % insn->get_address()); } else { // Non-standard return code (aka an overwritten scratch register). cmt = str(boost::format("NSRC_of_0x%X") % insn->get_address()); } // What happens when rd is not a 32-bit register as expected? At least we're getting the // size off the register, which would prevent us from crashing, but it's unclear whether // we've been thinking correctly through the scenarios that involve small register return // values. SymbolicValuePtr value = SymbolicValue::variable_instance(bits); value->set_comment(cmt); // This call instruction is now the only definer. value->defined_by(insn); return value; } void create_overwritten_register(SymbolicRiscOperatorsPtr rops, DescriptorSet const & ds, RegisterDescriptor rd, bool return_code, SymbolicValuePtr value, CallDescriptor* cd, const ParameterList& pl) { // Update the value of the register in the current state... rops->writeRegister(rd, value); // Record the write, since it didn't happen during semantics. rops->insn_accesses.push_back(AbstractAccess(ds, false, rd, value, rops->get_sstate())); // Set the return value in the call descriptor. Return values are more complicated than our // current design permits. For now, there's just one, which is essentially EAX. if (return_code) { cd->set_return_value(value); // Add the return register to the "returns" parameter list as well. ParameterList& params = cd->get_rw_parameters(); SDEBUG << "Creating return register parameter " << unparseX86Register(rd, NULL) << " with value " << *value << LEND; ParameterDefinition & rpd = params.create_return_reg(rd, value); // If the upstream parameters list has only a single return value, assume that this is it, // and transfer the type. if (pl.get_returns().size() == 1) { const ParameterDefinition& upstream_pd = *pl.get_returns().begin(); rpd.set_type(upstream_pd.get_type()); } } } void DUAnalysis::make_call_dependencies(SgAsmX86Instruction* insn, SymbolicStatePtr& cstate) { SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); // This might not be correct. I'm still a little muddled on how we're handling thunks. if (!insn_is_call(insn)) return; SDEBUG << "Creating parameter dependencies for " << debug_instruction(insn) << LEND; // Get the call descriptor for this call. Should we do this externally? CallDescriptor* cd = ds.get_rw_call(insn->get_address()); // multiple if (cd == NULL) { SERROR << "No call descriptor for " << debug_instruction(insn) << LEND; return; } // This is the function descriptor that contains our parameters. It might come from the // function descriptor in the call descriptor, or it might come from the import descriptor // (which must be const). const FunctionDescriptor* param_fd = NULL; // Get the function descriptor that describes the function that we're calling. There's a // nasty bit of confusion here that still needs some additional cleanup. This value can be // non-NULL even when the call is to an import descriptor, and so until we can figure out // where the bogus values are coming from (id == NULL) should be checked first. FunctionDescriptor* cfd = cd->get_rw_function_descriptor(); // Adds caller // But the call can also be to an import. If it is, this will be the import descriptor. const ImportDescriptor* id = cd->get_import_descriptor(); // If the call is to an import, the parameters will come from the function descriptor in the // import descriptor. This description may contain useful types, etc. from the API database. if (id != NULL) { param_fd = id->get_function_descriptor(); } // There's some nasty thunk logic here that I'd like to be elsewhere. else if (cfd != NULL) { const FunctionDescriptor* dethunked_cfd = cfd->follow_thunks_fd(); // If we successfully followed thunks, it's easy. if (dethunked_cfd != NULL) { param_fd = dethunked_cfd; // A little hackish code to work around some ongoing const design issues. FunctionDescriptor* non_const_cfd = ds.get_rw_func(dethunked_cfd->get_address()); // for call updates cfd = non_const_cfd; } // But there might have been thunks to addresses that are imports. This is a corner // condition that we're still hacking for in places like this. :-( else { // The worst this can do is set ID to NULL (again). rose_addr_t iaddr = cfd->follow_thunks(); id = ds.get_import(iaddr); if (id != NULL) { GDEBUG << "Got parameters for " << debug_instruction(insn) << " from thunked import." << LEND; param_fd = id->get_function_descriptor(); } } } // If we've failed to figure out which function we're calling to, it's pretty hopeless. Just // give up and return to the caller. This is done after the return code check, because it // allows us to preseume that all imports return a value without knowing any of the details // about the import (e.g. there's no function descriptor for the import). if (param_fd == NULL) { SWARN << "Unknown call target at: " << debug_instruction(insn) << ", parameter analysis failed." << LEND; return; } // The parameter definitions for the function that we're calling (including the return code // type which we'll need before the other parameter analysis). const ParameterList& fparams = param_fd->get_parameters(); // We'll be creating new parameter defintions on the call, so let's get a handle to the // parameter list object right now. ParameterList& call_params = cd->get_rw_parameters(); // ========================================================================================= // Register return code analysis... // ========================================================================================= size_t arch_bits = ds.get_arch_bits(); // This where we'll be storing the new value of EAX, get a handle to the state now. SymbolicStatePtr state = rops->get_sstate(); RegisterDescriptor esprd = ds.get_stack_reg(); RegisterDescriptor eaxrd = ds.get_arch_reg("eax"); RegisterDescriptor ecxrd = ds.get_arch_reg("ecx"); if (id != NULL) { // If we really are a call to an external import, just assume that we return a value. // Cory does't think that there are any external APIs that don't follow the standard // calling conventions, and none of them permit true returns void calls. In the // future, this code branch can become more sophisticated, asking the import // configuration what the type of return value is and so on. SDEBUG << "Creating return code for import " << id->get_long_name() << " at " << debug_instruction(insn) << LEND; // We don't handle situations involving more than one return value from an import at all // right now. That's probably ok, since it probably never happens. if (fparams.get_returns().size() > 1) { GFATAL << "Multiple return values not analyzed correctly." << LEND; } // We're going to overwrite EAX in all cases, since all external calling conventions // declare EAX as a scrtahc register, even if the function doesn't return a value. Whether // the return code is a "real" return code involving an intentional return of a value, is // determined by whether our parameter returns list contains any values. We should // probably work towards getting this register out of the calling convention data so that // we don't have to make architecture specific calls here. bool real_return_value = (fparams.get_returns().size() > 0); // This call simply creates the symbolic value that the return code is set to. SymbolicValuePtr rv = create_return_value(insn, arch_bits, real_return_value); // This call propogates the performs the actual write, creates the abstract access, sets // the return value in the call descriptor, propogates the parameter definition, etc. create_overwritten_register(rops, ds, eaxrd, real_return_value, rv, cd, fparams); SDEBUG << "Setting standard return value for " << addr_str(insn->get_address()) << " to " << *(rops->read_register(eaxrd)) << LEND; } // There Otherwise (if cfd == NULL), check for an import. else if (cfd != NULL) { SDEBUG << "Adding caller " << debug_instruction(insn) << " to call targets for " << cfd->address_string() << LEND; cfd->add_caller(insn->get_address()); const RegisterUsage& ru = cfd->get_register_usage(); SDEBUG << "Call at " << addr_str(insn->get_address()) << " returns-ecx: " << cfd->get_returns_this_pointer() << LEND; for (RegisterDescriptor rd : ru.changed_registers) { if (rd != eaxrd) { // It turns out that we can't enable this code properly because our system is just too // fragile. If we're incorrect in any low-level function, this propogates that failure // throughout the entire call-chain leading to that function. Specifically, claiming // that a function overwrites a register when it fact it does not, leads to the loss of // important local state that results in incorrect analysis. In most of the cases that // Cory has found so far, this is caused by functions with two possible execution // paths, one: returns and does not modify the register, and two: does not return and // does modify the register. Thus this might be fixed with better does not return analysis. // I re-enabled register overwritin, and we were passing tests, but I noticed that it // was doing some very bad things with tail-call optimized delete() methods, and // thought this would be a good defensive measure until we investigated more. This is // the other place where is_delete_method() is still required on a function descriptor. if (cfd->is_delete_method()) continue; SymbolicValuePtr rv = create_return_value(insn, rd.get_nbits(), false); create_overwritten_register(rops, ds, rd, false, rv, cd, fparams); GDEBUG << "Setting changed register " << unparseX86Register(rd, NULL) << " for insn " << addr_str(insn->get_address()) << " to value=" << *(rops->read_register(rd)) << LEND; // And we're done with this register... continue; } // EAX special cases... if (cfd->get_returns_this_pointer()) { // Assign to EAX in the current state, the value of ECX from the previous state. // Read the value of ecx from the current state at the time of the call. SymbolicValuePtr ecx_value = cstate->read_register(ecxrd); create_overwritten_register(rops, ds, eaxrd, true, ecx_value, cd, fparams); GDEBUG << "Setting return value for " << addr_str(insn->get_address()) << " to ECX prior to call, value=" << *(rops->read_register(eaxrd)) << LEND; } else { // Create a new symbolic value to represent the modified return code value. SymbolicValuePtr eax_value = create_return_value(insn, arch_bits, true); create_overwritten_register(rops, ds, eaxrd, true, eax_value, cd, fparams); GDEBUG << "Setting standard return value for " << addr_str(insn->get_address()) << " to " << *(rops->read_register(eaxrd)) << LEND; } } } else { // Long ago, Wes wrote code that executed here that went to the basic block where the // call originated and looked for instructions that read the eax register. If the value // had no definers, it was deemed that this function created a return value regardless of // the logic above. At revision 1549 this code was no longer required to pass tests, and // Cory removed it. GDEBUG << "Call at: " << debug_instruction(insn) << "appears to not return a value." << LEND; } // ========================================================================================= // Stack dependency analysis. Move to separate function? // // This code is mostly about deciding whether our understanding of the stack delta is correct // enough to apply the knowledge about the call target to the local environment. // ========================================================================================= // What was our stack delta going into the call instruction? StackDelta sd = sp_tracker.get_delta(insn->get_address()); // How many parameters does the call have? StackDelta params = cd->get_stack_parameters(); SDEBUG << "The call: " << debug_instruction(insn) << " appears to have " << params.delta << " bytes of parameters." << LEND; // If our confidence in the stack delta is too bad, don't make it worse by creating crazy // depdencies that are incorrect. if (sd.confidence < ConfidenceGuess && params.delta != 0) { // This is a pretty common error once our stack deltas are wrong, and so in order to reduce // spew, Cory moved this error to DEBUG, and incremented the failures counter. SWARN << "Skipping creation of " << params.delta << " bytes of parameter dependencies" << " due to low confidence of stack delta." << LEND; SWARN << "Stack delta was: " << sd << " at instruction: " << debug_instruction(insn) << LEND; // This wrongness was a consequence of earlier wrongness, but there's more wrong now. ++sd_failures; return; } // Also don't make the situation worse by creating a crazy number of dependencies if the // number of call parameters is unrealistically large. if (params.delta > ARBITRARY_PARAM_LIMIT) { SERROR << "Skipping creation of " << params.delta << " bytes of parameter dependencies" << " due to high parameter count for call: " << debug_instruction(insn) << LEND; // We know we didn't do the right thing, so let's tick failures. ++sd_failures; return; } // Dump the memory state //SDEBUG << "Memory state:" << state << LEND; SDEBUG << "Call: " << debug_instruction(insn) << " params=" << params.delta << LEND; // ========================================================================================= // Parameter definition analysis, creation, etc. // ========================================================================================= // Report the parameters that we expect to find... if (GDEBUG) { GDEBUG << "Parameters for call at: " << debug_instruction(insn) << " are: " << LEND; fparams.debug(); } // Go through each parameter to the call, and create an appropriate dependency. for (const ParameterDefinition& pd : fparams.get_params()) { // Cory says, this code used to assume that only stack parameters were in the parameter // list. Now that we're also creating parameter definitions for register values, this code // needs to be a little more complicated. The very first iteration is to simply ignore // register parameters. if (pd.is_reg()) { // ===================================================================================== // Register parameter definitions and instruction dependencies (move to a new function?) // ===================================================================================== SDEBUG << "Found register parameter: " << unparseX86Register(pd.get_register(), NULL) << " for call " << cd->address_string() << LEND; // Create a dependency between the instructions that last modifier the value of the // register, and the call instruction that uses the value (or the memory at the value?) // Read the value out of the current states SymbolicValuePtr rv = state->read_register(pd.get_register()); // The call reads the register value. AbstractAccess aa = AbstractAccess(ds, true, pd.get_register(), rv, state); SgAsmX86Instruction *latest_writer = NULL; // Create dependencies between all latest writers and the call instruction. Converting // this code to use latest writers instead of the modifiers resulted in dependencies, // where the previous approach was producing none (at least at the time). for (SgAsmInstruction* gm : aa.latest_writers) { SDEBUG << "Adding call dependency for " << debug_instruction(insn) << " to " << debug_instruction(gm) << LEND; // Convert from a generic instruction to an X86 instruction (and save last one). latest_writer = isSgAsmX86Instruction(gm); // Now create the actual dependency. add_dependency_pair(insn, latest_writer, aa); } // Also we need to find (or create) a parameter for this register on the calling side. // This routine will create the register definition if it doesn't exist and return the // existing parameter if it does. In a departure from the API I used on the stack side, // I just had the create_reg_parameter() interface update the symbolic value and modified // instruction as well. Maybe we should change the stack parameter interface to match? SymbolicValuePtr pointed_to = state->read_memory(rv, arch_bits); call_params.create_reg_parameter(pd.get_register(), rv, latest_writer, pointed_to); // We're done handling the register parameter. The rest of the code after here is for // stack parameters. continue; } // From the old code for doing this... size_t p = pd.get_stack_delta(); // The parameter will be found on the stack at [offset]. The sd.delta component is to // convert to stack deltas relative to the call. And p is the variable part (the parameter // offset in the called function). The outer sign is because we've been working with // positive deltas, and the hardware really does negative stack addresses. int64_t offset = -(sd.delta - p); // Non-negative offsets for parameters are unexpected, and produce ugly error messages // later. Additionally, it's not immediately obviously from the error message that the // sign is wrong (probably indicating a stack delta analysis failure). Let's generate an // error message specific to this situation, and the continue. if (offset > -4 || (offset % 4 != 0)) { SWARN << "Unexpected parameter offset (" << offset << ") at call: " << debug_instruction(insn) << LEND; continue; } SDEBUG << "Creating read of parameter " << p << " at stack offset: [esp" << offset << "]" << LEND; // Turn the offset into a SymbolicValue and find the memory cell for that address. // RegisterDescriptor esprd = dispatcher->findRegister("esp", arch_bits); SymbolicValuePtr esp_0 = cstate->read_register(esprd); //SDEBUG << "Initial ESP is supposedly:" << *esp_0 << LEND; SymbolicValuePtr mem_addr = SymbolicValue::promote(rops->add(esp_0, rops->number_(arch_bits, p))); //SymbolicValuePtr mem_addr = SymbolicValuePtr(new SymbolicValue(arch_bits, offset)); //SDEBUG << "Constructed memory address:" << *mem_addr << LEND; const SymbolicMemoryMapStatePtr& mstate = SymbolicMemoryMapState::promote(state->memoryState()); const MemoryCellPtr memcell = mstate->findCell(mem_addr); if (memcell == NULL) { SWARN << "No definer for parameter " << p << " at [esp" << offset << "] for call: " << debug_instruction(insn) << LEND; continue; } // Who last modified this address? This will typically be the push instruction that pushed // the parameter onto the stack before the call. This code is a little bit incorrect in // that we're assuming that all four bytes have still been modified by the same instruction // as the first byte was. SymbolicValuePtr mca = SymbolicValue::promote(memcell->get_address()); // Use rops->readMemory to read memory to read either 32 or 64 bits depending on the // architecture. In truth, we have no idea how large the object being pointed to is and // this choice is arbitary. For now I've made it the archtecture size since that seems the // least likely to cause problems. The segment register and the condition are literally // unused, and the default value shouldn't be used but might be to create a deafult value // during the read. We used to read directly out of the memory map, but we need proper // reassembly of multiple bytes so now we call readMemory. RegisterDescriptor csrd = dispatcher->findRegister("cs", 16); SymbolicValuePtr dflt = SymbolicValue::promote(rops->undefined_(arch_bits)); SymbolicValuePtr cond = SymbolicValue::promote(rops->undefined_(1)); BaseSValuePtr bmcv = rops->readMemory(csrd, mca, dflt, cond); SymbolicValuePtr mcv = SymbolicValue::promote(bmcv); SDEBUG << "Parameter memory address:" << *mca << LEND; SDEBUG << "Parameter memory value:" << *mcv << LEND; const MemoryCell::AddressSet& writers = memcell->getWriters(); // Not having any modifiers is fairly common in at least one binary file we looked at. // It's probably caused by stack delta analysis failures, so let's make that a warning. if (writers.size() == 0) { SWARN << "No latest writer for call parameter " << p << " at [esp" << offset << "] addr= " << *mca << "value=" << *mcv << " at: " << debug_instruction(insn) << LEND; continue; } // The call instruction reads this address, and gets the current value. We're assuming // that we read four bytes of memory, which is incorrect, and we should probably get around // to fixing this, but we'll need proper protoypes to know the type and size of the // parameter on the stack, which we presently don't have. AbstractAccess aa = AbstractAccess(ds, true, mca, 4, mcv, state); // The most common case is for there to be only one writer. This is the typical scenario // where the arguments all pushed onto the stack immediately before the call. If any of // the parameters are computed conditionally however, there may be more than one push // instruction responsible for writing the parameter. The value of the parameter should // already be an ITE expression, but we need to create multiple dependencies here as well. // Save the last of the latest writers for adding to the parameter definition. SgAsmX86Instruction *writer = NULL; // Now get the writers for just this one cell. There's been some recent email discussion // with Robb that this approach is defective, and there's a fix pending in ROSE. for (rose_addr_t waddr : writers.values()) { SgAsmInstruction* winsn = ds.get_insn(waddr); assert(winsn); writer = isSgAsmX86Instruction(winsn); assert(writer); SDEBUG << "Adding call dependency for " << debug_instruction(insn) << " to " << debug_instruction(writer) << LEND; // Now create the actual dependency. add_dependency_pair(insn, writer, aa); } ParameterDefinition* cpd = call_params.create_stack_parameter(p); if (cpd == NULL) { GFATAL << "Unable to create stack parameter " << p << " for offset [esp" << offset << "] for call: " << debug_instruction(insn) << LEND; } else { SymbolicValuePtr pointed_to = state->read_memory(mcv, arch_bits); // The writer variable is only _one_ of the writers. The parameter definition can't // currently store more than one evidence instruction, so I'm not sure it really matters, // but we should fix this by enhancing parameter definitions to have complete lists. cpd->set_stack_attributes(mcv, mca, writer, pointed_to); // Copy names, types and directions from the function descriptor parameter definition. cpd->copy_parameter_description(pd); //OINFO << " CPD:"; //cpd->debug(); //OINFO << " CPD:"; //fpd->debug(); } } } // This code was supposed to make "jmp [import]" have a non-NULL successor list. // Unfortunately, there no easy way to update successors on the import. I presume this // function (which is neve called) was left here as a reminder to eventually fix this. void update_jump_targets(const DescriptorSet& ds, SgAsmInstruction* insn) { rose_addr_t target = insn_get_jump_deref(insn); if (target != 0) { const ImportDescriptor* id = ds.get_import(target); if (id != NULL) { // There's NO add_successor()!!! } } } void DUAnalysis::update_function_delta() { // Because it's shorter than current_function... FunctionDescriptor* fd = current_function; // Our unified stack delta across all return instructions. StackDelta unified = StackDelta(0, ConfidenceNone); bool first = true; // This is the number on the RETN instruction and is also our expected stack delta. int64_t retn_size = 0; for (CFGVertex vertex : fd->get_return_vertices()) { const SgAsmBlock *block = convert_vertex_to_bblock(cfg, vertex); // Find the return instruction. const SgAsmStatementPtrList &insns = block->get_statementList(); assert(insns.size() > 0); SgAsmX86Instruction *last = isSgAsmX86Instruction(insns[insns.size() - 1]); if (last == NULL) { // An error should be reported later in the return block merging code. continue; } SDEBUG << "Last instruction in ret-block:" << debug_instruction(last) << LEND; StackDelta ld = sp_tracker.get_delta(last->get_address()); SDEBUG << "Stack delta going into last instruction: " << ld << LEND; // Not all blocks returned by get_return_blocks() end with return instructions. It also // includes blocks that jump (jmp or jcc) outside the current function. We'll start by // handling the more common case, blocks that end with a return. if (last->get_kind() == x86_ret) { // Get the number of bytes popped off the stack by the return instruction (not counting the // return address). SgAsmExpressionPtrList &ops = last->get_operandList()->get_operands(); if (ops.size() > 0) { SgAsmIntegerValueExpression *val = isSgAsmIntegerValueExpression(ops[0]); if (val != NULL) retn_size = val->get_absoluteValue(); } SDEBUG << "RET instruction pops " << retn_size << " additional bytes off the stack." << LEND; // Add the return size to the delta going into the return instruction. ld.delta += retn_size; } // This case is still confusing to me. Why would calls be return blocks in ANY case? else if (insn_is_call(last)) { // This workaround simply causes the merge code to do nothing. SWARN << "Block is a 'return' block, ending with a CALL instruction:" << debug_instruction(last) << LEND; ld.delta = unified.delta; ld.confidence = unified.confidence; } // This is the less obvious case. Blocks that end with an external jump. The right answer // here is to take the block delta at the jump instruction and add the delta that would have // occured if you had called to the target. else if (last->get_kind() == x86_jmp) { SDEBUG << "JMP instruction:" << debug_instruction(last) << LEND; // If we are a thunk, let our target function update our delta for us if (fd->is_thunk()) { SDEBUG << "Processing a thunk deferring stack update to thunk target" << LEND; return; } // Start by checking to see if this is a jump to a dereference of an address in the // import table. rose_addr_t target = insn_get_jump_deref(last); StackDelta td; if (target != 0) { const ImportDescriptor* id = ds.get_import(target); if (id != NULL) { td = id->get_stack_delta(); SDEBUG << "Branch target is to " << *id << LEND; } } // If that failed, maybe we're just a branch directly to some other function. else { target = insn_get_branch_target(last); td = sp_tracker.get_delta(target); } SDEBUG << "Branch target is: 0x" << std::hex << target << std::dec << " which has stack delta: " << td << LEND; // We can only be as confident as the delta we're branching to. if (td.confidence < ld.confidence) ld.confidence = td.confidence; ld.delta += td.delta; // And there's one more fix-up that's needed. A common case is thunks that jump to a // callee cleanup function. In this case, we've set retn_size to zero for the jump, // and yet our stack delta will be non-zero. This generates a warning later that is // incorrect. Although it may not be the perfect solution, we can prevent that by // setting retn_size here. We may need to check explicitly for thunks for this to // be more correct, or it may be fine like it is. if (retn_size == 0) retn_size = ld.delta; } else { // This message used to be at log level "error", but most of them are really just // warnings about "int3" instructions. We should probably fix that at the disassembly // level and then move this message back to "error" level. SWARN << "Unexpected instruction at end of basic block: " << debug_instruction(last) << LEND; ld.delta = 0; ld.confidence = ConfidenceNone; } // Merge the updated last instruction delta with the unified delta. if (first) { unified.delta = ld.delta; unified.confidence = ld.confidence; first = false; } else { if (ld.delta != unified.delta) { // Here's another case that should really be log level "error", but it's too common to // subject general users to at the present time. SWARN << "Function " << fd->address_string() << " has inconsistent return stack deltas: delta1=" << unified << " delta2=" << ld << LEND; unified.delta = 0; unified.confidence = ConfidenceNone; break; } else { if (ld.confidence < unified.confidence) unified.confidence = ld.confidence; } } } SDEBUG << "Final unified stack delta for function " << fd->address_string() << " is: " << unified << LEND; if (unified.confidence <= ConfidenceConfident && unified.delta != retn_size) { SWARN << "Unified stack delta for function " << fd->address_string() << " does not match RETN size of: " << retn_size << " unified stack delta was: " << unified << LEND; // We used to charge ahead, knowing that we were wrong... It seems wiser to use the RETN // size, at least until we have a better guessing algorithm, and a more reliable stack // delta system in general. unified.delta = retn_size; unified.confidence = ConfidenceGuess; } // In this case, we lost confidence in our stack delta, but in the end it appears to have // worked out ok, because the final stack delta matches our expected return size, and that's // what is most important. Rather than panicking upstream callers about our lack of // confidence, move the confidence back to "guess". if (unified.confidence == ConfidenceWrong && unified.delta == retn_size) { SDEBUG << "Restoring stack delta confidence for expected delta to 'guess'." << LEND; unified.confidence = ConfidenceGuess; } if (unified.confidence > ConfidenceNone) { fd->update_stack_delta(unified); } SDEBUG << "Final unified stack delta (reread) for function " << fd->address_string() << " is: " << fd->get_stack_delta() << LEND; } // DUPLICATIVE OF FunctionDescriptor::check_saved_register. :-( WRONG! WRONG! WRONG! // Is this a sterotypical case of a saved register? E.g. does this instruction only read the // value of a register so that we can subsequently restore it for the caller? bool DUAnalysis::saved_register(SgAsmX86Instruction* insn, const Definition& def) { // We're typically looking for the situation in which insn is a push instruction, and the // only other dependent is a pop instruction. The passed definition will be the register // that's being "saved", and the defining instructon should be NULL. // We might have already tested this, but testing it again will make this function useful in // more contexts. if (def.definer != NULL) return false; // This isn't really required, since we could be saving the register with a pair of moves, // but it'll be easier to debug I think if I start with push/pop pairs. if (insn->get_kind() != x86_push) return false; SDEBUG << "Checking for saved register for:" << debug_instruction(insn) << LEND; // We need a register descriptor for ESP, because it's special. RegisterDictionary regdict = ds.get_regdict(); RegisterDescriptor resp = regdict.lookup("esp"); const AbstractAccess* saveloc = NULL; for (const AbstractAccess& aa : get_writes(insn)) { // Of course the push updated ESP. We're not intersted in that. if (aa.is_reg(resp)) continue; if (saveloc == NULL && aa.is_mem()) { saveloc = &aa; continue; } SDEBUG << "Unexpected write to: " << aa.str() << " while checking for saved register" << debug_instruction(insn) << LEND; } // If we couldn't find a memory address that we wrote to, we've not a register save. if (saveloc == NULL) return false; SDEBUG << " --- Looking for write to" << saveloc->str() << LEND; const DUChain* deps = get_dependents(insn); if (deps == NULL) { SDEBUG << "No dependents_of entry for instruction: " << debug_instruction(insn) << LEND; return false; } for (const Definition& dx : *deps) { if (dx.access.same_location(*saveloc)) { // The definer field is the instruction that used the saved location on the stack. // Typically this is a pop instruction in the epilog. SDEBUG << " --- Found instruction using saveloc" << dx.access.str() << " | " << debug_instruction(dx.definer) << LEND; } } return false; } // Determine whether we return a value at all, and if it's the initial value of ECX. This // routine should probably continue to be part of the DUAnalysis class because it uses // input_state and output_state to do it's work. void DUAnalysis::analyze_return_code() { // Because it's shorter than current_function... FunctionDescriptor* fd = current_function; // If we're a thunk, then we should use whatever values our target has. if (fd->is_thunk()) { fd->propagate_thunk_info(); return; } // It is possible for input_state and output_state to be NULL if the function encountered // analysis failures that prevented the computation of a reasonably correct state. In those // cases, we're unable to analyze the return code, and should just return. if (output_state == NULL) { SDEBUG << "Function " << fd->address_string() << " has no output state. " << "Unable to analyze return code." << LEND; return; } if (input_state == NULL) { SDEBUG << "Function " << fd->address_string() << " has no input state. " << "Unable to analyze return code." << LEND; return; } // Otherwise we should analyze our own behavior to decide what we return. // Check to see whether we're returning the initial value of EAX in ECX. This is basically a // hack to make up for a lack of real calling convention detection. We have sufficient // calling convention data to improve this code now, but that's not my current goal. RegisterDescriptor eaxrd = ds.get_arch_reg("eax"); RegisterDescriptor ecxrd = ds.get_arch_reg("ecx"); SymbolicValuePtr retvalue = output_state->read_register(eaxrd); SymbolicValuePtr initial_ecx = input_state->read_register(ecxrd); // If EAX at the end of the function contains the same value as ECX at the beginning of the // function, then we're return ECX in EAX... bool returns_ecx = (*retvalue == *initial_ecx); STRACE << "Checking return values for function " << fd->address_string() << LEND; STRACE << "Returns ECX=" << returns_ecx << " EAX=" << retvalue->str() << " ECX=" << initial_ecx->str() << LEND; fd->set_returns_this_pointer(returns_ecx); // Emitted once per function... SDEBUG << "Returns thisptr=" << fd->get_returns_this_pointer() << " function=" << fd->address_string() << LEND; } // This function attempts to assign a value to the function summary output state variable. In // theory, it does this by merging all return blocks into a single consistent result. Wes' // original code appeared to have multiple problems, and there used to be a horrible // hodge-podge set of parameters passed, but apparently the function got cleaned up quite a lot // because now it only needs the state histories. Cory has not reviewed this function // carefully to see if it's actually correct yet, but it's certainly on the road to being // reasonable now. void DUAnalysis::update_output_state() { // Until we reach the end of this function, assume that we're malformed with respect to // having a well formed set of return blocks. output_valid = false; all_returns = false; // Because it's shorter than current_function... FunctionDescriptor* fd = current_function; // This list isn't really the return blocks, but rather all "out" edges in the control flow // graph which can contain jumps, and other strange things as a result of bad partitioning. std::vector<CFGVertex> out_vertices = fd->get_return_vertices(); // Create an empty output state when we don't know what else to do... In this case because // there are no out edges from the function... For example a jump to itself... This choice // can result in confusing downstream behavior, because the output state is not related to the input if (out_vertices.size() == 0) { SERROR << "Function " << fd->address_string() << " has no out edges." << LEND; auto ip = ds.get_partitioner().instructionProvider(); SymbolicRegisterStatePtr rstate = SymbolicRegisterState::instance(ip); SymbolicMemoryMapStatePtr mstate = SymbolicMemoryMapState::instance(); output_state = SymbolicState::instance(rstate, mstate); output_valid = false; return; } // Make a list of real return blocks that are worth merging into the outout state. std::vector<const SgAsmBlock*> ret_blocks; for (CFGVertex vertex : out_vertices) { const SgAsmBlock* block = convert_vertex_to_bblock(cfg, vertex); rose_addr_t addr = block->get_address(); // The call to at() should not throw unless our code is using the wrong CFG. const BlockAnalysis & analysis = blocks.at(addr); // Blocks that we've previously identified as "bad" are not valid return blocks. if (analysis.bad) continue; // The block also needs to have an entry in the state history to be useful. if (!analysis.output_state) continue; // Find the last instruction, and check to see if it's a return. const SgAsmStatementPtrList &insns = block->get_statementList(); if (insns.size() == 0) continue; SgAsmX86Instruction *last = isSgAsmX86Instruction(insns[insns.size() - 1]); if (last == NULL) { GERROR << "Last instruction in block " << addr_str(block->get_address()) << " was not an X86 instruction!" << LEND; continue; } SDEBUG << "Last instruction in ret-block:" << debug_instruction(last) << LEND; // Cory originally through that we should be ensuring stack delta concensus in this routine // around here, but it appears that is already implemented in update_function_delta(). // There's also some ambiguity here about what we should be doing for blocks that don't end // in return. The simple approach is to say that we should check valid_returns before // placing too much stock in the output_state, but a more robust approach would be to merge // external function states into our state, especially in cases where this function eitehr // returns a value or passes control to anotehr complete and well formed function. // If the block ends in a return instruction, add it to ret_blocks. if (last->get_kind() == x86_ret) { ret_blocks.push_back(block); } } // If no blocks ended with return instructions, return an empty output_state. if (ret_blocks.size() == 0) { SDEBUG << "Function " << fd->address_string() << " has no valid return blocks." << LEND; auto ip = ds.get_partitioner().instructionProvider(); SymbolicRegisterStatePtr rstate = SymbolicRegisterState::instance(ip); SymbolicMemoryMapStatePtr mstate = SymbolicMemoryMapState::instance(); output_state = SymbolicState::instance(rstate, mstate); output_valid = false; return; } // This means that we were able to merge output blocks. It does not mean that all out-edges // were merged, since some of them might have been non-return blocks. (See all_returns). output_valid = true; // If not all of the blocks got copied into the return blocks set, then we must have // discarded one or more for being bad code, or lacking return statements. That means that // there's something a wrong with the function, and we should only indicate that it has a // well formed return block structure if every block ended with a return. if (ret_blocks.size() == out_vertices.size()) all_returns = true; // Regardless of whether all or just some of the blocks ended in returns, we can still create // an output state. Do that now by beginning with the first state, and merging into it all // of the other states. There's no need to confirm that each address is in state histories, // because w did that when filtering the blocks earlier. rose_addr_t addr = ret_blocks[0]->get_address(); output_state = blocks.at(addr).output_state->sclone(); for (const SgAsmBlock *block : ret_blocks) { addr = block->get_address(); SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); output_state->merge(blocks.at(addr).output_state, rops.get(), SymbolicValue::incomplete(1)); } } void DUAnalysis::save_treenodes() { // Map for every treenode we every find SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); unique_treenodes_ = rops->unique_treenodes; memory_accesses_ = rops->memory_accesses; } void DUAnalysis::create_blocks() { // The entry block is always zero when it exists (see more detailed test in CDG constructor). static constexpr CFGVertex entry_vertex = 0; // Which control flow graph we're using here depends on how we were called. If we're using // the trimmed Pharos CFG, we won't even know about "bad" blocks, but if we're using the ROSE // CFG they'll still be in there. Either way, the block list will match the CFG. for (auto vertex : cfg_vertices(cfg)) { BlockAnalysis block = BlockAnalysis(*this, cfg, vertex, vertex == entry_vertex); blocks.emplace(block.get_address(), std::move(block)); } } // Print some information about a state to simplify debugging of the merge algorithm. // No effect on the analysis and enabled/disabled with STATE_DEBUG. void DUAnalysis::debug_state_merge(UNUSED const SymbolicStatePtr& cstate, UNUSED const std::string label) const { #ifdef STATE_DEBUG Semantics2::BaseSemantics::Formatter formatter; formatter.set_suppress_initial_values(true); formatter.set_show_latest_writers(false); formatter.set_show_properties(false); formatter.set_indentation_suffix("..."); if (cstate) { OINFO << "================= " << label << " ================" << LEND; // This is the magic syntax that makes the formatter work (most conveniently). OINFO << (*cstate+formatter); } else { OINFO << "============= " << label << " (NONE) =============" << LEND; } #endif } // Print some information about a state to simplify debugging of the merge algorithm. // No effect on the analysis and enabled/disabled with STATE_DEBUG. void DUAnalysis::debug_state_replaced(UNUSED const rose_addr_t baddr) const { #ifdef STATE_DEBUG Semantics2::BaseSemantics::Formatter formatter; formatter.set_suppress_initial_values(true); formatter.set_show_latest_writers(false); formatter.set_show_properties(false); formatter.set_indentation_suffix("..."); const BlockAnalysis & analysis = blocks.at(baddr); if (!analysis.output_state) { OINFO << "============ STATE BEING REPLACED (NONE) ===============" << LEND; } else { OINFO << "================ STATE BEING REPLACED ==================" << LEND; const SymbolicStatePtr fstate = analysis.output_state; OINFO << (*fstate+formatter); } DSTREAM << "Updating state history for " << addr_str(baddr) << LEND; #endif } SymbolicValuePtr DUAnalysis::get_eip_condition(const BlockAnalysis& pred_analysis, SgAsmBlock* pblock, const rose_addr_t bb_addr) { using namespace Rose::BinaryAnalysis; if (insn_is_call(last_x86insn_in_block(pblock))) { return SymbolicValue::treenode_instance(SymbolicExpr::makeBoolean(true)); } if (!pred_analysis.output_state) { return SymbolicValuePtr(); } SymbolicRegisterStatePtr eip_reg_state = pred_analysis.output_state->get_register_state(); if (!eip_reg_state) { return SymbolicValuePtr(); } // RegisterDescriptor eiprd = global_descriptor_set->get_arch_reg("eip"); RegisterDescriptor eiprd = ds.get_ip_reg(); SymbolicValuePtr eip_sv = eip_reg_state->read_register(eiprd); SymbolicValuePtr final_condition; std::vector<TreeNodePtr> condition_list; get_expression_condition(eip_sv, bb_addr, condition_list, final_condition); return final_condition; } // Merge all predecessor block's output states into a single state that becomes the input state // for the next this block. // Merge all predecessor block's output states into a single state that becomes the input state // for the next this block. SymbolicStatePtr DUAnalysis::merge_predecessors(CFGVertex vertex) { // The merged state that we return. SymbolicStatePtr cstate; SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); SgAsmBlock *bblock = get(boost::vertex_name, cfg, vertex); assert(bblock!=NULL); rose_addr_t baddr = bblock->get_address(); // The loop to merge predecessors. size_t merge_cnt = 0; size_t edge_cnt = 0; const BlockAnalysis & analysis = blocks.at(baddr); ResourceLimit merge_limit; for (SgAsmBlock *pblock : cfg_in_bblocks(cfg, vertex)) { rose_addr_t paddr = pblock->get_address(); DSTREAM << "Merging states for predecessor " << addr_str(paddr) << " into block " << addr_str(baddr) << LEND; const BlockAnalysis & pred_analysis = blocks.at(paddr); if (pred_analysis.output_state) { merge_cnt++; debug_state_merge(cstate, "STATE BEFORE MERGE"); debug_state_merge(pred_analysis.output_state, "STATE BEING MERGED"); if (cstate) { assert(edge_cnt > 0); cstate->merge(pred_analysis.output_state, rops.get(), analysis.conditions[edge_cnt - 1]); } else { cstate = pred_analysis.output_state->sclone(); } debug_state_merge(cstate, "STATE AFTER MERGE"); } ++edge_cnt; } DSTREAM << "Merging " << merge_cnt << " predecessors for block " << addr_str(baddr) << " in function " << current_function->address_string() << " (loop #" << func_limit.get_counter() << ") took " << merge_limit.get_relative_clock().count() << " seconds." << LEND; if (!cstate) { if (bblock != current_function->get_entry_block()) { GERROR << "Block " << addr_str(baddr) << " has no predecessors." << LEND; } // This is apparently not the same as input_state. :-( return initial_state; } return cstate; } // Merge the predecessor block's output state while *preserving* condtions. The other merge // predecessory routine uses fresh expressions for condtions rather than accumulating // conditions during analysis. This is performant and suitable for certain types of analysis, // but it will not work for other types of analysis SymbolicStatePtr DUAnalysis::merge_predecessors_with_conditions(CFGVertex vertex) { using namespace Rose::BinaryAnalysis; // The merged state that we return. SymbolicStatePtr cstate; SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); SgAsmBlock *bblock = get(boost::vertex_name, cfg, vertex); assert(bblock!=NULL); rose_addr_t baddr = bblock->get_address(); // The loop to merge predecessors. size_t merge_cnt = 0; BlockAnalysis & analysis = blocks.at(baddr); ResourceLimit merge_limit; // The entry condition treenode, which will include ancestors TreeNodePtr entry_cond_tnp; for (SgAsmBlock *pblock : cfg_in_bblocks(cfg, vertex)) { rose_addr_t paddr = pblock->get_address(); DSTREAM << "Merging states for predecessor " << addr_str(paddr) << " into block " << addr_str(baddr) << LEND; // Every direct predecessor must be and'd with the current analysis const BlockAnalysis & pred_analysis = blocks.at(paddr); if (pred_analysis.output_state) { merge_cnt++; debug_state_merge(cstate, "STATE BEFORE MERGE"); debug_state_merge(pred_analysis.output_state, "STATE BEING MERGED"); // This is a predecessor condition that must be conjoined with SymbolicValuePtr prev_cond = pred_analysis.entry_condition; SymbolicValuePtr eip_cond = get_eip_condition(pred_analysis, pblock, baddr); SymbolicValuePtr merge_cond = SymbolicValue::treenode_instance( SymbolicExpr::makeAnd(eip_cond->get_expression(), prev_cond->get_expression())); DSTREAM << "Merged condition addr=" << addr_str(baddr) << " cond=" << *merge_cond << LEND; if (cstate) { // There is a state, so it must be disjoined with the previous state entry_cond_tnp = SymbolicExpr::makeOr(merge_cond->get_expression(), entry_cond_tnp); SymbolicValuePtr inverted_merge_cond = SymbolicValue::treenode_instance( SymbolicExpr::makeInvert(merge_cond->get_expression())); cstate->merge(pred_analysis.output_state, rops.get(), inverted_merge_cond); } else { // First time through the loop the complete condition is the merge condition; on // subsequent iterations it will be disjoined entry_cond_tnp = merge_cond->get_expression(); cstate = pred_analysis.output_state->sclone(); } debug_state_merge(cstate, "STATE AFTER MERGE"); } } if (entry_cond_tnp) { DSTREAM << "Final condition addr=" << addr_str(baddr) << " cond=" << *entry_cond_tnp << LEND; analysis.entry_condition = SymbolicValue::treenode_instance(entry_cond_tnp); } DSTREAM << "Merging " << merge_cnt << " predecessors for block " << addr_str(baddr) << " in function " << current_function->address_string() << " (loop #" << func_limit.get_counter() << ") took " << merge_limit.get_relative_clock().count() << " seconds." << LEND; if (!cstate) { if (bblock != current_function->get_entry_block()) { GERROR << "Block " << addr_str(baddr) << " has no predecessors." << LEND; } // This is apparently not the same as input_state. :-( return initial_state; } return cstate; } // Process one basic block (identified by a CFG vertex). Merge the output states of the // predcessor blocks, evaulate the specified block, save the resulting state in the state // histories map, and mark the successors as pending. Return true is the output state changed // from the previous iteration. bool DUAnalysis::process_block_with_limit(CFGVertex vertex) { bool changed = false; SgAsmBlock *bblock = get(boost::vertex_name, cfg, vertex); assert(bblock!=NULL); rose_addr_t baddr = bblock->get_address(); BlockAnalysis& analysis = blocks.at(baddr); ResourceLimit block_limit; DSTREAM << "Starting iteration " << analysis.iterations << " for block " << addr_str(baddr) << " Reason " << bblock->reason_str("", bblock->get_reason()) << LEND; // Incoming rops for the block. This is the merge of all out policies of predecessor // vertices, with special consideration for the function entry block. SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); // There is now a setting to determine whether the conditions computed for basic blocks are // preserved and propogated when merging predecessors. Real conditions are needed for certain // classes of analysis, such as path finding where program state SymbolicStatePtr cstate = nullptr; if (propagate_conditions) { cstate = merge_predecessors_with_conditions(vertex); } else { cstate = merge_predecessors(vertex); } analysis.input_state = cstate->sclone(); rops->currentState(cstate); analysis.analyze(true); // If output of this block changed from what we previously calculated, then mark all its // children as pending. if (!(analysis.output_state && cstate->equals(analysis.output_state))) { changed = true; debug_state_merge(cstate, "STATE AFTER EXECUTION"); debug_state_replaced(baddr); analysis.output_state = cstate; debug_state_merge(analysis.output_state, "STATE AFTER UPDATE"); for (SgAsmBlock *sblock : cfg_out_bblocks(cfg, vertex)) { rose_addr_t saddr = sblock->get_address(); blocks.at(saddr).pending = true; DSTREAM << "Marking successor block " << addr_str(saddr) << " for revisting." << LEND; } } DSTREAM << "Analysis of basic block " << addr_str(baddr) << " in function " << current_function->address_string() << " (loop #" << func_limit.get_counter() << ") took " << block_limit.get_relative_clock().count() << " seconds." << LEND; DSTREAM << "========================================================================" << LEND; return changed; } // This must be called, post block analysis // void // DUAnalysis::add_edge_conditions() { // struct EdgeCondition { // SymbolicValuePtr condition; // }; // using Cfg2 = boost::adjacency_list<boost::vecS, boost::vecS, // boost::bidirectionalS, // boost::vertex_name_t, EdgeCondition>; // using Cfg2Vertex = boost::graph_traits<Cfg2>::vertex_descriptor; // using Cfg2VertexIter = boost::graph_traits<Cfg2>::vertex_iterator; // using Cfg2OutEdgeIter = boost::graph_traits<Cfg2>::out_edge_iterator; // using Cfg2InEdgeIter = boost::graph_traits<Cfg2>::in_edge_iterator; // using Cfg2Edge = boost::graph_traits<Cfg2>::edge_descriptor; // using Cfg2EdgeIter = boost::graph_traits<Cfg2>::edge_iterator; // Cfg2 cfg2; // boost::copy_graph(cfg, cfg2); // std::pair<Cfg2EdgeIter, Cfg2EdgeIter> edge_iter_range = boost::edges(cfg2); // for(Cfg2EdgeIter edge_iter = edge_iter_range.first; edge_iter != edge_iter_range.second; ++edge_iter) { // auto edge = *edge_iter; // Cfg2Vertex sv = boost::source(edge, cfg2); // SgAsmBlock *src_bb = isSgAsmBlock(boost::get(boost::vertex_name, cfg2, sv)); // Cfg2Vertex tv = boost::target(edge, cfg2); // SgAsmBlock *tgt_bb = isSgAsmBlock(boost::get(boost::vertex_name, cfg2, tv)); // BlockAnalysis src_analysis = blocks.at(src_bb->get_address()); // BlockAnalysis tgt_analysis = blocks.at(tgt_bb->get_address()); // SymbolicRegisterStatePtr tgt_reg_state = tgt_analysis.output_state->get_register_state(); // SymbolicRegisterStatePtr src_reg_state = src_analysis.output_state->get_register_state(); // if (tgt_reg_state && src_reg_state) { // RegisterDescriptor eiprd = ds.get_arch_reg("eip"); // SymbolicValuePtr src_eip = src_reg_state->read_register(eiprd); // SymbolicValuePtr tgt_eip = tgt_reg_state->read_register(eiprd); // OINFO << "\nThe edge " << addr_str(src_bb->get_address()) << " -> " << addr_str(tgt_bb->get_address()) // << " is " << *(src_eip->get_expression()) << LEND; // cfg2[*edge_iter].condition = src_eip; // } // } // } // This is the supposedly intermediate basic block analysis for each block in a function const BlockAnalysisMap& DUAnalysis::get_block_analysis() const { return blocks; } // Loop over the control flow graph several times, processing each basic block and keeping a // list of which blocks need to bew revisited. This code need to be rewritten so that is uses // a proper worklist. LimitCode DUAnalysis::loop_over_cfg() { // Because it's shorter than current_function... FunctionDescriptor* & fd = current_function; // add_edge_conditions(); // Now that the control flow graph has been cleaned up, we can construct a flow order list of // the blocks reachable from the entry point. This graph should now be internally consistent. std::vector<CFGVertex> flowlist = fd->get_vertices_in_flow_order(); if (blocks.size() != flowlist.size()) { GWARN << "Function " << fd->address_string() << " includes only " << flowlist.size() << " of " << num_vertices(cfg) << " blocks in the control flow." << LEND; } SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); initial_state = rops->get_sstate(); // Cory thinks the clone here is wrong, because it won't include subsequent "updates" to the // initial state for values that are created as we read them. input_state = rops->get_sstate()->sclone(); // Solve the flow equation iteratively to find out what's defined at the end of every basic // block. The policies[] stores this info for each vertex. bool changed = true; LimitCode rstatus = func_limit.check(); while (changed && rstatus == LimitSuccess) { changed = false; func_limit.increment_counter(); SDEBUG << "loop try #" << func_limit.get_counter() << LEND; for (auto vertex : flowlist) { SgAsmBlock *bblock = convert_vertex_to_bblock(cfg, vertex); assert(bblock!=NULL); rose_addr_t baddr = bblock->get_address(); // The call to at() should not throw unless our code is using the wrong CFG. BlockAnalysis& analysis = blocks.at(baddr); // If the block is a "bad" block, then skip it. if (analysis.bad) continue; // If this block is in the processed list (meaning we've processed it before) and it it // is no longer pending then continue with the next basic block. This is a very common // case and we could probably simplify the logic some by adding and removing entries // from a worklist that would prevent us from being in this loop in the first place. if (analysis.pending == false) continue; // If we're really pending, but we've visited this block more than max iteration times, // then we should give up even though it produces incorrect answers. Report the condition // as an error so that the user knows something went wrong. if (analysis.iterations >= MAX_LOOP) { // Cory thinks that this should really be an error, but it's still too common to be // considered a true error, and so he moved it to warning importance. SWARN << "Maximum iterations (" << MAX_LOOP << ") exceeded for block " << addr_str(baddr) << " in function " << fd->address_string() << LEND; // Setting the block so that it is not pending should help prevent the error message // from being generated repeatedly for the same block. analysis.pending = false; continue; } // We're processing the block now, so it's no longer pending (and we've interated once more). analysis.pending = false; analysis.iterations++; // Process a block with a resource limit, and if it changed our status, update our boolean. if (process_block_with_limit(vertex)) changed = true; rstatus = func_limit.check(); // The intention is that rstatus and changed would be the only clauses on the while condition. if (rstatus != LimitSuccess) { SERROR << "Function " << fd->address_string() << " " << func_limit.get_message() << LEND; // Break out of the loop of basic blocks. break; } } // foreach block in flow list... // Cory would like for this to become: func_limit.report("Func X took: "); ? SDEBUG << "Flow equation loop #" << func_limit.get_counter() << " for " << fd->address_string() << " took " << func_limit.get_relative_clock().count() << " seconds." << LEND; } if (rstatus != LimitSuccess) { SERROR << "Function analysis convergence failed for: " << fd->address_string() << LEND; } GDEBUG << "Analysis of function " << fd->address_string() << " took " << func_limit.get_relative_clock().count() << " seconds." << LEND; if (GDEBUG) { for (auto& bpair : blocks) { const BlockAnalysis& block = bpair.second; GDEBUG << " Basic block: " << block.address_string() << " in function " << fd->address_string() << " took " << block.iterations << " iterations." << LEND; } } return rstatus; } LimitCode DUAnalysis::solve_flow_equation_iteratively() { // Start by checking absolute limits. LimitCode rstatus = func_limit.check(); if (rstatus != LimitSuccess) return rstatus; // This limits the number of times we complain about discarded expressions. It's a naughty // global variable. Go read about it in SymbolicValue::scopy(). discarded_expressions = 0; // This analysis requires the filtered version of the control flow graph because we don't // know how to merge predecessors in cases where there are none. cfg = current_function->get_pharos_cfg(); // Create a BlockAnalysis object for every basic block in function. Create conditions for // each of the predecessor edges, and analyze the blocks to see if they look like bad code. create_blocks(); // Set the stack delta of the first instruction to zero, with confidence Certain (by definition). sp_tracker.update_delta(current_function->get_address(), StackDelta(0, ConfidenceCertain), sd_failures); // Do most of the real work. Visit each block in the control flow graph, possibly multiple // times, merging predecessor states, emulating each block, and updating state histories. rstatus = loop_over_cfg(); // Look at all of the return blocks, and bring them together into a unified stack delta. update_function_delta(); // Merge all states at each return block into a single unified output state. update_output_state(); // Determine whether we return a value at all, and if it's the initial value of ECX. analyze_return_code(); // Currently the decision on whether to analyze tree node types depends on a command line argument to // prevent a dependancy on prolog save_treenodes(); // Free the resources consumed by the ROSE emulation environment. dispatcher.reset(); return rstatus; } // Convert a list-based memory state into a map-based memory state. SymbolicMemoryMapStatePtr convert_memory_list_to_map( SymbolicMemoryListStatePtr list_mem, size_t max_aliases, bool give_up); LimitCode DUAnalysis::analyze_basic_blocks_independently() { // Start by checking absolute limits. LimitCode rstatus = func_limit.check(); if (rstatus != LimitSuccess) return rstatus; // Because it's shorter than current_function... FunctionDescriptor* & fd = current_function; // In analyze_flow_equation_iteratively() we discarded blocks with various problems such as // not having predecessors. We don't want that filter here because we're computing per-block // semantics, and can do so even if we don't understand how they fit into the control flow. // Most of the otehr fields in the function descriptor are based on the Pharos (filtered) // control flow graph, so some extra caution is required qhen using this CFG. cfg = fd->get_rose_cfg(); // Create a BlockAnalysis object for every basic block in function. Create conditions for // each of the predecessor edges, and analyze the blocks to see if they look like bad code. create_blocks(); // Set the stack delta of the first instruction to zero, with confidence Certain (by definition). sp_tracker.update_delta(current_function->get_address(), StackDelta(0, ConfidenceCertain), sd_failures); // Instead of loop_over_cfg(), this algorithm is going to be simpler, so it's right here. // The RISC operators were built in the constructor based on how much rigor we wanted. SymbolicRiscOperatorsPtr rops = SymbolicRiscOperators::promote(dispatcher->get_operators()); // Visit each basic block in the function without regard to the ordering in the control flow, // or even whether the blocks are connected to the control flow. for (auto vertex : cfg_vertices(cfg)) { SgAsmBlock *bblock = convert_vertex_to_bblock(cfg, vertex); assert(bblock!=NULL); rose_addr_t baddr = bblock->get_address(); BlockAnalysis& analysis = blocks.at(baddr); // If the block is a "bad" block, then skip it. if (analysis.bad) continue; // Create a basic block limit just for tracking time. Perhaps this limit should really be // moved to analyze, so it can be evaluated after each instruction? ResourceLimit block_limit; GDEBUG << "Starting analysis of block " << addr_str(baddr) << " Reason " << bblock->reason_str("", bblock->get_reason()) << LEND; analysis.analyze(false); const SymbolicStatePtr& cstate = rops->get_sstate(); GDEBUG << "-----------------------------------------------------------------" << LEND; GDEBUG << "Machine state before conversion from list to map." << LEND; GDEBUG << "-----------------------------------------------------------------" << LEND; GDEBUG << *cstate; // save the block output state (current state) analysis.output_state = cstate; GDEBUG << "-----------------------------------------------------------------" << LEND; // const SymbolicMemoryListStatePtr& list_mem = SymbolicMemoryListState::promote(cstate->memoryState()); // SymbolicMemoryMapStatePtr map_mem = convert_memory_list_to_map(list_mem, 5, false); GDEBUG << "-----------------------------------------------------------------" << LEND; GDEBUG << "Memory state after conversion from list to map." << LEND; GDEBUG << "-----------------------------------------------------------------" << LEND; // GDEBUG << *map_mem; GDEBUG << "Analysis of basic block " << addr_str(baddr) << " in function " << current_function->address_string() << ", took " << block_limit.get_relative_clock().count() << " seconds." << LEND; } return rstatus; } bool get_expression_condition(SymbolicValuePtr sv, rose_addr_t next_addr, std::vector<TreeNodePtr>& condition_list, SymbolicValuePtr& final_condition, bool direction) { using namespace Rose::BinaryAnalysis; TreeNodePtr tn = sv->get_expression(); // We are at a leaf, is it the target? if (tn->isLeafNode() && tn->isLeafNode()->isNumber()) { rose_addr_t node_addr = address_from_node(tn->isLeafNode()); if (next_addr == node_addr) { // if we came here on the false branch, invert the last condition if (false==direction) { TreeNodePtr& last_condition = condition_list.back(); last_condition = SymbolicExpr::makeInvert(last_condition); } final_condition = SymbolicValue::treenode_instance(SymbolicExpr::makeBoolean(true)); return true; } final_condition = SymbolicValue::treenode_instance(SymbolicExpr::makeBoolean(false)); return false; } const InternalNodePtr in = tn->isInteriorNode(); // If an ITE, then recurse through the branches if (in && in->getOperator() == SymbolicExpr::OP_ITE) { const TreeNodePtrVector& children = in->children(); // Camee from a false branch, so invert the last controlling condition if (false == direction && !condition_list.empty()) { TreeNodePtr& last_condition = condition_list.back(); last_condition = SymbolicExpr::makeInvert(last_condition); } // Save this condition on the path and continue the search through the subtrees condition_list.push_back(children[0]); if (get_expression_condition(SymbolicValue::treenode_instance(children[1]), next_addr, condition_list, final_condition, true) || get_expression_condition(SymbolicValue::treenode_instance(children[2]), next_addr, condition_list, final_condition, false)) { // found the target in a subtree, now conjoin the path TreeNodePtr and_cond = condition_list.at(0); if (condition_list.size()>1) { size_t i=1; while (i<condition_list.size()) { and_cond = SymbolicExpr::makeAnd(and_cond, condition_list.at(i)); i++; } } final_condition = SymbolicValue::treenode_instance(and_cond); return true; } } // next address not in this subtree if (!condition_list.empty()) condition_list.pop_back(); // the default is to simply return an incomplete expression. final_condition = SymbolicValue::incomplete(1); return false; } } // Namespace pharos /* Local Variables: */ /* mode: c++ */ /* fill-column: 95 */ /* comment-column: 0 */ /* End: */
45.282147
133
0.666354
[ "object", "vector", "transform" ]
6d9598395c81620e2bd3d844aa7ddd443148a50c
7,057
hpp
C++
inference-engine/thirdparty/ade/common/include/util/memory_range.hpp
mypopydev/dldt
8cd639116b261adbbc8db860c09807c3be2cc2ca
[ "Apache-2.0" ]
3
2019-07-08T09:03:03.000Z
2020-09-09T10:34:17.000Z
inference-engine/thirdparty/ade/common/include/util/memory_range.hpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
3
2020-11-13T18:59:18.000Z
2022-02-10T02:14:53.000Z
inference-engine/thirdparty/ade/common/include/util/memory_range.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 // // SPDX-License-Identifier: Apache-2.0 // #ifndef UTIL_MEMORYRANGE_HPP #define UTIL_MEMORYRANGE_HPP #include <type_traits> #include <cstring> //size_t #include <algorithm> #include <array> #include "util/type_traits.hpp" #include "util/assert.hpp" namespace util { /// Non owning view over the data in another container /// T can be cv-qualified object or cv-qualified void template<typename T> struct MemoryRange { static_assert(std::is_object<T>::value || std::is_void<T>::value, "Invalid type"); using value_type = T; T* data = nullptr; size_t size = 0; MemoryRange() = default; MemoryRange(const MemoryRange&) = default; MemoryRange& operator=(const MemoryRange&) = default; MemoryRange(T* data_, size_t size_): data(data_), size(size_) { ASSERT((nullptr != data) || (0 == size)); //size must be 0 for null data } /// Slice view /// if T is void start and newSize addressable in bytes /// otherwise in elements MemoryRange<T> Slice(size_t start, size_t newSize) const { ASSERT(nullptr != data); ASSERT((start + newSize) <= size); using temp_t = typename std::conditional<std::is_void<T>::value, char, T>::type; return MemoryRange<T>(static_cast<temp_t*>(data) + start, newSize); } template<typename Dummy = void> typename std::enable_if<!std::is_void<T>::value, typename std::conditional<true, T*, Dummy>::type >::type begin() { return data; } template<typename Dummy = void> typename std::enable_if<!std::is_void<T>::value, typename std::conditional<true, T*, Dummy>::type >::type end() { return data + size; } template<typename Dummy = void> typename std::enable_if<!std::is_void<T>::value, typename std::conditional<true, const T*, Dummy>::type >::type begin() const { return data; } template<typename Dummy = void> typename std::enable_if<!std::is_void<T>::value, typename std::conditional<true, const T*, Dummy>::type >::type end() const { return data + size; } template<typename Dummy = T> // hack for sfinae typename std::enable_if<(sizeof(Dummy) > 0), Dummy& >::type operator[](size_t index) { ASSERT(index < size); return data[index]; } template<typename Dummy = T> // hack for sfinae typename std::enable_if<(sizeof(Dummy) > 0), const Dummy& >::type operator[](size_t index) const { ASSERT(index < size); return data[index]; } template<typename NewT> MemoryRange<NewT> reinterpret() const { const size_t elem_size = sizeof(util::conditional_t< std::is_void<T>::value, char, T >); const size_t elem_size_new = sizeof(util::conditional_t< std::is_void<NewT>::value, char, NewT >); const size_t newSize = (size * elem_size) / elem_size_new; return MemoryRange<NewT>(static_cast<NewT*>(data), newSize); } template<typename Dummy = T> // hack for sfinae typename std::enable_if<(sizeof(Dummy) > 0), Dummy& >::type front() { ASSERT(size > 0); return data[0]; } template<typename Dummy = T> // hack for sfinae typename std::enable_if<(sizeof(Dummy) > 0), const Dummy& >::type front() const { ASSERT(size > 0); return data[0]; } template<typename Dummy = T> // hack for sfinae typename std::enable_if<(sizeof(Dummy) > 0), Dummy& >::type back() { ASSERT(size > 0); return data[size - 1]; } template<typename Dummy = T> // hack for sfinae typename std::enable_if<(sizeof(Dummy) > 0), const Dummy& >::type back() const { ASSERT(size > 0); return data[size - 1]; } bool empty() const { return 0 == size; } void popFront() { ASSERT(!empty()); *this = Slice(1, size - 1); } }; template<typename T> inline MemoryRange<T> memory_range(T* ptr, const std::size_t size) { return {ptr, size}; } template<typename T, std::size_t size_> inline MemoryRange<T> memory_range(T (&range)[size_]) { return memory_range(&range[0], size_); } template<typename T, std::size_t size_> inline MemoryRange<T> memory_range(std::array<T, size_>& arr) { return memory_range(arr.data(), size_); } template<typename T> inline T* data(const MemoryRange<T>& range) { return range.data; } template<typename T, std::size_t size> inline T* data(T (&range)[size]) { return &(range[0]); } template<typename T> inline std::size_t size(const MemoryRange<T>& range) { return range.size; } template<typename T, std::size_t size_> inline std::size_t size(T (&)[size_]) { return size_; } template<typename T> inline bool operator==(const MemoryRange<T>& range, std::nullptr_t) { return range.data == nullptr; } template<typename T> inline bool operator==(std::nullptr_t, const MemoryRange<T>& range) { return range.data == nullptr; } template<typename T> inline bool operator!=(const MemoryRange<T>& range, std::nullptr_t) { return range.data != nullptr; } template<typename T> inline bool operator!=(std::nullptr_t, const MemoryRange<T>& range) { return range.data != nullptr; } template<typename T> inline MemoryRange<T> slice(const MemoryRange<T>& range, const std::size_t start, const std::size_t newSize) { return range.Slice(start, newSize); } template<typename T, std::size_t size> inline MemoryRange<T> slice(T (&range)[size], const std::size_t start, const std::size_t newSize) { return memory_range(&range[0], size).Slice(start, newSize); } template<typename SrcRange, typename DstRange> inline auto raw_copy(const SrcRange& src, DstRange&& dst) -> decltype(slice(dst, size(src), size(dst) - size(src))) { static_assert(std::is_same< util::decay_t<decltype(*data(src))>, util::decay_t<decltype(*data(dst))> >::value, "Types must be same"); static_assert(std::is_pod< util::decay_t<decltype(*data(src))> >::value, "Types must be pod"); static_assert(sizeof(src[std::size_t{}]) == sizeof(dst[std::size_t{}]), "Size mismatch"); const auto src_size = size(src); const auto dst_size = size(dst); ASSERT(nullptr != src); ASSERT(nullptr != dst); ASSERT(dst_size >= src_size); auto src_data = data(src); auto dst_data = data(dst); // Check overlap ASSERT(((src_data < dst_data) || (src_data >= (dst_data + dst_size))) && ((dst_data < src_data) || (dst_data >= (src_data + src_size)))); std::copy_n(src_data, src_size, dst_data); return slice(dst, size(src), size(dst) - size(src)); } inline MemoryRange<void> raw_copy(const MemoryRange<void>& src, MemoryRange<void> dst) { return raw_copy(src.reinterpret<const char>(), dst.reinterpret<char>()).reinterpret<void>(); } inline MemoryRange<void> raw_copy(const MemoryRange<const void>& src, MemoryRange<void> dst) { return raw_copy(src.reinterpret<const char>(), dst.reinterpret<char>()).reinterpret<void>(); } } // util #endif // UTIL_MEMORYRANGE_HPP
26.935115
114
0.65056
[ "object" ]
6d9e622781bc2c79cf1cffd71f149e7bc64b115f
6,718
cc
C++
chrome/browser/apps/app_service/file_utils_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/apps/app_service/file_utils_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/apps/app_service/file_utils_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.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 "chrome/browser/apps/app_service/file_utils.h" #include <memory> #include <string> #include <vector> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/strings/strcat.h" #include "chrome/browser/ash/file_manager/app_id.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "net/base/filename_util.h" #include "storage/browser/file_system/external_mount_points.h" #include "storage/browser/file_system/file_system_url.h" #include "storage/common/file_system/file_system_util.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "url/gurl.h" #include "url/origin.h" #include "url/url_constants.h" namespace apps { namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; class FileUtilsTest : public ::testing::Test { public: void SetUp() override { testing::Test::SetUp(); profile_manager_ = std::make_unique<TestingProfileManager>( TestingBrowserProcess::GetGlobal()); ASSERT_TRUE(profile_manager_->SetUp()); profile_ = profile_manager_->CreateTestingProfile("testing_profile"); ASSERT_TRUE( storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem( mount_name_, storage::FileSystemType::kFileSystemTypeExternal, storage::FileSystemMountOption(), base::FilePath(fs_root_))); ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); } void TearDown() override { ASSERT_TRUE( storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem( mount_name_)); profile_manager_->DeleteAllTestingProfiles(); profile_ = nullptr; profile_manager_.reset(); } TestingProfile* GetProfile() { return profile_; } base::FilePath GetTempDir() { return scoped_temp_dir_.GetPath(); } // FileUtils explicitly relies on ChromeOS Files.app for files manipulation. const url::Origin GetFileManagerOrigin() { return url::Origin::Create(extensions::Extension::GetBaseURLFromExtensionId( file_manager::kFileManagerAppId)); } // Converts the given virtual |path| to a file system URL. Uses test file // system type. storage::FileSystemURL ToTestFileSystemURL(const std::string& path) { return storage::FileSystemURL::CreateForTest( blink::StorageKey(GetFileManagerOrigin()), storage::FileSystemType::kFileSystemTypeTest, base::FilePath(path)); } // For a given |root| converts the given virtual |path| to a GURL. GURL ToGURL(const base::FilePath& root, const std::string& path) { const std::string abs_path = root.Append(path).value(); return GURL(base::StrCat({url::kFileSystemScheme, ":", GetFileManagerOrigin().Serialize(), abs_path})); } protected: const std::string mount_name_ = "TestMountName"; const std::string fs_root_ = "/path/to/test/filesystemroot"; private: content::BrowserTaskEnvironment task_environment_; std::unique_ptr<TestingProfileManager> profile_manager_; base::ScopedTempDir scoped_temp_dir_; TestingProfile* profile_; }; TEST_F(FileUtilsTest, GetFileSystemURL) { std::vector<GURL> url_list; std::vector<storage::FileSystemURL> fsurl_list; // Case 1: url_list is empty. fsurl_list = GetFileSystemURL(GetProfile(), url_list); EXPECT_THAT(fsurl_list, IsEmpty()); // Case 2: url_list contains a GURL. const std::string path = "Documents/foo.txt"; url_list.push_back(ToGURL(base::FilePath(storage::kTestDir), path)); fsurl_list = GetFileSystemURL(GetProfile(), url_list); EXPECT_THAT(fsurl_list, ElementsAre(ToTestFileSystemURL(path))); } TEST_F(FileUtilsTest, GetFileSystemUrls) { std::vector<GURL> url_list; std::vector<base::FilePath> fp_list; // Case 1: fp_list is empty. url_list = GetFileSystemUrls(GetProfile(), fp_list); EXPECT_THAT(url_list, IsEmpty()); // Case 2: fp_list contain some paths. const std::string path = "Images/foo.jpg"; fp_list.push_back(base::FilePath(fs_root_).Append(path)); url_list = GetFileSystemUrls(GetProfile(), fp_list); // Given a list of absolute file paths, return a list of filesystem:// URLs // that use the kFileSystemTypeExternal type with Files Manager's origin. // TODO(crbug/1203961): The use of Files Manager origin in these URLs is // probably incorrect and should be revisited. EXPECT_THAT( url_list, ElementsAre(ToGURL( base::FilePath(storage::kExternalDir).Append(mount_name_), path))); // Case 3: paths not originating in a known root are ignored. fp_list.push_back(base::FilePath("/not/a/known/root").Append(path)); url_list = GetFileSystemUrls(GetProfile(), fp_list); // Still just one path corresponding to foo.jpg under a known root. EXPECT_THAT( url_list, ElementsAre(ToGURL( base::FilePath(storage::kExternalDir).Append(mount_name_), path))); } TEST_F(FileUtilsTest, GetFileUrls) { constexpr char kTestData[] = "testing1234"; base::FilePath test_file = GetTempDir().AppendASCII("test.txt"); ASSERT_EQ(static_cast<int>(base::size(kTestData)), base::WriteFile(test_file, kTestData, base::size(kTestData))); std::vector<GURL> url_list; std::vector<base::FilePath> fp_list; // fp_list is empty. url_list = GetFileUrls(fp_list); EXPECT_THAT(url_list, IsEmpty()); // fp_list containing test profile path should work with file: url. fp_list.push_back(test_file); url_list = GetFileUrls(fp_list); base::FilePath url_path; net::FileURLToFilePath(url_list.at(0), &url_path); EXPECT_EQ(url_path, test_file); } TEST_F(FileUtilsTest, GetSingleFileSystemURL) { GURL url; storage::FileSystemURL fsurl; const std::string path = "Documents/foo.txt"; url = ToGURL(base::FilePath(storage::kTestDir), path); fsurl = GetFileSystemURL(GetProfile(), url); EXPECT_EQ(fsurl, ToTestFileSystemURL(path)); } TEST_F(FileUtilsTest, GetSingleFileSystemUrl) { GURL url; base::FilePath file_path; const std::string path = "Images/foo.jpg"; file_path = base::FilePath(fs_root_).Append(path); url = GetFileSystemUrl(GetProfile(), file_path); EXPECT_EQ( url, ToGURL(base::FilePath(storage::kExternalDir).Append(mount_name_), path)); } } // namespace } // namespace apps
34.989583
80
0.732659
[ "vector" ]
6d9e6796a56c24072d4532ef637f4cd8d80726fc
6,266
cpp
C++
src/Design/ModuleInstance.cpp
sjkelly/Surelog
792de2fcc5f51d233dbb677ca6f1a1a05e483483
[ "Apache-2.0" ]
null
null
null
src/Design/ModuleInstance.cpp
sjkelly/Surelog
792de2fcc5f51d233dbb677ca6f1a1a05e483483
[ "Apache-2.0" ]
null
null
null
src/Design/ModuleInstance.cpp
sjkelly/Surelog
792de2fcc5f51d233dbb677ca6f1a1a05e483483
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Alain Dargelas Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * File: ModuleInstance.cpp * Author: alain * * Created on October 16, 2017, 10:48 PM */ #include "Design/ModuleInstance.h" #include <iostream> #include <string> #include "Design/FileContent.h" #include "ElaboratorListener.h" #include "Library/Library.h" #include "SourceCompile/SymbolTable.h" #include "clone_tree.h" #include "uhdm.h" using namespace SURELOG; using namespace UHDM; ModuleInstance::ModuleInstance(DesignComponent* moduleDefinition, const FileContent* fileContent, NodeId nodeId, ModuleInstance* parent, std::string instName, std::string modName) : ValuedComponentI(parent, moduleDefinition), m_definition(moduleDefinition), m_fileContent(fileContent), m_nodeId(nodeId), m_parent(parent), m_instName(instName), m_netlist(nullptr) { if (m_definition == NULL) { m_instName = modName + "&" + instName; } } Value* ModuleInstance::getValue(const std::string& name, ExprBuilder& exprBuilder) const { Value* sval = nullptr; if (getComplexValue(name)) { return nullptr; } ModuleInstance* instance = (ModuleInstance*)this; while (instance) { if (instance->m_netlist) { UHDM::VectorOfparam_assign* param_assigns = instance->m_netlist->param_assigns(); if (param_assigns) { for (param_assign* param : *param_assigns) { if (param && param->Lhs()) { const std::string& param_name = param->Lhs()->VpiName(); if (param_name == name) { const any* exp = param->Rhs(); if (exp && exp->UhdmType() == uhdmconstant) { constant* c = (constant*)exp; sval = exprBuilder.fromVpiValue(c->VpiValue(), c->VpiSize()); } break; } } } } } if (instance->getType() != slModule_instantiation) instance = instance->getParent(); else instance = nullptr; } if (sval == nullptr) { sval = ValuedComponentI::getValue(name); } if (m_definition && (sval == nullptr)) { UHDM::VectorOfparam_assign* param_assigns = m_definition->getParam_assigns(); if (param_assigns) { for (param_assign* param : *param_assigns) { const std::string& param_name = param->Lhs()->VpiName(); if (param_name == name) { const any* exp = param->Rhs(); if (exp->UhdmType() == uhdmconstant) { constant* c = (constant*)exp; sval = exprBuilder.fromVpiValue(c->VpiValue(), c->VpiSize()); } break; } } } } return sval; } ModuleInstance::~ModuleInstance() { delete m_netlist; for (unsigned int index = 0; index < m_allSubInstances.size(); index++) { delete m_allSubInstances[index]; } } void ModuleInstance::addSubInstance(ModuleInstance* subInstance) { m_allSubInstances.push_back(subInstance); } ModuleInstance* ModuleInstanceFactory::newModuleInstance( DesignComponent* moduleDefinition, const FileContent* fileContent, NodeId nodeId, ModuleInstance* parent, std::string instName, std::string modName) { return new ModuleInstance(moduleDefinition, fileContent, nodeId, parent, instName, modName); } VObjectType ModuleInstance::getType() { return m_fileContent->Type(m_nodeId); } VObjectType ModuleInstance::getModuleType() { VObjectType type = (VObjectType)0; if (m_definition) { type = m_definition->getType(); } return type; } unsigned int ModuleInstance::getLineNb() { return m_fileContent->Line(m_nodeId); } SymbolId ModuleInstance::getFullPathId(SymbolTable* symbols) { return symbols->registerSymbol(getFullPathName()); } SymbolId ModuleInstance::getInstanceId(SymbolTable* symbols) { return symbols->registerSymbol(getInstanceName()); } SymbolId ModuleInstance::getModuleNameId(SymbolTable* symbols) { return symbols->registerSymbol(getModuleName()); } std::string ModuleInstance::getFullPathName() { std::string path; ModuleInstance* tmp = this; std::vector<std::string> nibbles; while (tmp) { nibbles.push_back(tmp->getInstanceName()); tmp = tmp->getParent(); } for (int i = nibbles.size() - 1; i >= 0; i--) { path += nibbles[i]; if (i > 0) { path += "."; } } return path; } unsigned int ModuleInstance::getDepth() { unsigned int depth = 0; ModuleInstance* tmp = this; while (tmp) { tmp = tmp->getParent(); depth++; } return depth; } std::string ModuleInstance::getInstanceName() { if (m_definition == NULL) { std::string name = m_instName.substr(m_instName.find("&", 0, 1) + 1, m_instName.size()); return name; } else { return m_instName; } } std::string ModuleInstance::getModuleName() { if (m_definition == NULL) { std::string name = m_instName.substr(0, m_instName.find("&", 0, 1)); return name; } else { return m_definition->getName(); } } void ModuleInstance::overrideParentChild(ModuleInstance* parent, ModuleInstance* interm, ModuleInstance* child) { if (parent != this) return; child->m_parent = this; std::vector<ModuleInstance*> children; for (unsigned int i = 0; i < m_allSubInstances.size(); i++) { if (m_allSubInstances[i] == interm) { for (unsigned int j = 0; j < interm->m_allSubInstances.size(); j++) { children.push_back(interm->m_allSubInstances[j]); } } else { children.push_back(m_allSubInstances[i]); } } m_allSubInstances = children; }
27.973214
79
0.636451
[ "vector" ]
6da5bdacc5a7b76cba7feda87150e09be6c14fac
5,449
cpp
C++
hiro/extension/about-dialog.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
hiro/extension/about-dialog.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
hiro/extension/about-dialog.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#if defined(Hiro_AboutDialog) auto AboutDialog::setAlignment(Alignment alignment) -> type& { state.alignment = alignment; state.relativeTo = {}; return *this; } auto AboutDialog::setAlignment(sWindow relativeTo, Alignment alignment) -> type& { state.alignment = alignment; state.relativeTo = relativeTo; return *this; } auto AboutDialog::setCopyright(const string& copyright, const string& uri) -> type& { state.copyright = copyright; state.copyrightURI = uri; return *this; } auto AboutDialog::setDescription(const string& description) -> type& { state.description = description; return *this; } auto AboutDialog::setLicense(const string& license, const string& uri) -> type& { state.license = license; state.licenseURI = uri; return *this; } auto AboutDialog::setLogo(const multiFactorImage& logo) -> type& { state.logo = logo; state.logo.transform(); return *this; } auto AboutDialog::setName(const string& name) -> type& { state.name = name; return *this; } auto AboutDialog::setVersion(const string& version) -> type& { state.version = version; return *this; } auto AboutDialog::setWebsite(const string& website, const string& uri) -> type& { state.website = website; state.websiteURI = uri; return *this; } auto AboutDialog::show() -> void { Window window; window.onClose([&] { window.setModal(false); }); VerticalLayout layout{&window}; layout.setPadding(5_sx, 5_sy); Label nameLabel{&layout, Size{~0, 0}}; nameLabel.setCollapsible(); nameLabel.setAlignment(0.5); nameLabel.setFont(Font().setFamily(Font::Serif).setBold().setSize(36.0)); nameLabel.setText(state.name ? state.name : Application::name()); nameLabel.setVisible((bool)state.name && !(bool)state.logo); Canvas logoCanvas{&layout, Size{~0, state.logo.height()}, 5_sy}; logoCanvas.setCollapsible(); if(state.logo) { logoCanvas.setIcon(state.logo); } else { logoCanvas.setVisible(false); } Label descriptionLabel{&layout, Size{~0, 0}}; descriptionLabel.setCollapsible(); descriptionLabel.setAlignment(0.5); descriptionLabel.setText(state.description); if(!state.description) descriptionLabel.setVisible(false); HorizontalLayout versionLayout{&layout, Size{~0, 0}, 0}; versionLayout.setCollapsible(); Label versionLabel{&versionLayout, Size{~0, 0}, 3_sx}; versionLabel.setAlignment(1.0); versionLabel.setFont(Font().setBold()); versionLabel.setText("Version:"); Label versionValue{&versionLayout, Size{~0, 0}}; versionValue.setAlignment(0.0); versionValue.setText(state.version); if(!state.version) versionLayout.setVisible(false); HorizontalLayout copyrightLayout{&layout, Size{~0, 0}, 0}; copyrightLayout.setCollapsible(); Label copyrightLabel{&copyrightLayout, Size{~0, 0}, 3_sx}; copyrightLabel.setAlignment(1.0); copyrightLabel.setFont(Font().setBold()); copyrightLabel.setText("Copyright:"); HorizontalLayout copyrightValueLayout{&copyrightLayout, Size{~0, 0}}; Label copyrightValue{&copyrightValueLayout, Size{~0, 0}}; copyrightValue.setAlignment(0.0); copyrightValue.setText(state.copyright); if(state.copyrightURI) { copyrightValue.setForegroundColor(SystemColor::Link).setFont(Font().setBold());; copyrightValue.setMouseCursor(MouseCursor::Hand); copyrightValue.onMouseRelease([&](auto button) { if(button == Mouse::Button::Left) invoke(state.copyrightURI); }); } if(!state.copyright) copyrightLayout.setVisible(false); HorizontalLayout licenseLayout{&layout, Size{~0, 0}, 0}; licenseLayout.setCollapsible(); Label licenseLabel{&licenseLayout, Size{~0, 0}, 3_sx}; licenseLabel.setAlignment(1.0); licenseLabel.setFont(Font().setBold()); licenseLabel.setText("License:"); HorizontalLayout licenseValueLayout{&licenseLayout, Size{~0, 0}}; Label licenseValue{&licenseValueLayout, Size{0, 0}}; licenseValue.setAlignment(0.0); licenseValue.setText(state.license); if(state.licenseURI) { licenseValue.setForegroundColor(SystemColor::Link).setFont(Font().setBold());; licenseValue.setMouseCursor(MouseCursor::Hand); licenseValue.onMouseRelease([&](auto button) { if(button == Mouse::Button::Left) invoke(state.licenseURI); }); } if(!state.license) licenseLayout.setVisible(false); HorizontalLayout websiteLayout{&layout, Size{~0, 0}, 0}; websiteLayout.setCollapsible(); Label websiteLabel{&websiteLayout, Size{~0, 0}, 3_sx}; websiteLabel.setAlignment(1.0); websiteLabel.setFont(Font().setBold()); websiteLabel.setText("Website:"); HorizontalLayout websiteValueLayout{&websiteLayout, Size{~0, 0}}; Label websiteValue{&websiteValueLayout, Size{0, 0}}; websiteValue.setAlignment(0.0); websiteValue.setText(state.website); if(state.websiteURI) { websiteValue.setForegroundColor(SystemColor::Link).setFont(Font().setBold());; websiteValue.setMouseCursor(MouseCursor::Hand); websiteValue.onMouseRelease([&](auto button) { if(button == Mouse::Button::Left) invoke(state.websiteURI); }); } if(!state.website) websiteLayout.setVisible(false); window.setTitle({"About ", state.name ? state.name : Application::name()}); window.setSize({max(320_sx, layout.minimumSize().width()), layout.minimumSize().height()}); window.setResizable(false); window.setAlignment(state.relativeTo, state.alignment); window.setDismissable(); window.setVisible(); window.setModal(); window.setVisible(false); } #endif
33.84472
93
0.72472
[ "transform" ]
6da921c599a29ba43fa15e09da820d261e500ee1
13,709
cpp
C++
MerlionServerCore/MasterNode.cpp
yvt/Merlion
0eda14f20181dd88d8cea95f3551147872eed3f3
[ "Apache-2.0" ]
2
2015-09-27T21:49:45.000Z
2019-05-06T15:11:14.000Z
MerlionServerCore/MasterNode.cpp
yvt/Merlion
0eda14f20181dd88d8cea95f3551147872eed3f3
[ "Apache-2.0" ]
null
null
null
MerlionServerCore/MasterNode.cpp
yvt/Merlion
0eda14f20181dd88d8cea95f3551147872eed3f3
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2014 yvt <i@yvt.jp>. * * 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 "Prefix.pch" #include "MasterNode.hpp" #include "Protocol.hpp" #include "Exceptions.hpp" #include <boost/format.hpp> #include "Packet.hpp" #include "MasterClient.hpp" #include <sstream> namespace asio = boost::asio; using boost::format; namespace mcore { MasterNode::MasterNode(const MasterNodeConnection::ptr&connection): connection(connection), connected(false), sendReady(true) { channel = str(format("Unknown Node [%s]") % connection->tcpSocket().remote_endpoint()); log.setChannel(channel); connection->setChannelName(channel); { std::stringstream ss; ss << connection->tcpSocket().remote_endpoint(); _hostNameString = ss.str(); } // Placeholder for packet size sendBuffer.write<std::uint32_t>(0); } MasterNode::~MasterNode() { master().removeListener(this); connection->shutdown(); } Master& MasterNode::master() { return connection->master(); } void MasterNode::service() { connection->enableBuffering(); auto self = shared_from_this(); auto headerBuffer = std::make_shared<std::uint32_t>(0); connection->readAsync(asio::buffer(headerBuffer.get(), 4), [this, self, headerBuffer] (const boost::system::error_code& error, std::size_t readCount){ try { if (error) { MSCThrow(boost::system::system_error(error)); } std::uint32_t dataSize = *headerBuffer; if (dataSize == 0 || dataSize > 1024 * 1024) { MSCThrow(InvalidDataException("Header is too big.")); } receiveHeader(dataSize); } catch (...) { connection->performShutdownByError(boost::current_exception_diagnostic_information()); } }); } void MasterNode::receiveHeader(std::size_t size) { auto self = shared_from_this(); auto headerBuffer = std::make_shared<std::vector<char>>(); headerBuffer->resize(size); connection->readAsync(asio::buffer(headerBuffer->data(), size), [this, self, headerBuffer] (const boost::system::error_code& error, std::size_t readCount){ try { if (error) { MSCThrow(boost::system::system_error(error)); } PacketReader reader(headerBuffer->data(), readCount); _nodeInfo.deserialize(reader); auto nodeUptime = reader.read<std::uint64_t>(); startTime = boost::posix_time::second_clock::universal_time() - boost::posix_time::seconds(static_cast<long>(nodeUptime)); channel = str(format("Node:%s [%s]") % _nodeInfo.nodeName % connection->tcpSocket().remote_endpoint()); log.setChannel(channel); connection->setChannelName(channel); BOOST_LOG_SEV(log, LogLevel::Info) << "Connected. Requesting to load versions."; // Request to load all versions auto vers = master().getAllVersionNames(); for (const auto& ver: vers) sendLoadVersion(ver, false); flushSendBuffer(); master().addListener(this); master().addNode(shared_from_this()); connected = true; BOOST_LOG_SEV(log, LogLevel::Info) << "Started receiving commands."; receiveCommand(); } catch (...) { connection->performShutdownByError(boost::current_exception_diagnostic_information()); } }); } void MasterNode::receiveCommand() { auto self = shared_from_this(); auto sizeBuffer = std::make_shared<std::uint32_t>(); connection->readAsync(asio::buffer(sizeBuffer.get(), 4), [this, self, sizeBuffer] (const boost::system::error_code& error, std::size_t readCount){ try { if (error) { MSCThrow(boost::system::system_error(error)); } std::uint32_t dataSize = *sizeBuffer; if (dataSize == 0 || dataSize > 1024 * 1024) { MSCThrow(InvalidDataException("Command packet is too big.")); } receiveCommandBody(dataSize); } catch (...) { connection->performShutdownByError(boost::current_exception_diagnostic_information()); } }); } void MasterNode::receiveCommandBody(std::size_t size) { auto self = shared_from_this(); auto cmdBuffer = std::make_shared<std::vector<char>>(); cmdBuffer->resize(size); connection->readAsync(asio::buffer(cmdBuffer->data(), size), [this, self, cmdBuffer] (const boost::system::error_code& error, std::size_t readCount){ try { if (error) { MSCThrow(boost::system::system_error(error)); } PacketReader reader(cmdBuffer->data(), readCount); while (reader.canReadBytes(1)) { MasterCommand cmd = reader.read<MasterCommand>(); switch (cmd) { case MasterCommand::Nop: break; case MasterCommand::RejectClient: { auto clientId = reader.read<std::uint64_t>(); auto req = master().dequePendingClient(clientId); if (!req) { BOOST_LOG_SEV(log, LogLevel::Debug) << format("Requested to reject client #%d that doesn't exist.") % clientId; break; } req->response->reject(std::string()); break; } case MasterCommand::VersionLoaded: { auto version = reader.readString(); std::lock_guard<std::recursive_mutex> lock(domainsMutex); Domain& domain = domains[version]; domain.versionName = version; domain.startTime = boost::posix_time::second_clock::universal_time(); break; } case MasterCommand::VersionUnloaded: { auto version = reader.readString(); std::lock_guard<std::recursive_mutex> lock(domainsMutex); domains.erase(version); break; } case MasterCommand::BindRoom: { auto room = reader.readString(); auto version = reader.readString(); std::lock_guard<std::recursive_mutex> lock(domainsMutex); auto it = domains.find(version); if (it != domains.end()) { Domain& domain = it->second; domain.rooms.insert(room); } break; } case MasterCommand::UnbindRoom: { auto room = reader.readString(); std::lock_guard<std::recursive_mutex> lock(domainsMutex); for (auto& d: domains) { d.second.rooms.erase(room); } break; } case MasterCommand::Log: { LogEntry entry; entry.level = reader.read<LogLevel>(); entry.source = reader.readString(); entry.channel = reader.readString(); entry.message = reader.readString(); entry.host = channel; try { entry.log(); } catch (...) { BOOST_LOG_SEV(log, LogLevel::Warn) << "Error while recording the forwarded log. Ignoring.: " << boost::current_exception_diagnostic_information(); } break; } default: MSCThrow(InvalidDataException(str(format("Invalid command 0x%02x received.") % static_cast<std::uint8_t>(cmd)))); } } receiveCommand(); } catch (...) { connection->performShutdownByError (boost::current_exception_diagnostic_information()); } }); } void MasterNode::sendLoadVersion(const std::string& version, bool flush) { auto self = shared_from_this(); std::lock_guard<std::recursive_mutex> lock(sendMutex); sendBuffer.write(NodeCommand::LoadVersion); sendBuffer.writeString(version); if (flush) flushSendBuffer(); } void MasterNode::sendUnloadVersion(const std::string& version, bool flush) { auto self = shared_from_this(); std::lock_guard<std::recursive_mutex> lock(sendMutex); sendBuffer.write(NodeCommand::UnloadVersion); sendBuffer.writeString(version); if (flush) flushSendBuffer(); } void MasterNode::sendClientConnected(std::uint64_t clientId, const std::string &version, const std::string &room) { auto self = shared_from_this(); { std::lock_guard<std::recursive_mutex> lock(sendMutex); sendBuffer.write(NodeCommand::Connect); sendBuffer.write(clientId); sendBuffer.writeString(version); sendBuffer.writeString(room); flushSendBuffer(); } } void MasterNode::sendHeartbeat() { auto self = shared_from_this(); std::lock_guard<std::recursive_mutex> lock(sendMutex); sendBuffer.write(NodeCommand::Nop); flushSendBuffer(); } void MasterNode::flushSendBuffer() { auto self = shared_from_this(); std::lock_guard<std::recursive_mutex> lock(sendMutex); if (!sendReady) return; auto sentData = std::make_shared<std::vector<char>>(); sentData->swap(sendBuffer.vector()); // Placeholder for packet size sendBuffer.write<std::uint32_t>(0); *reinterpret_cast<std::uint32_t *>(sentData->data()) = static_cast<std::uint32_t>(sentData->size() - 4); sendReady = false; connection->writeAsync(asio::buffer(sentData->data(), sentData->size()), [this, sentData] (const boost::system::error_code& error, std::size_t readCount) { try { if (error) { MSCThrow(boost::system::system_error(error)); } std::lock_guard<std::recursive_mutex> lock(sendMutex); sendReady = true; if (sendBuffer.size() > 4) { flushSendBuffer(); } } catch (...) { connection->performShutdownByError(boost::current_exception_diagnostic_information()); } }); } void MasterNode::acceptClient(const std::shared_ptr<MasterClientResponse> &response, const std::string &version) { auto client = response->client(); std::lock_guard<std::recursive_mutex> lock(domainsMutex); auto it = domains.find(version); if (it == domains.end()) { response->reject("Version not found."); return; } it->second.clients.emplace(response->client()->id(), response->client()); BOOST_LOG_SEV(log, LogLevel::Debug) << format("Sending client connect request (id = '%d').") % client->id(); sendClientConnected(client->id(), version, client->room()); BOOST_LOG_SEV(log, LogLevel::Debug) << format("Client connect request sent (id = '%d').") % client->id(); } void MasterNode::versionAdded(Master &, const std::string &version) { sendLoadVersion(version); } void MasterNode::versionRemoved(Master &, const std::string &version) { sendUnloadVersion(version); } void MasterNode::connectionShutdown() { auto self = shared_from_this(); connected = false; master().removeListener(this); master().removeNode(this); } void MasterNode::heartbeat(Master &param) { sendHeartbeat(); } void MasterNode::clientDisconnected(std::uint64_t cId) { removeClient(cId); } void MasterNode::removeClient(std::uint64_t clientId) { std::lock_guard<std::recursive_mutex> lock(domainsMutex); for (auto& item: domains) item.second.clients.erase(clientId); } std::size_t MasterNode::numClients() { std::size_t count = 0; std::lock_guard<std::recursive_mutex> lock(domainsMutex); for (const auto& item: domains) count += item.second.clients.size(); return count; } std::size_t MasterNode::numRooms() { std::size_t count = 0; std::lock_guard<std::recursive_mutex> lock(domainsMutex); for (const auto& item: domains) count += item.second.rooms.size(); return count; } std::uint64_t MasterNode::uptime() { return static_cast<std::uint64_t> ((boost::posix_time::second_clock::universal_time() - startTime).total_seconds());; } boost::optional<std::string> MasterNode::findDomainForRoom(const std::string& room) { if (room.empty()) return boost::none; std::lock_guard<std::recursive_mutex> lock(domainsMutex); for (const auto& item: domains) { auto it = item.second.rooms.find(room); if (it != item.second.rooms.end()) return item.first; } return boost::none; } std::vector<MasterNode::DomainStatus> MasterNode::domainStatuses() { std::vector<DomainStatus> ret; std::lock_guard<std::recursive_mutex> lock(domainsMutex); ret.reserve(domains.size()); for (const auto& item: domains) { DomainStatus status; status.versionName = item.second.versionName; status.uptime = static_cast<std::uint64_t> ((boost::posix_time::second_clock::universal_time() - item.second.startTime).total_seconds()); status.numClients = item.second.clients.size(); status.numRooms = item.second.rooms.size(); ret.push_back(status); } return ret; } }
28.679916
107
0.615435
[ "vector" ]
6dab5348ee7057a0fd25be4daf7617ea65ffe322
527
hpp
C++
include/RED4ext/Types/generated/mesh/ChunkFlags.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/mesh/ChunkFlags.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/mesh/ChunkFlags.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> namespace RED4ext { namespace mesh { struct ChunkFlags { static constexpr const char* NAME = "meshChunkFlags"; static constexpr const char* ALIAS = NAME; bool renderInScene; // 00 bool renderInShadows; // 01 bool isTwoSided; // 02 bool isRayTracedEmissive; // 03 }; RED4EXT_ASSERT_SIZE(ChunkFlags, 0x4); } // namespace mesh } // namespace RED4ext
21.08
57
0.717268
[ "mesh" ]
6db4a5fd1cc540ec159053c9c8ab539c6122e684
779
cpp
C++
cpp/example/tst/TwoSum2SortedArr/TwoSum2SortedArr-test.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
1
2022-01-26T16:33:45.000Z
2022-01-26T16:33:45.000Z
cpp/example/tst/TwoSum2SortedArr/TwoSum2SortedArr-test.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
null
null
null
cpp/example/tst/TwoSum2SortedArr/TwoSum2SortedArr-test.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
1
2022-01-26T16:35:44.000Z
2022-01-26T16:35:44.000Z
#include "TwoSum2SortedArr/twoSum2SortedArr.h" #include "gtest/gtest.h" using namespace std; class twoSum2SortedArr_MultipleParamsTests : public ::testing::TestWithParam<tuple<vector<int>,int,vector<int>>>{ }; TEST_P(twoSum2SortedArr_MultipleParamsTests, CheckAns){ vector<int> numbers = get<0>(GetParam()); int target = get<1>(GetParam()); vector<int> expected = get<2>(GetParam()); ASSERT_EQ(expected,twoSum2SortedArr::naive(numbers,target)); }; INSTANTIATE_TEST_CASE_P( TwoSum2SortedArrTests, twoSum2SortedArr_MultipleParamsTests, ::testing::Values( make_tuple(vector<int>{2,7,11,15},9,vector<int>{1,2}), make_tuple(vector<int>{2,3,4},6,vector<int>{1,3}), make_tuple(vector<int>{-1,0},-1,vector<int>{1,2}) ) );
29.961538
72
0.698331
[ "vector" ]
6dbe2503e85aa4f48bf143c6e7bd1e8bee1b0cdc
1,773
cpp
C++
libfma/src/fma/assem/BinaryCodeGenerator.cpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
14
2018-01-25T10:31:05.000Z
2022-02-19T13:08:11.000Z
libfma/src/fma/assem/BinaryCodeGenerator.cpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
1
2020-12-24T10:10:28.000Z
2020-12-24T10:10:28.000Z
libfma/src/fma/assem/BinaryCodeGenerator.cpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
null
null
null
#include <fma/Project.hpp> #include <fma/assem/BinaryCodeGenerator.hpp> #include <fma/assem/BinaryCodeGeneratorScope.hpp> #include <fma/linker/LinkerObject.hpp> #include <fma/linker/LinkerBlock.hpp> #include <fma/plugin/MemoryPluginAdapter.hpp> #include <fma/symbol/SymbolReference.hpp> #include <iostream> using namespace FMA; using namespace FMA::assem; using namespace FMA::symbol; using namespace FMA::plugin; using namespace FMA::linker; // ---------------------------------------------------------------------------- BinaryCodeGenerator::BinaryCodeGenerator(Project *project, LinkerObject *object) : project(project) , object(object) { } // ---------------------------------------------------------------------------- BinaryCodeGenerator::~BinaryCodeGenerator() { } // ---------------------------------------------------------------------------- void BinaryCodeGenerator::add(MemoryBlock *block) { blocks.push_back(block); } // ---------------------------------------------------------------------------- bool BinaryCodeGenerator::generate() { while (blocks.size()) { auto block = blocks.back(); blocks.pop_back(); if (!generate(block)) { return false; } } return true; } // ---------------------------------------------------------------------------- bool BinaryCodeGenerator::generate(MemoryBlock *source) { const std::string &name = source->createReference()->getName(); project->log().trace() << "Generate bytecode for " << name; LinkerBlock *target = object->createBlock(); target->symbol(name); target->setLocation(source->location()); BinaryCodeGeneratorScope scope(this, target); return source->buildByteCode(&scope); } // ----------------------------------------------------------------------------
29.55
80
0.534687
[ "object" ]