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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f672d2a108cc99f3214eaa3a4dbeefedec9f0efa | 16,095 | cpp | C++ | clang/lib/Driver/ToolChains/HIPAMD.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | clang/lib/Driver/ToolChains/HIPAMD.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | clang/lib/Driver/ToolChains/HIPAMD.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | //===--- HIPAMD.cpp - HIP Tool and ToolChain Implementations ----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "HIPAMD.h"
#include "AMDGPU.h"
#include "CommonArgs.h"
#include "HIPUtility.h"
#include "clang/Basic/Cuda.h"
#include "clang/Basic/TargetID.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/InputInfo.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/SanitizerArgs.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetParser.h"
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;
#if defined(_WIN32) || defined(_WIN64)
#define NULL_FILE "nul"
#else
#define NULL_FILE "/dev/null"
#endif
static bool shouldSkipSanitizeOption(const ToolChain &TC,
const llvm::opt::ArgList &DriverArgs,
StringRef TargetID,
const llvm::opt::Arg *A) {
// For actions without targetID, do nothing.
if (TargetID.empty())
return false;
Option O = A->getOption();
if (!O.matches(options::OPT_fsanitize_EQ))
return false;
if (!DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
options::OPT_fno_gpu_sanitize, true))
return true;
auto &Diags = TC.getDriver().getDiags();
// For simplicity, we only allow -fsanitize=address
SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);
if (K != SanitizerKind::Address)
return true;
llvm::StringMap<bool> FeatureMap;
auto OptionalGpuArch = parseTargetID(TC.getTriple(), TargetID, &FeatureMap);
assert(OptionalGpuArch && "Invalid Target ID");
(void)OptionalGpuArch;
auto Loc = FeatureMap.find("xnack");
if (Loc == FeatureMap.end() || !Loc->second) {
Diags.Report(
clang::diag::warn_drv_unsupported_option_for_offload_arch_req_feature)
<< A->getAsString(DriverArgs) << TargetID << "xnack+";
return true;
}
return false;
}
void AMDGCN::Linker::constructLlvmLinkCommand(Compilation &C,
const JobAction &JA,
const InputInfoList &Inputs,
const InputInfo &Output,
const llvm::opt::ArgList &Args) const {
// Construct llvm-link command.
// The output from llvm-link is a bitcode file.
ArgStringList LlvmLinkArgs;
assert(!Inputs.empty() && "Must have at least one input.");
LlvmLinkArgs.append({"-o", Output.getFilename()});
for (auto Input : Inputs)
LlvmLinkArgs.push_back(Input.getFilename());
// Look for archive of bundled bitcode in arguments, and add temporary files
// for the extracted archive of bitcode to inputs.
auto TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);
AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LlvmLinkArgs, "amdgcn",
TargetID,
/*IsBitCodeSDL=*/true,
/*PostClangLink=*/false);
const char *LlvmLink =
Args.MakeArgString(getToolChain().GetProgramPath("llvm-link"));
C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
LlvmLink, LlvmLinkArgs, Inputs,
Output));
}
void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
const InputInfoList &Inputs,
const InputInfo &Output,
const llvm::opt::ArgList &Args) const {
// Construct lld command.
// The output from ld.lld is an HSA code object file.
ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined", "-shared",
"-plugin-opt=-amdgpu-internalize-symbols"};
auto &TC = getToolChain();
auto &D = TC.getDriver();
assert(!Inputs.empty() && "Must have at least one input.");
bool IsThinLTO = D.getLTOMode(/*IsOffload=*/true) == LTOK_Thin;
addLTOOptions(TC, Args, LldArgs, Output, Inputs[0], IsThinLTO);
// Extract all the -m options
std::vector<llvm::StringRef> Features;
amdgpu::getAMDGPUTargetFeatures(D, TC.getTriple(), Args, Features);
// Add features to mattr such as cumode
std::string MAttrString = "-plugin-opt=-mattr=";
for (auto OneFeature : unifyTargetFeatures(Features)) {
MAttrString.append(Args.MakeArgString(OneFeature));
if (OneFeature != Features.back())
MAttrString.append(",");
}
if (!Features.empty())
LldArgs.push_back(Args.MakeArgString(MAttrString));
// ToDo: Remove this option after AMDGPU backend supports ISA-level linking.
// Since AMDGPU backend currently does not support ISA-level linking, all
// called functions need to be imported.
if (IsThinLTO)
LldArgs.push_back(Args.MakeArgString("-plugin-opt=-force-import-all"));
for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
LldArgs.push_back(
Args.MakeArgString(Twine("-plugin-opt=") + A->getValue(0)));
}
if (C.getDriver().isSaveTempsEnabled())
LldArgs.push_back("-save-temps");
addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);
LldArgs.append({"-o", Output.getFilename()});
for (auto Input : Inputs)
LldArgs.push_back(Input.getFilename());
// Look for archive of bundled bitcode in arguments, and add temporary files
// for the extracted archive of bitcode to inputs.
auto TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);
AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LldArgs, "amdgcn",
TargetID,
/*IsBitCodeSDL=*/true,
/*PostClangLink=*/false);
const char *Lld = Args.MakeArgString(getToolChain().GetProgramPath("lld"));
C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
Lld, LldArgs, Inputs, Output));
}
// For amdgcn the inputs of the linker job are device bitcode and output is
// either an object file or bitcode (-emit-llvm). It calls llvm-link, opt,
// llc, then lld steps.
void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
if (Inputs.size() > 0 &&
Inputs[0].getType() == types::TY_Image &&
JA.getType() == types::TY_Object)
return HIP::constructGenerateObjFileFromHIPFatBinary(C, Output, Inputs,
Args, JA, *this);
if (JA.getType() == types::TY_HIP_FATBIN)
return HIP::constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs,
Args, *this);
if (JA.getType() == types::TY_LLVM_BC)
return constructLlvmLinkCommand(C, JA, Inputs, Output, Args);
return constructLldCommand(C, JA, Inputs, Output, Args);
}
HIPAMDToolChain::HIPAMDToolChain(const Driver &D, const llvm::Triple &Triple,
const ToolChain &HostTC, const ArgList &Args)
: ROCMToolChain(D, Triple, Args), HostTC(HostTC) {
// Lookup binaries into the driver directory, this is used to
// discover the clang-offload-bundler executable.
getProgramPaths().push_back(getDriver().Dir);
// Diagnose unsupported sanitizer options only once.
if (!Args.hasFlag(options::OPT_fgpu_sanitize, options::OPT_fno_gpu_sanitize,
true))
return;
for (auto A : Args.filtered(options::OPT_fsanitize_EQ)) {
SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);
if (K != SanitizerKind::Address)
D.getDiags().Report(clang::diag::warn_drv_unsupported_option_for_target)
<< A->getAsString(Args) << getTriple().str();
}
}
void HIPAMDToolChain::addClangTargetOptions(
const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
Action::OffloadKind DeviceOffloadingKind) const {
HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
assert(DeviceOffloadingKind == Action::OFK_HIP &&
"Only HIP offloading kinds are supported for GPUs.");
CC1Args.push_back("-fcuda-is-device");
if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
options::OPT_fno_cuda_approx_transcendentals, false))
CC1Args.push_back("-fcuda-approx-transcendentals");
if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
false))
CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
StringRef MaxThreadsPerBlock =
DriverArgs.getLastArgValue(options::OPT_gpu_max_threads_per_block_EQ);
if (!MaxThreadsPerBlock.empty()) {
std::string ArgStr =
std::string("--gpu-max-threads-per-block=") + MaxThreadsPerBlock.str();
CC1Args.push_back(DriverArgs.MakeArgStringRef(ArgStr));
}
CC1Args.push_back("-fcuda-allow-variadic-functions");
// Default to "hidden" visibility, as object level linking will not be
// supported for the foreseeable future.
if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
options::OPT_fvisibility_ms_compat)) {
CC1Args.append({"-fvisibility", "hidden"});
CC1Args.push_back("-fapply-global-visibility-to-externs");
}
llvm::for_each(getHIPDeviceLibs(DriverArgs), [&](auto BCFile) {
CC1Args.push_back(BCFile.ShouldInternalize ? "-mlink-builtin-bitcode"
: "-mlink-bitcode-file");
CC1Args.push_back(DriverArgs.MakeArgString(BCFile.Path));
});
}
llvm::opt::DerivedArgList *
HIPAMDToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
StringRef BoundArch,
Action::OffloadKind DeviceOffloadKind) const {
DerivedArgList *DAL =
HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
if (!DAL)
DAL = new DerivedArgList(Args.getBaseArgs());
const OptTable &Opts = getDriver().getOpts();
for (Arg *A : Args) {
if (!shouldSkipArgument(A) &&
!shouldSkipSanitizeOption(*this, Args, BoundArch, A))
DAL->append(A);
}
if (!BoundArch.empty()) {
DAL->eraseArg(options::OPT_mcpu_EQ);
DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ), BoundArch);
checkTargetID(*DAL);
}
return DAL;
}
Tool *HIPAMDToolChain::buildLinker() const {
assert(getTriple().getArch() == llvm::Triple::amdgcn);
return new tools::AMDGCN::Linker(*this);
}
void HIPAMDToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
HostTC.addClangWarningOptions(CC1Args);
}
ToolChain::CXXStdlibType
HIPAMDToolChain::GetCXXStdlibType(const ArgList &Args) const {
return HostTC.GetCXXStdlibType(Args);
}
void HIPAMDToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
}
void HIPAMDToolChain::AddClangCXXStdlibIncludeArgs(
const ArgList &Args, ArgStringList &CC1Args) const {
HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
}
void HIPAMDToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
ArgStringList &CC1Args) const {
HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
}
void HIPAMDToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
}
SanitizerMask HIPAMDToolChain::getSupportedSanitizers() const {
// The HIPAMDToolChain only supports sanitizers in the sense that it allows
// sanitizer arguments on the command line if they are supported by the host
// toolchain. The HIPAMDToolChain will actually ignore any command line
// arguments for any of these "supported" sanitizers. That means that no
// sanitization of device code is actually supported at this time.
//
// This behavior is necessary because the host and device toolchains
// invocations often share the command line, so the device toolchain must
// tolerate flags meant only for the host toolchain.
return HostTC.getSupportedSanitizers();
}
VersionTuple HIPAMDToolChain::computeMSVCVersion(const Driver *D,
const ArgList &Args) const {
return HostTC.computeMSVCVersion(D, Args);
}
llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
HIPAMDToolChain::getHIPDeviceLibs(const llvm::opt::ArgList &DriverArgs) const {
llvm::SmallVector<BitCodeLibraryInfo, 12> BCLibs;
if (DriverArgs.hasArg(options::OPT_nogpulib))
return {};
ArgStringList LibraryPaths;
// Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
for (auto Path : RocmInstallation.getRocmDeviceLibPathArg())
LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");
// Maintain compatability with --hip-device-lib.
auto BCLibArgs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);
if (!BCLibArgs.empty()) {
llvm::for_each(BCLibArgs, [&](StringRef BCName) {
StringRef FullName;
for (std::string LibraryPath : LibraryPaths) {
SmallString<128> Path(LibraryPath);
llvm::sys::path::append(Path, BCName);
FullName = Path;
if (llvm::sys::fs::exists(FullName)) {
BCLibs.push_back(FullName);
return;
}
}
getDriver().Diag(diag::err_drv_no_such_file) << BCName;
});
} else {
if (!RocmInstallation.hasDeviceLibrary()) {
getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 0;
return {};
}
StringRef GpuArch = getGPUArch(DriverArgs);
assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
// If --hip-device-lib is not set, add the default bitcode libraries.
if (DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
options::OPT_fno_gpu_sanitize, true) &&
getSanitizerArgs(DriverArgs).needsAsanRt()) {
auto AsanRTL = RocmInstallation.getAsanRTLPath();
if (AsanRTL.empty()) {
unsigned DiagID = getDriver().getDiags().getCustomDiagID(
DiagnosticsEngine::Error,
"AMDGPU address sanitizer runtime library (asanrtl) is not found. "
"Please install ROCm device library which supports address "
"sanitizer");
getDriver().Diag(DiagID);
return {};
} else
BCLibs.push_back({AsanRTL.str(), /*ShouldInternalize=*/false});
}
// Add the HIP specific bitcode library.
BCLibs.push_back(RocmInstallation.getHIPPath());
// Add common device libraries like ocml etc.
for (auto N : getCommonDeviceLibNames(DriverArgs, GpuArch.str()))
BCLibs.push_back(StringRef(N));
// Add instrument lib.
auto InstLib =
DriverArgs.getLastArgValue(options::OPT_gpu_instrument_lib_EQ);
if (InstLib.empty())
return BCLibs;
if (llvm::sys::fs::exists(InstLib))
BCLibs.push_back(InstLib);
else
getDriver().Diag(diag::err_drv_no_such_file) << InstLib;
}
return BCLibs;
}
void HIPAMDToolChain::checkTargetID(
const llvm::opt::ArgList &DriverArgs) const {
auto PTID = getParsedTargetID(DriverArgs);
if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
getDriver().Diag(clang::diag::err_drv_bad_target_id)
<< PTID.OptionalTargetID.getValue();
}
}
| 38.876812 | 80 | 0.653992 | [
"object",
"vector"
] |
f675b0f212c59a58327653ff03d8a5aedb1fbda3 | 2,504 | cpp | C++ | BFS/iterateGridForMaxIterationsToReachEveryPosBFS.cpp | jkerkela/best-algorithm-collection | 6b22536a9f8ebdf3ae134031d41becf30066a5ef | [
"MIT"
] | null | null | null | BFS/iterateGridForMaxIterationsToReachEveryPosBFS.cpp | jkerkela/best-algorithm-collection | 6b22536a9f8ebdf3ae134031d41becf30066a5ef | [
"MIT"
] | null | null | null | BFS/iterateGridForMaxIterationsToReachEveryPosBFS.cpp | jkerkela/best-algorithm-collection | 6b22536a9f8ebdf3ae134031d41becf30066a5ef | [
"MIT"
] | null | null | null | class Solution {
public:
int nextStepDims[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
int orangesRotting(vector<vector<int>>& grid) {
return stepsNeededForSpreadingRotOverGrid(grid);
}
int stepsNeededForSpreadingRotOverGrid(vector<vector<int>>& grid) {
int gridWidth = grid[0].size();
int gridHeight = grid.size();
int currentSteps = 0;
int currentFreshItemCount = 0;
queue<pair<int,int>> rottenItemLocations;
initializeRotAndFreshItemsData(grid, rottenItemLocations, currentFreshItemCount, gridWidth, gridHeight);
pair<int,int> currentRotItemLocation = rottenItemLocations.front();
while(!rottenItemLocations.empty()) {
int levelSize = rottenItemLocations.size();
bool rottenItemsThisLevel = false;
for(int i = 0; i < levelSize; i++) {
pair<int,int> currentRotItemLocation = rottenItemLocations.front();
rottenItemLocations.pop();
int yCoord = currentRotItemLocation.first;
int xCoord = currentRotItemLocation.second;
for(auto stepToAdjacentLoc : nextStepDims) {
int adjacentXCoord = xCoord + stepToAdjacentLoc[0];
int adjacentYCoord = yCoord + stepToAdjacentLoc[1];
if(adjacentXCoord >= 0 && adjacentXCoord < gridWidth && adjacentYCoord >= 0 && adjacentYCoord < gridHeight && grid[adjacentYCoord][adjacentXCoord] == 1) {
grid[adjacentYCoord][adjacentXCoord] = 2;
currentFreshItemCount--;
rottenItemLocations.push({adjacentYCoord, adjacentXCoord});
rottenItemsThisLevel = true;
}
}
}
if(rottenItemsThisLevel) {currentSteps++;}
}
if(currentFreshItemCount > 0) {
return -1;
}
return currentSteps;
}
void initializeRotAndFreshItemsData(vector<vector<int>>& grid, queue<pair<int,int>>& rottenItemLocations, int& currentFreshItemCount, int& gridWidth, int& gridHeight) {
for(int i = 0; i < gridHeight; i++) {
for(int j = 0; j < gridWidth; j++) {
if(grid[i][j] == 2) {
rottenItemLocations.push({i, j});
}
if(grid[i][j] == 1) {
currentFreshItemCount++;
}
}
}
}
};
| 41.733333 | 174 | 0.555112 | [
"vector"
] |
f6773d944950bf9a6648a99db5dc141e931f2863 | 35,494 | cpp | C++ | openstudiocore/src/model/EvaporativeCoolerIndirectResearchSpecial.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | 1 | 2017-10-13T09:23:04.000Z | 2017-10-13T09:23:04.000Z | openstudiocore/src/model/EvaporativeCoolerIndirectResearchSpecial.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | null | null | null | openstudiocore/src/model/EvaporativeCoolerIndirectResearchSpecial.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | 1 | 2022-03-20T13:19:42.000Z | 2022-03-20T13:19:42.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* 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, THE UNITED STATES GOVERNMENT, OR ANY 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 "EvaporativeCoolerIndirectResearchSpecial.hpp"
#include "EvaporativeCoolerIndirectResearchSpecial_Impl.hpp"
#include "Schedule.hpp"
#include "Schedule_Impl.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include "Curve.hpp"
#include "Curve_Impl.hpp"
#include "ScheduleTypeLimits.hpp"
#include "ScheduleTypeRegistry.hpp"
#include <utilities/idd/OS_EvaporativeCooler_Indirect_ResearchSpecial_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
EvaporativeCoolerIndirectResearchSpecial_Impl::EvaporativeCoolerIndirectResearchSpecial_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == EvaporativeCoolerIndirectResearchSpecial::iddObjectType());
}
EvaporativeCoolerIndirectResearchSpecial_Impl::EvaporativeCoolerIndirectResearchSpecial_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == EvaporativeCoolerIndirectResearchSpecial::iddObjectType());
}
EvaporativeCoolerIndirectResearchSpecial_Impl::EvaporativeCoolerIndirectResearchSpecial_Impl(const EvaporativeCoolerIndirectResearchSpecial_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& EvaporativeCoolerIndirectResearchSpecial_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType EvaporativeCoolerIndirectResearchSpecial_Impl::iddObjectType() const {
return EvaporativeCoolerIndirectResearchSpecial::iddObjectType();
}
std::vector<ScheduleTypeKey> EvaporativeCoolerIndirectResearchSpecial_Impl::getScheduleTypeKeys(const Schedule& schedule) const
{
std::vector<ScheduleTypeKey> result;
UnsignedVector fieldIndices = getSourceIndices(schedule.handle());
UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end());
if (std::find(b,e,OS_EvaporativeCooler_Indirect_ResearchSpecialFields::AvailabilityScheduleName) != e)
{
result.push_back(ScheduleTypeKey("EvaporativeCoolerIndirectResearchSpecial","Availability"));
}
return result;
}
boost::optional<Schedule> EvaporativeCoolerIndirectResearchSpecial_Impl::availabilitySchedule() const {
return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::AvailabilityScheduleName);
}
double EvaporativeCoolerIndirectResearchSpecial_Impl::coolerMaximumEffectiveness() const {
boost::optional<double> value = getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::CoolerMaximumEffectiveness,true);
OS_ASSERT(value);
return value.get();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::recirculatingWaterPumpPowerConsumption() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::RecirculatingWaterPumpPowerConsumption,true);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::isRecirculatingWaterPumpPowerConsumptionAutosized() const {
bool result = false;
boost::optional<std::string> value = getString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::RecirculatingWaterPumpPowerConsumption, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autosize");
}
return result;
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::secondaryFanFlowRate() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate,true);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::isSecondaryFanFlowRateAutosized() const {
bool result = false;
boost::optional<std::string> value = getString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autosize");
}
return result;
}
double EvaporativeCoolerIndirectResearchSpecial_Impl::secondaryFanTotalEfficiency() const {
boost::optional<double> value = getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanTotalEfficiency,true);
OS_ASSERT(value);
return value.get();
}
double EvaporativeCoolerIndirectResearchSpecial_Impl::secondaryFanDeltaPressure() const {
boost::optional<double> value = getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanDeltaPressure,true);
OS_ASSERT(value);
return value.get();
}
double EvaporativeCoolerIndirectResearchSpecial_Impl::dewpointEffectivenessFactor() const {
boost::optional<double> value = getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DewpointEffectivenessFactor,true);
OS_ASSERT(value);
return value.get();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::driftLossFraction() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DriftLossFraction,true);
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::blowdownConcentrationRatio() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::BlowdownConcentrationRatio,true);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setAvailabilitySchedule(Schedule& schedule) {
bool result = setSchedule(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::AvailabilityScheduleName,
"EvaporativeCoolerIndirectResearchSpecial",
"Availability",
schedule);
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetAvailabilitySchedule() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::AvailabilityScheduleName, "");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setCoolerMaximumEffectiveness(double coolerMaximumEffectiveness) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::CoolerMaximumEffectiveness, coolerMaximumEffectiveness);
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::setRecirculatingWaterPumpPowerConsumption(double recirculatingWaterPumpPowerConsumption) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::RecirculatingWaterPumpPowerConsumption, recirculatingWaterPumpPowerConsumption);
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::autosizeRecirculatingWaterPumpPowerConsumption() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::RecirculatingWaterPumpPowerConsumption, "autosize");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setSecondaryFanFlowRate(boost::optional<double> secondaryFanFlowRate) {
bool result(false);
if (secondaryFanFlowRate) {
result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate, secondaryFanFlowRate.get());
}
else {
resetSecondaryFanFlowRate();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetSecondaryFanFlowRate() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate, "");
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::autosizeSecondaryFanFlowRate() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate, "autosize");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setSecondaryFanTotalEfficiency(double secondaryFanTotalEfficiency) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanTotalEfficiency, secondaryFanTotalEfficiency);
return result;
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setSecondaryFanDeltaPressure(double secondaryFanDeltaPressure) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanDeltaPressure, secondaryFanDeltaPressure);
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::setDewpointEffectivenessFactor(double dewpointEffectivenessFactor) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DewpointEffectivenessFactor, dewpointEffectivenessFactor);
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setDriftLossFraction(boost::optional<double> driftLossFraction) {
bool result(false);
if (driftLossFraction) {
result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DriftLossFraction, driftLossFraction.get());
}
else {
resetDriftLossFraction();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetDriftLossFraction() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DriftLossFraction, "");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setBlowdownConcentrationRatio(boost::optional<double> blowdownConcentrationRatio) {
bool result(false);
if (blowdownConcentrationRatio) {
result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::BlowdownConcentrationRatio, blowdownConcentrationRatio.get());
}
else {
resetBlowdownConcentrationRatio();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetBlowdownConcentrationRatio() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::BlowdownConcentrationRatio, "");
OS_ASSERT(result);
}
unsigned EvaporativeCoolerIndirectResearchSpecial_Impl::inletPort()
{
return OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryAirInletNode;
}
unsigned EvaporativeCoolerIndirectResearchSpecial_Impl::outletPort()
{
return OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryAirOutletNode;
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::addToNode(Node & node)
{
if( boost::optional<AirLoopHVAC> airLoop = node.airLoopHVAC() )
{
if( ! airLoop->demandComponent(node.handle()) )
{
if( StraightComponent_Impl::addToNode( node ) )
{
return true;
}
}
}
return false;
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setReliefAirInletNode(const Node & node)
{
return setPointer(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::ReliefAirInletNode, node.handle());
}
boost::optional<Node> EvaporativeCoolerIndirectResearchSpecial_Impl::reliefAirInletNode() const
{
return getObject<ModelObject>().getModelObjectTarget<Node>(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::ReliefAirInletNode);
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial_Impl::wetbulbEffectivenessFlowRatioModifierCurve() const {
return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WetbulbEffectivenessFlowRatioModifierCurveName);
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::coolerDrybulbDesignEffectiveness() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::CoolerDrybulbDesignEffectiveness,true);
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial_Impl::drybulbEffectivenessFlowRatioModifierCurve() const {
return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DrybulbEffectivenessFlowRatioModifierCurveName);
}
double EvaporativeCoolerIndirectResearchSpecial_Impl::waterPumpPowerSizingFactor() const {
boost::optional<double> value = getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WaterPumpPowerSizingFactor,true);
OS_ASSERT(value);
return value.get();
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial_Impl::waterPumpPowerModifierCurve() const {
return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WaterPumpPowerModifierCurveName);
}
double EvaporativeCoolerIndirectResearchSpecial_Impl::secondaryAirFlowScalingFactor() const {
boost::optional<double> value = getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFlowScalingFactor,true);
OS_ASSERT(value);
return value.get();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::secondaryAirFanDesignPower() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanDesignPower,true);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::isSecondaryAirFanDesignPowerAutosized() const {
bool result = false;
boost::optional<std::string> value = getString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanDesignPower, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autosize");
}
return result;
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial_Impl::secondaryAirFanPowerModifierCurve() const {
return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanPowerModifierCurveName);
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial_Impl::primaryDesignAirFlowRate() const {
return getDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryDesignAirFlowRate,true);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::isPrimaryDesignAirFlowRateAutosized() const {
bool result = false;
boost::optional<std::string> value = getString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryDesignAirFlowRate, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autosize");
}
return result;
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setWetbulbEffectivenessFlowRatioModifierCurve(const boost::optional<Curve>& curve) {
bool result(false);
if (curve) {
result = setPointer(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WetbulbEffectivenessFlowRatioModifierCurveName, curve.get().handle());
}
else {
resetWetbulbEffectivenessFlowRatioModifierCurve();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetWetbulbEffectivenessFlowRatioModifierCurve() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WetbulbEffectivenessFlowRatioModifierCurveName, "");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setCoolerDrybulbDesignEffectiveness(boost::optional<double> coolerDrybulbDesignEffectiveness) {
bool result(false);
if (coolerDrybulbDesignEffectiveness) {
result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::CoolerDrybulbDesignEffectiveness, coolerDrybulbDesignEffectiveness.get());
}
else {
resetCoolerDrybulbDesignEffectiveness();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetCoolerDrybulbDesignEffectiveness() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::CoolerDrybulbDesignEffectiveness, "");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setDrybulbEffectivenessFlowRatioModifierCurve(const boost::optional<Curve>& curve) {
bool result(false);
if (curve) {
result = setPointer(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DrybulbEffectivenessFlowRatioModifierCurveName, curve.get().handle());
}
else {
resetDrybulbEffectivenessFlowRatioModifierCurve();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetDrybulbEffectivenessFlowRatioModifierCurve() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::DrybulbEffectivenessFlowRatioModifierCurveName, "");
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::setWaterPumpPowerSizingFactor(double waterPumpPowerSizingFactor) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WaterPumpPowerSizingFactor, waterPumpPowerSizingFactor);
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setWaterPumpPowerModifierCurve(const boost::optional<Curve>& curve) {
bool result(false);
if (curve) {
result = setPointer(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WaterPumpPowerModifierCurveName, curve.get().handle());
}
else {
resetWaterPumpPowerModifierCurve();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetWaterPumpPowerModifierCurve() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::WaterPumpPowerModifierCurveName, "");
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::setSecondaryAirFlowScalingFactor(double secondaryAirFlowScalingFactor) {
bool result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFlowScalingFactor, secondaryAirFlowScalingFactor);
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::setSecondaryAirFanDesignPower(boost::optional<double> secondaryAirFanDesignPower) {
bool result(false);
if (secondaryAirFanDesignPower) {
result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanDesignPower, secondaryAirFanDesignPower.get());
}
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::autosizeSecondaryAirFanDesignPower() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanDesignPower, "autosize");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setSecondaryAirFanPowerModifierCurve(const boost::optional<Curve>& curve) {
bool result(false);
if (curve) {
result = setPointer(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanPowerModifierCurveName, curve.get().handle());
}
else {
resetSecondaryAirFanPowerModifierCurve();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetSecondaryAirFanPowerModifierCurve() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryAirFanPowerModifierCurveName, "");
OS_ASSERT(result);
}
bool EvaporativeCoolerIndirectResearchSpecial_Impl::setPrimaryDesignAirFlowRate(boost::optional<double> primaryDesignAirFlowRate) {
bool result(false);
if (primaryDesignAirFlowRate) {
result = setDouble(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryDesignAirFlowRate, primaryDesignAirFlowRate.get());
}
else {
resetPrimaryDesignAirFlowRate();
result = true;
}
return result;
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::resetPrimaryDesignAirFlowRate() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryDesignAirFlowRate, "");
OS_ASSERT(result);
}
void EvaporativeCoolerIndirectResearchSpecial_Impl::autosizePrimaryDesignAirFlowRate() {
bool result = setString(OS_EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryDesignAirFlowRate, "autosize");
OS_ASSERT(result);
}
} // detail
EvaporativeCoolerIndirectResearchSpecial::EvaporativeCoolerIndirectResearchSpecial(const Model& model)
: StraightComponent(EvaporativeCoolerIndirectResearchSpecial::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>());
setCoolerMaximumEffectiveness(0.75);
setRecirculatingWaterPumpPowerConsumption(30.0);
setSecondaryFanTotalEfficiency(0.6);
setSecondaryFanDeltaPressure(124.6);
setDewpointEffectivenessFactor(0.9);
setDriftLossFraction(0.0);
setWaterPumpPowerSizingFactor(0.1);
setSecondaryAirFlowScalingFactor(1.0);
resetBlowdownConcentrationRatio();
}
IddObjectType EvaporativeCoolerIndirectResearchSpecial::iddObjectType() {
return IddObjectType(IddObjectType::OS_EvaporativeCooler_Indirect_ResearchSpecial);
}
boost::optional<Schedule> EvaporativeCoolerIndirectResearchSpecial::availabilitySchedule() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->availabilitySchedule();
}
double EvaporativeCoolerIndirectResearchSpecial::coolerMaximumEffectiveness() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->coolerMaximumEffectiveness();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::recirculatingWaterPumpPowerConsumption() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->recirculatingWaterPumpPowerConsumption();
}
bool EvaporativeCoolerIndirectResearchSpecial::isRecirculatingWaterPumpPowerConsumptionAutosized() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->isRecirculatingWaterPumpPowerConsumptionAutosized();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::secondaryFanFlowRate() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->secondaryFanFlowRate();
}
bool EvaporativeCoolerIndirectResearchSpecial::isSecondaryFanFlowRateAutosized() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->isSecondaryFanFlowRateAutosized();
}
double EvaporativeCoolerIndirectResearchSpecial::secondaryFanTotalEfficiency() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->secondaryFanTotalEfficiency();
}
double EvaporativeCoolerIndirectResearchSpecial::secondaryFanDeltaPressure() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->secondaryFanDeltaPressure();
}
double EvaporativeCoolerIndirectResearchSpecial::dewpointEffectivenessFactor() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->dewpointEffectivenessFactor();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::driftLossFraction() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->driftLossFraction();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::blowdownConcentrationRatio() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->blowdownConcentrationRatio();
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial::wetbulbEffectivenessFlowRatioModifierCurve() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->wetbulbEffectivenessFlowRatioModifierCurve();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::coolerDrybulbDesignEffectiveness() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->coolerDrybulbDesignEffectiveness();
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial::drybulbEffectivenessFlowRatioModifierCurve() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->drybulbEffectivenessFlowRatioModifierCurve();
}
double EvaporativeCoolerIndirectResearchSpecial::waterPumpPowerSizingFactor() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->waterPumpPowerSizingFactor();
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial::waterPumpPowerModifierCurve() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->waterPumpPowerModifierCurve();
}
double EvaporativeCoolerIndirectResearchSpecial::secondaryAirFlowScalingFactor() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->secondaryAirFlowScalingFactor();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::secondaryAirFanDesignPower() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->secondaryAirFanDesignPower();
}
bool EvaporativeCoolerIndirectResearchSpecial::isSecondaryAirFanDesignPowerAutosized() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->isSecondaryAirFanDesignPowerAutosized();
}
boost::optional<Curve> EvaporativeCoolerIndirectResearchSpecial::secondaryAirFanPowerModifierCurve() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->secondaryAirFanPowerModifierCurve();
}
boost::optional<double> EvaporativeCoolerIndirectResearchSpecial::primaryDesignAirFlowRate() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->primaryDesignAirFlowRate();
}
bool EvaporativeCoolerIndirectResearchSpecial::isPrimaryDesignAirFlowRateAutosized() const {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->isPrimaryDesignAirFlowRateAutosized();
}
bool EvaporativeCoolerIndirectResearchSpecial::setAvailabilitySchedule(Schedule& schedule) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setAvailabilitySchedule(schedule);
}
void EvaporativeCoolerIndirectResearchSpecial::resetAvailabilitySchedule() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetAvailabilitySchedule();
}
bool EvaporativeCoolerIndirectResearchSpecial::setCoolerMaximumEffectiveness(double coolerMaximumEffectiveness) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setCoolerMaximumEffectiveness(coolerMaximumEffectiveness);
}
void EvaporativeCoolerIndirectResearchSpecial::setRecirculatingWaterPumpPowerConsumption(double recirculatingWaterPumpPowerConsumption) {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setRecirculatingWaterPumpPowerConsumption(recirculatingWaterPumpPowerConsumption);
}
void EvaporativeCoolerIndirectResearchSpecial::autosizeRecirculatingWaterPumpPowerConsumption() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->autosizeRecirculatingWaterPumpPowerConsumption();
}
bool EvaporativeCoolerIndirectResearchSpecial::setSecondaryFanFlowRate(double secondaryFanFlowRate) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setSecondaryFanFlowRate(secondaryFanFlowRate);
}
void EvaporativeCoolerIndirectResearchSpecial::resetSecondaryFanFlowRate() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetSecondaryFanFlowRate();
}
void EvaporativeCoolerIndirectResearchSpecial::autosizeSecondaryFanFlowRate() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->autosizeSecondaryFanFlowRate();
}
bool EvaporativeCoolerIndirectResearchSpecial::setSecondaryFanTotalEfficiency(double secondaryFanTotalEfficiency) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setSecondaryFanTotalEfficiency(secondaryFanTotalEfficiency);
}
bool EvaporativeCoolerIndirectResearchSpecial::setSecondaryFanDeltaPressure(double secondaryFanDeltaPressure) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setSecondaryFanDeltaPressure(secondaryFanDeltaPressure);
}
void EvaporativeCoolerIndirectResearchSpecial::setDewpointEffectivenessFactor(double dewpointEffectivenessFactor) {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setDewpointEffectivenessFactor(dewpointEffectivenessFactor);
}
bool EvaporativeCoolerIndirectResearchSpecial::setDriftLossFraction(double driftLossFraction) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setDriftLossFraction(driftLossFraction);
}
void EvaporativeCoolerIndirectResearchSpecial::resetDriftLossFraction() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetDriftLossFraction();
}
bool EvaporativeCoolerIndirectResearchSpecial::setBlowdownConcentrationRatio(double blowdownConcentrationRatio) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setBlowdownConcentrationRatio(blowdownConcentrationRatio);
}
void EvaporativeCoolerIndirectResearchSpecial::resetBlowdownConcentrationRatio() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetBlowdownConcentrationRatio();
}
bool EvaporativeCoolerIndirectResearchSpecial::setWetbulbEffectivenessFlowRatioModifierCurve(const Curve& curve) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setWetbulbEffectivenessFlowRatioModifierCurve(curve);
}
void EvaporativeCoolerIndirectResearchSpecial::resetWetbulbEffectivenessFlowRatioModifierCurve() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetWetbulbEffectivenessFlowRatioModifierCurve();
}
bool EvaporativeCoolerIndirectResearchSpecial::setCoolerDrybulbDesignEffectiveness(double coolerDrybulbDesignEffectiveness) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setCoolerDrybulbDesignEffectiveness(coolerDrybulbDesignEffectiveness);
}
void EvaporativeCoolerIndirectResearchSpecial::resetCoolerDrybulbDesignEffectiveness() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetCoolerDrybulbDesignEffectiveness();
}
bool EvaporativeCoolerIndirectResearchSpecial::setDrybulbEffectivenessFlowRatioModifierCurve(const Curve& curve) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setDrybulbEffectivenessFlowRatioModifierCurve(curve);
}
void EvaporativeCoolerIndirectResearchSpecial::resetDrybulbEffectivenessFlowRatioModifierCurve() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetDrybulbEffectivenessFlowRatioModifierCurve();
}
void EvaporativeCoolerIndirectResearchSpecial::setWaterPumpPowerSizingFactor(double waterPumpPowerSizingFactor) {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setWaterPumpPowerSizingFactor(waterPumpPowerSizingFactor);
}
bool EvaporativeCoolerIndirectResearchSpecial::setWaterPumpPowerModifierCurve(const Curve& curve) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setWaterPumpPowerModifierCurve(curve);
}
void EvaporativeCoolerIndirectResearchSpecial::resetWaterPumpPowerModifierCurve() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetWaterPumpPowerModifierCurve();
}
void EvaporativeCoolerIndirectResearchSpecial::setSecondaryAirFlowScalingFactor(double secondaryAirFlowScalingFactor) {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setSecondaryAirFlowScalingFactor(secondaryAirFlowScalingFactor);
}
void EvaporativeCoolerIndirectResearchSpecial::setSecondaryAirFanDesignPower(double secondaryAirFanDesignPower) {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setSecondaryAirFanDesignPower(secondaryAirFanDesignPower);
}
void EvaporativeCoolerIndirectResearchSpecial::autosizeSecondaryAirFanDesignPower() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->autosizeSecondaryAirFanDesignPower();
}
bool EvaporativeCoolerIndirectResearchSpecial::setSecondaryAirFanPowerModifierCurve(const Curve& curve) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setSecondaryAirFanPowerModifierCurve(curve);
}
void EvaporativeCoolerIndirectResearchSpecial::resetSecondaryAirFanPowerModifierCurve() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetSecondaryAirFanPowerModifierCurve();
}
bool EvaporativeCoolerIndirectResearchSpecial::setPrimaryDesignAirFlowRate(double primaryDesignAirFlowRate) {
return getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->setPrimaryDesignAirFlowRate(primaryDesignAirFlowRate);
}
void EvaporativeCoolerIndirectResearchSpecial::resetPrimaryDesignAirFlowRate() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->resetPrimaryDesignAirFlowRate();
}
void EvaporativeCoolerIndirectResearchSpecial::autosizePrimaryDesignAirFlowRate() {
getImpl<detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->autosizePrimaryDesignAirFlowRate();
}
/// @cond
EvaporativeCoolerIndirectResearchSpecial::EvaporativeCoolerIndirectResearchSpecial(std::shared_ptr<detail::EvaporativeCoolerIndirectResearchSpecial_Impl> impl)
: StraightComponent(impl)
{}
/// @endcond
} // model
} // openstudio
| 48.755495 | 165 | 0.807714 | [
"vector",
"model"
] |
f6776803f2fa96ba832948a6042bd0b6a4af057f | 7,181 | cpp | C++ | Day17/src/main.cpp | tux2nicolae/AOC-2019 | f69f873b28954396a6adc1a6d179c62a8155683c | [
"MIT"
] | null | null | null | Day17/src/main.cpp | tux2nicolae/AOC-2019 | f69f873b28954396a6adc1a6d179c62a8155683c | [
"MIT"
] | null | null | null | Day17/src/main.cpp | tux2nicolae/AOC-2019 | f69f873b28954396a6adc1a6d179c62a8155683c | [
"MIT"
] | 1 | 2019-12-11T15:18:18.000Z | 2019-12-11T15:18:18.000Z | /**
* Advent of code 2019
* @author : Nicolae Telechi
*/
#include <iostream>
#include <fstream>
#include <string>
#include <memory>
#include <algorithm>
#include <vector>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <unordered_map>
#include <optional>
#include <numeric>
#include <assert.h>
#include <stack>
#include <queue>
#include <thread>
#include <chrono>
using namespace std;
#include "../../AOCLib/src/Algorithm.h"
#include "../../AOCLib/src/FStreamReader.h"
#include "../../AOCLib/src/FStreamWriter.h"
#include "../../AOCLib/src/Math.h"
#include "../../AOCLib/src/Time.h"
#include "robot.h"
struct Space
{
bool continuousFeed = false;
string main = "A,B,A,C,B,A,B,C,C,B";
string functionA = "L,12,L,12,R,4";
string functionB = "R,10,R,6,R,4,R,4";
string functionC = "R,6,L,12,L,12";
char GetInput()
{
auto c = mInput.front();
mInput.erase(0, 1);
return c;
};
int lastC = 0;
void reportMap(int c)
{
assert(c != 0);
static int reportI = 0, reportJ = 0;
space[{reportI, reportJ++}] = c;
cout << char(c);
lastC = c;
if (c == 10)
{
++reportI;
reportJ = 0;
}
}
//------------------------------------------------------
string calculatePath() {
string str = "";
while(true)
{
if (space.find(robot.GetRight()) != end(space) && space[robot.GetRight()] == '#')
{
str += "R,";
robot.turnRight();
}
else if(space.find(robot.GetLeft()) != end(space) && space[robot.GetLeft()] == '#')
{
str += "L,";
robot.turnLeft();
}
int frontN = 0;
while (space.find(robot.GetFront()) != end(space) && space[robot.GetFront()] == '#')
{
frontN++;
robot.moveForward();
}
if (frontN == 0)
break;
str += to_string(frontN) + ",";
}
return str;
};
int calculateIntersectionsAlignment()
{
minX = numeric_limits<int>::max();
minY = numeric_limits<int>::max();
maxX = 0;
maxY = 0;
for (auto [pixel, value] : space)
{
minX = std::min(minX, pixel.x);
minY = std::min(minY, pixel.y);
maxX = std::max(maxX, pixel.x);
maxY = std::max(maxY, pixel.y);
if (value == '^')
robot.setPosition(pixel);
}
for (int i = minX + 1; i <= maxX - 1; i++)
{
for (int j = minY + 1; j <= maxY - 1; j++)
{
if (space[{i, j}] == '#'
&& space[{i - 1, j}] == '#'
&& space[{i + 1, j}] == '#'
&& space[{i, j - 1}] == '#'
&& space[{i, j + 1}] == '#')
{
intersections.push_back({ i, j });
}
}
}
int sum = 0;
for (const auto & point : intersections)
{
int alignmentParamenter = (point.x - minX) * (point.y - minY);
sum += alignmentParamenter;
}
return sum;
};
//------------------------------------------------------
void printMap(ostream& out)
{
int minX = numeric_limits<int>::max();
int minY = numeric_limits<int>::max();
int maxX = 0;
int maxY = 0;
for (auto pixel : space)
{
minX = std::min(minX, pixel.first.x);
minY = std::min(minY, pixel.first.y);
maxX = std::max(maxX, pixel.first.x);
maxY = std::max(maxY, pixel.first.y);
}
for (int i = minX; i <= maxX; i++)
{
for (int j = minY; j <= maxY; j++)
{
out.width(4);
out << char(space[{i, j}]);
}
out << endl;
}
}
void generateInputData()
{
mInput = main + "\n" +
functionA + "\n" +
functionB + "\n" +
functionC + "\n" +
(continuousFeed ? "y\n" : "n\n");
}
private:
Robot robot;
map<AOC::Point, int> space;
int minX{};
int minY{};
int maxX{};
int maxY{};
string mInput;
vector<AOC::Point> intersections;
};
Space space;
using INT = long long;
class IntCodeComputer {
public:
IntCodeComputer(const vector<INT>& memory)
: memory(memory)
{
}
bool run(const vector<INT>& input)
{
AOC::Point outputPos;
while (true)
{
INT opcode = memory[++i] % 100;
if (opcode == 99)
{
return true;
}
INT aMode = (memory[i] / 100) % 10;
INT bMode = (memory[i] / 1000) % 10;
INT cMode = (memory[i] / 10000) % 10;
if (opcode == 1)
{
INT a = getValue(aMode);
INT b = getValue(bMode);
INT c = getOutputPos(cMode);
memory[c] = a + b;
}
else if (opcode == 2)
{
INT a = getValue(aMode);
INT b = getValue(bMode);
INT c = getOutputPos(cMode);
memory[c] = a * b;
}
// input
else if (opcode == 3)
{
INT a = getOutputPos(aMode);
memory[a] = space.GetInput();
}
// output
else if (opcode == 4)
{
INT a = getValue(aMode);
space.reportMap(a);
}
else if (opcode == 5)
{
INT a = getValue(aMode);
INT b = getValue(bMode);
if (a)
i = b - 1;
}
else if (opcode == 6)
{
INT a = getValue(aMode);
INT b = getValue(bMode);
if (!a)
i = b - 1;
}
else if (opcode == 7)
{
INT a = getValue(aMode);
INT b = getValue(bMode);
INT c = getOutputPos(cMode);
memory[c] = a < b;
}
else if (opcode == 8)
{
INT a = getValue(aMode);
INT b = getValue(bMode);
INT c = getOutputPos(cMode);
memory[c] = a == b;
}
else if (opcode == 9)
{
INT a = getValue(aMode);
mRelativeBase += a;
}
}
return true;
}
INT GetOutput() {
return mOutput;
};
private:
// address pointer
INT i{ -1 };
// memory
vector<INT> memory;
// output
INT mOutput{ 0 };
// relative base
INT mRelativeBase{ 0 };
//---------------------------------------
INT getValue(INT mode)
{
if (mode == 0)
{
size_t pos = memory[++i];
return memory[pos];
}
else if (mode == 1)
{
return memory[++i];
}
else if (mode == 2)
{
return memory[memory[++i] + mRelativeBase];
}
return 0;
}
INT getOutputPos(INT mode)
{
if (mode == 0)
return memory[++i];
if (mode == 2)
return memory[++i] + mRelativeBase;
assert(mode != 1);
return 0;
}
};
int main()
{
ifstream in("..\\..\\Day17\\src\\Day17.in");
ofstream out("..\\..\\Day17\\src\\Day17.out");
FStreamReader reader(in);
auto memory = reader.ReadVectorSeparatedByChar<INT>();
memory.resize(memory.size() + 10000000);
space.generateInputData();
vector<INT> input;
// create computer
memory[0] = 1;
IntCodeComputer mapComputer(memory);
mapComputer.run(input);
cout << endl;
cout << "part1:" << space.calculateIntersectionsAlignment() << endl;
cout << space.calculatePath() << endl;
// run
memory[0] = 2;
IntCodeComputer runComputer(memory);
runComputer.run(input);
cout << endl;
cout << endl;
cout << "part2:" << space.lastC << endl;
// space.printMap(out);
return 0;
}
| 18.749347 | 90 | 0.494917 | [
"vector"
] |
f6793bb268a2b671ad75e3a48b620ede4cd9281f | 10,868 | cc | C++ | tincan/trunk/src/tincan.cc | saumitraaditya/evio | aa0b118b07008cb08f8825e67614e58acc8660cf | [
"MIT"
] | null | null | null | tincan/trunk/src/tincan.cc | saumitraaditya/evio | aa0b118b07008cb08f8825e67614e58acc8660cf | [
"MIT"
] | null | null | null | tincan/trunk/src/tincan.cc | saumitraaditya/evio | aa0b118b07008cb08f8825e67614e58acc8660cf | [
"MIT"
] | null | null | null | /*
* EdgeVPNio
* Copyright 2020, University of Florida
*
* 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 "tincan.h"
#include "tincan_exception.h"
#include "turn_descriptor.h"
namespace tincan
{
Tincan::Tincan() :
exit_event_(false, false)
{}
Tincan::~Tincan()
{
}
void
Tincan::SetControllerLink(
//shared_ptr<ControllerLink> ctrl_handle)
ControllerLink * ctrl_handle)
{
ctrl_link_ = ctrl_handle;
}
void Tincan::CreateTunnel(
const Json::Value & tnl_desc,
Json::Value & tnl_info)
{
unique_ptr<TunnelDescriptor> td(new TunnelDescriptor);
td->uid = tnl_desc[TincanControl::TunnelId].asString();
td->node_id = tnl_desc[TincanControl::NodeId].asString();
if(IsTunnelExisit(td->uid))
throw TCEXCEPT("The specified Tunnel identifier already exists");
Json::Value stun_servers = tnl_desc["StunServers"];
for (Json::Value::ArrayIndex i = 0; i < stun_servers.size(); ++i)
{
td->stun_servers.push_back(stun_servers[i].asString());
}
Json::Value turn_servers = tnl_desc["TurnServers"];
for (Json::Value::ArrayIndex i = 0; i < turn_servers.size(); ++i)
{
TurnDescriptor turn_desc(
turn_servers[i]["Address"].asString(),
turn_servers[i]["User"].asString(),
turn_servers[i]["Password"].asString());
td->turn_descs.push_back(turn_desc);
}
td->enable_ip_mapping = false;
unique_ptr<BasicTunnel> tnl;
if(tnl_desc[TincanControl::Type].asString() == "VNET")
{
tnl = make_unique<MultiLinkTunnel>(move(td), ctrl_link_);
}
else if(tnl_desc[TincanControl::Type].asString() == "TUNNEL")
{
tnl = make_unique<SingleLinkTunnel>(move(td), ctrl_link_);
}
else
throw TCEXCEPT("Invalid Tunnel type specified");
unique_ptr<TapDescriptor> tap_desc = make_unique<TapDescriptor>();
tap_desc->name = tnl_desc["TapName"].asString();
tap_desc->ip4 = tnl_desc["IP4"].asString();
tap_desc->prefix4 = tnl_desc["IP4PrefixLen"].asUInt();
tap_desc->mtu4 = tnl_desc[TincanControl::MTU4].asUInt();
Json::Value network_ignore_list =
tnl_desc[TincanControl::IgnoredNetInterfaces];
int count = network_ignore_list.size();
vector<string> if_list(count);
for (int i = 0; i < count; i++)
{
if_list[i] = network_ignore_list[i].asString();
}
tnl->Configure(move(tap_desc), if_list);
tnl->Start();
tnl->QueryInfo(tnl_info);
lock_guard<mutex> lg(tunnels_mutex_);
tunnels_.push_back(move(tnl));
return;
}
void
Tincan::CreateVlink(
const Json::Value & link_desc,
const TincanControl & control)
{
unique_ptr<VlinkDescriptor> vl_desc = make_unique<VlinkDescriptor>();
vl_desc->uid = link_desc[TincanControl::LinkId].asString();
unique_ptr<Json::Value> resp = make_unique<Json::Value>(Json::objectValue);
Json::Value & tnl_info = (*resp)[TincanControl::Message];
string tnl_id = link_desc[TincanControl::TunnelId].asString();
if(!IsTunnelExisit(tnl_id))
{
CreateTunnel(link_desc, tnl_info);
}
else
{
TunnelFromId(tnl_id).QueryInfo(tnl_info);
}
unique_ptr<PeerDescriptor> peer_desc = make_unique<PeerDescriptor>();
peer_desc->uid =
link_desc[TincanControl::PeerInfo][TincanControl::UID].asString();
peer_desc->vip4 =
link_desc[TincanControl::PeerInfo][TincanControl::VIP4].asString();
peer_desc->cas =
link_desc[TincanControl::PeerInfo][TincanControl::CAS].asString();
peer_desc->fingerprint =
link_desc[TincanControl::PeerInfo][TincanControl::FPR].asString();
peer_desc->mac_address =
link_desc[TincanControl::PeerInfo][TincanControl::MAC].asString();
vl_desc->dtls_enabled = true;
BasicTunnel & tnl = TunnelFromId(tnl_id);
shared_ptr<VirtualLink> vlink =
tnl.CreateVlink(move(vl_desc), move(peer_desc));
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>(control);
if(!vlink->IsGatheringComplete())
{
ctrl->SetResponse(move(resp));
std::lock_guard<std::mutex> lg(inprogess_controls_mutex_);
inprogess_controls_[link_desc[TincanControl::LinkId].asString()]
= move(ctrl);
vlink->SignalLocalCasReady.connect(this, &Tincan::OnLocalCasUpdated);
}
else
{
(*resp)["Message"]["CAS"] = vlink->Candidates();
(*resp)["Success"] = true;
ctrl->SetResponse(move(resp));
ctrl_link_->Deliver(move(ctrl));
}
}
void
Tincan::InjectFrame(
const Json::Value & frame_desc)
{
const string & tnl_id = frame_desc[TincanControl::TunnelId].asString();
BasicTunnel & ol = TunnelFromId(tnl_id);
ol.InjectFame(frame_desc[TincanControl::Data].asString());
}
void
Tincan::QueryLinkCas(
const Json::Value & link_desc,
Json::Value & cas_info)
{
const string tnl_id = link_desc[TincanControl::TunnelId].asString();
const string vlid = link_desc[TincanControl::LinkId].asString();
BasicTunnel & ol = TunnelFromId(tnl_id);
ol.QueryLinkCas(vlid, cas_info);
}
void
Tincan::QueryLinkStats(
const Json::Value & tunnel_ids,
Json::Value & stat_info)
{
for(uint32_t i = 0; i < tunnel_ids["TunnelIds"].size(); i++)
{
vector<string>link_ids;
string tnl_id = tunnel_ids["TunnelIds"][i].asString();
BasicTunnel & ol = TunnelFromId(tnl_id);
ol.QueryLinkIds(link_ids);
for(auto vlid : link_ids)
{
ol.QueryLinkInfo(vlid, stat_info[tnl_id][vlid]);
}
}
}
void
Tincan::QueryTunnelInfo(
const Json::Value & tnl_desc,
Json::Value & tnl_info)
{
BasicTunnel & ol = TunnelFromId(tnl_desc[TincanControl::TunnelId].asString());
ol.QueryInfo(tnl_info);
}
void
Tincan::RemoveTunnel(
const Json::Value & tnl_desc)
{
const string tnl_id = tnl_desc[TincanControl::TunnelId].asString();
if(tnl_id.empty())
throw TCEXCEPT("No Tunnel ID was specified");
lock_guard<mutex> lg(tunnels_mutex_);
for(auto tnl = tunnels_.begin(); tnl != tunnels_.end(); tnl++)
{
if((*tnl)->Descriptor().uid.compare(tnl_id) == 0)
{
(*tnl)->Shutdown();
tunnels_.erase(tnl);
LOG(LS_INFO) << "RemoveTunnel: Instance erased from collection " << tnl_id;
return;
}
}
LOG(LS_WARNING) << "RemoveTunnel: No such virtual network exists " << tnl_id;
}
void
Tincan::RemoveVlink(
const Json::Value & link_desc)
{
const string tnl_id = link_desc[TincanControl::TunnelId].asString();
const string vlid = link_desc[TincanControl::LinkId].asString();
if(tnl_id.empty() || vlid.empty())
throw TCEXCEPT("Required identifier not specified");
lock_guard<mutex> lg(tunnels_mutex_);
for(auto & tnl : tunnels_)
{
if(tnl->Descriptor().uid.compare(tnl_id) == 0)
{
tnl->RemoveLink(vlid);
}
}
}
void
Tincan::SendIcc(
const Json::Value & icc_desc)
{
const string tnl_id = icc_desc[TincanControl::TunnelId].asString();
const string & link_id = icc_desc[TincanControl::LinkId].asString();
if(icc_desc[TincanControl::Data].isString())
{
const string & data = icc_desc[TincanControl::Data].asString();
BasicTunnel & ol = TunnelFromId(tnl_id);
ol.SendIcc(link_id, data);
}
else
throw TCEXCEPT("Icc data is not represented as a string");
}
void
Tincan::OnLocalCasUpdated(
string link_id,
string lcas)
{
if(lcas.empty())
{
lcas = "No local candidates available on this vlink";
LOG(LS_WARNING) << lcas;
}
bool to_deliver = false;
unique_ptr<TincanControl> ctrl;
{
std::lock_guard<std::mutex> lg(inprogess_controls_mutex_);
auto itr = inprogess_controls_.begin();
for(; itr != inprogess_controls_.end(); itr++)
{
if(itr->first == link_id)
{
to_deliver = true;
ctrl = move(itr->second);
Json::Value & resp = ctrl->GetResponse();
resp["Message"]["CAS"] = lcas;
resp["Success"] = true;
inprogess_controls_.erase(itr);
break;
}
}
}
if(to_deliver)
{
ctrl_link_->Deliver(move(ctrl));
}
}
void Tincan::UpdateRouteTable(
const Json::Value & rts_desc)
{
string tnl_id = rts_desc[TincanControl::TunnelId].asString();
BasicTunnel & ol = TunnelFromId(tnl_id);
ol.UpdateRouteTable(rts_desc["Table"]);
}
void
Tincan::Run()
{
//TODO:Code cleanup
#if defined(_TNC_WIN)
self_ = this;
SetConsoleCtrlHandler(ControlHandler, TRUE);
#endif // _TNC_WIN
//Start tincan control to get config from Controller
unique_ptr<ControlDispatch> ctrl_dispatch(new ControlDispatch);
ctrl_dispatch->SetDispatchToTincanInf(this);
ctrl_listener_ = make_shared<ControlListener>(move(ctrl_dispatch));
ctl_thread_.Start(ctrl_listener_.get());
exit_event_.Wait(Event::kForever);
}
bool
Tincan::IsTunnelExisit(
const string & tnl_id)
{
lock_guard<mutex> lg(tunnels_mutex_);
for(auto const & tnl : tunnels_) {
if(tnl->Descriptor().uid.compare(tnl_id) == 0)
return true;
}
return false;
}
BasicTunnel &
Tincan::TunnelFromId(
const string & tnl_id)
{
lock_guard<mutex> lg(tunnels_mutex_);
for(auto const & tnl : tunnels_)
{
//list of tunnels will be small enough where a linear search is satifactory
if(tnl->Descriptor().uid.compare(tnl_id) == 0)
return *tnl.get();
}
string msg("No virtual network exists by this name: ");
msg.append(tnl_id);
throw TCEXCEPT(msg.c_str());
}
//-----------------------------------------------------------------------------
void Tincan::OnStop() {
Shutdown();
exit_event_.Set();
}
void
Tincan::Shutdown()
{
lock_guard<mutex> lg(tunnels_mutex_);
ctl_thread_.Quit();
for(auto const & tnl : tunnels_) {
tnl->Shutdown();
}
tunnels_.clear();
}
/*
FUNCTION:ControlHandler
PURPOSE: Handles keyboard signals
PARAMETERS: The signal code
RETURN VALUE: Success/Failure
++*/
#if defined(_TNC_WIN)
BOOL __stdcall Tincan::ControlHandler(DWORD CtrlType) {
switch(CtrlType) {
case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to send
case CTRL_C_EVENT: // termination signal
cout << "Stopping tincan... " << std::endl;
self_->OnStop();
return(TRUE);
}
return(FALSE);
}
#endif // _TNC_WIN
} // namespace tincan
| 28.082687 | 81 | 0.693228 | [
"vector"
] |
f679c78e959b53f0a6c8764b73c16f240d14302f | 16,693 | cc | C++ | src/FF/source/SimpleFF.cc | asu-cactus/netsdb | fe6ae0e1dcd07ea0b9a47ff4a657d5ed029c7af5 | [
"Apache-2.0"
] | 13 | 2022-01-17T16:14:26.000Z | 2022-03-30T02:06:04.000Z | src/FF/source/SimpleFF.cc | asu-cactus/netsdb | fe6ae0e1dcd07ea0b9a47ff4a657d5ed029c7af5 | [
"Apache-2.0"
] | 1 | 2022-01-28T23:17:14.000Z | 2022-01-28T23:17:14.000Z | src/FF/source/SimpleFF.cc | asu-cactus/netsdb | fe6ae0e1dcd07ea0b9a47ff4a657d5ed029c7af5 | [
"Apache-2.0"
] | 3 | 2022-01-18T02:13:53.000Z | 2022-03-06T19:28:19.000Z | #include "SimpleFF.h"
#include "FFAggMatrix.h"
#include "FFInputLayerJoin.h"
#include "FFMatrixBlock.h"
#include "FFMatrixBlockScanner.h"
#include "FFMatrixData.h"
#include "FFMatrixMeta.h"
#include "FFMatrixWriter.h"
#include "FFOutputLayer.h"
#include "FFReluBiasSum.h"
#include "FFRowAggregate.h"
#include "FFTransposeBiasSum.h"
#include "FFTransposeMult.h"
#include "FFMatrixPartitioner.h"
#include "FFMatrixUtil.h"
#include "PDBClient.h"
#include "TensorBlock2D.h"
namespace ff {
void loadLibrary(pdb::PDBClient &pdbClient, string path) {
string errMsg;
if (!pdbClient.registerType(path, errMsg)) {
cout << "Couldnt include " << path << ": " << errMsg << endl;
exit(-1);
}
}
template <class T>
void createSetGeneric(pdb::PDBClient &pdbClient, std::string dbName,
std::string setName, std::string setName1, int size) {
string errMsg;
pdbClient.removeSet(dbName, setName, errMsg);
if (!pdbClient.createSet<T>(
dbName, setName, errMsg, (size_t)size * (size_t)1024 * (size_t)1024,
setName1)) {
cout << "Not able to create set: " + errMsg;
//exit(-1); //It is possible that the set exists
} else {
cout << "Created set.\n";
}
}
template void createSetGeneric<pdb::TensorBlock2D<float>>(pdb::PDBClient &pdbClient, std::string dbName,
std::string setName, std::string setName1, int size);
template void createSetGeneric<pdb::TensorBlock2D<double>>(pdb::PDBClient &pdbClient, std::string dbName,
std::string setName, std::string setName1, int size);
template void createSetGeneric<pdb::Vector<float>>(pdb::PDBClient &pdbClient, std::string dbName,
std::string setName, std::string setName1, int size);
template void createSetGeneric<pdb::Vector<double>>(pdb::PDBClient &pdbClient, std::string dbName,
std::string setName, std::string setName1, int size);
void createSet(pdb::PDBClient &pdbClient, string dbName, string setName, string setName1, int size) {
createSetGeneric<FFMatrixBlock>(pdbClient, dbName, setName, setName1, size);
}
void createSet(pdb::PDBClient &pdbClient, string dbName, string setName,
string setName1, string jobName, string computationName, string lambdaName, int size) {
string errMsg;
pdbClient.removeSet(dbName, setName, errMsg);
Handle<LambdaIdentifier> identifier = pdb::makeObject<LambdaIdentifier>(jobName, computationName, lambdaName);
if (!pdbClient.createSet<FFMatrixBlock>(
dbName, setName, errMsg, (size_t)size * (size_t)1024 * (size_t)1024,
setName1, nullptr, identifier)) {
cout << "Not able to create set: " + errMsg;
//exit(-1); //It is possible that the set exists
} else {
cout << "Created set.\n";
}
}
void createDatabase(pdb::PDBClient &pdbClient, string dbName) {
string errMsg;
pdbClient.removeDatabase(dbName, errMsg);
if (!pdbClient.createDatabase(dbName, errMsg)) {
cout << "Not able to create database: " << errMsg << endl;
//exit(-1); //It is possible that the database exists.
} else {
cout << "Created database" << endl;
}
}
void setup(pdb::PDBClient &pdbClient, string database) {
loadLibrary(pdbClient, "libraries/libFFMatrixMeta.so");
loadLibrary(pdbClient, "libraries/libFFMatrixData.so");
loadLibrary(pdbClient, "libraries/libFFMatrixBlock.so");
loadLibrary(pdbClient, "libraries/libFFMatrixBlockScanner.so");
loadLibrary(pdbClient, "libraries/libFFInputLayerJoin.so");
loadLibrary(pdbClient, "libraries/libFFMatrixWriter.so");
loadLibrary(pdbClient, "libraries/libFFAggMatrix.so");
loadLibrary(pdbClient, "libraries/libFFReluBiasSum.so");
loadLibrary(pdbClient, "libraries/libFFTransposeMult.so");
loadLibrary(pdbClient, "libraries/libFFTransposeBiasSum.so");
loadLibrary(pdbClient, "libraries/libFFRowAggregate.so");
loadLibrary(pdbClient, "libraries/libFFOutputLayer.so");
}
void cleanup(pdb::PDBClient &pdblient, string database) {
string errMsg;
// pdblient.removeSet(database, "y1", errMsg);
// pdblient.removeSet(database, "y2", errMsg);
// pdblient.removeSet(database, "yo", errMsg);
}
static bool materializeHash = true;
void inference_compute(pdb::PDBClient &pdbClient, string database, string w1,
string w2, string wo, string inputs, string b1,
string b2, string bo, double dropout_rate, bool enablePartition) {
string errMsg;
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
// make the computation
pdb::Handle<pdb::Computation> readA =
makeObject<FFMatrixBlockScanner>(database, w1);
pdb::Handle<pdb::Computation> readB =
makeObject<FFMatrixBlockScanner>(database, inputs);
pdb::Handle<pdb::Computation> join = pdb::makeObject<FFTransposeMult>();
join->setInput(0, readA);
join->setInput(1, readB);
// make the aggregation
pdb::Handle<pdb::Computation> myAggregation =
pdb::makeObject<FFAggMatrix>();
myAggregation->setInput(join);
pdb::Handle<pdb::Computation> readC =
makeObject<FFMatrixBlockScanner>(database, b1);
pdb::Handle<pdb::Computation> reluBias =
pdb::makeObject<FFReluBiasSum>(dropout_rate);
reluBias->setInput(0, myAggregation);
reluBias->setInput(1, readC);
// make the writer
pdb::Handle<pdb::Computation> myWriter = nullptr;
if (enablePartition)
myWriter = pdb::makeObject<FFMatrixPartitioner>(database, "y1");
else
myWriter = pdb::makeObject<FFMatrixWriter>(database, "y1");
myWriter->setInput(reluBias);
auto begin = std::chrono::high_resolution_clock::now();
// run the computation
if (!pdbClient.executeComputations(errMsg, "inference-1", materializeHash, myWriter)) {
cout << "Computation failed. Message was: " << errMsg << "\n";
exit(1);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Inference-1 Stage Time Duration: "
<< std::chrono::duration_cast<std::chrono::duration<float>>(end - begin).count()
<< " secs." << std::endl;
}
//pdbClient.flushData (errMsg);
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
#ifdef DEBUG_SIMPLE_FF
print_stats(pdbClient, database, w1);
print_stats(pdbClient, database, inputs);
print_stats(pdbClient, database, b1);
print_stats(pdbClient, database, "y1");
#endif
#ifdef DEBUG_SIMPLE_FF_VERBOSE
print(pdbClient, database, w1);
print(pdbClient, database, inputs);
print(pdbClient, database, b1);
print(pdbClient, database, "y1");
#endif
}
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
// make the computation
pdb::Handle<pdb::Computation> readA =
makeObject<FFMatrixBlockScanner>(database, w2);
pdb::Handle<pdb::Computation> readB =
makeObject<FFMatrixBlockScanner>(database, "y1");
pdb::Handle<pdb::Computation> join = pdb::makeObject<FFInputLayerJoin>();
join->setInput(0, readA);
join->setInput(1, readB);
// make the aggregation
pdb::Handle<pdb::Computation> myAggregation =
pdb::makeObject<FFAggMatrix>();
myAggregation->setInput(join);
pdb::Handle<pdb::Computation> readC =
makeObject<FFMatrixBlockScanner>(database, b2);
pdb::Handle<pdb::Computation> reluBias =
pdb::makeObject<FFReluBiasSum>(dropout_rate);
reluBias->setInput(0, myAggregation);
reluBias->setInput(1, readC);
// make the writer
pdb::Handle<pdb::Computation> myWriter = nullptr;
if (enablePartition)
myWriter = pdb::makeObject<FFMatrixPartitioner>(database, "y2");
else
myWriter = pdb::makeObject<FFMatrixWriter>(database, "y2");
myWriter->setInput(reluBias);
auto begin = std::chrono::high_resolution_clock::now();
// run the computation
if (!pdbClient.executeComputations(errMsg, "inference-2", materializeHash, myWriter)) {
cout << "Computation failed. Message was: " << errMsg << "\n";
exit(1);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Inference-2 Stage Time Duration: "
<< std::chrono::duration_cast<std::chrono::duration<float>>(end - begin).count()
<< " secs." << std::endl;
}
//pdbClient.flushData (errMsg);
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
#ifdef DEBUG_SIMPLE_FF
print_stats(pdbClient, database, w2);
print_stats(pdbClient, database, "y1");
print_stats(pdbClient, database, b2);
print_stats(pdbClient, database, "y2");
#endif
#ifdef DEBUG_SIMPLE_FF_VERBOSE
print(pdbClient, database, w2);
print(pdbClient, database, "y1");
print(pdbClient, database, b2);
print(pdbClient, database, "y2");
#endif
}
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
// make the computation
pdb::Handle<pdb::Computation> readA =
makeObject<FFMatrixBlockScanner>(database, wo);
pdb::Handle<pdb::Computation> readB =
makeObject<FFMatrixBlockScanner>(database, "y2");
pdb::Handle<pdb::Computation> join = pdb::makeObject<FFInputLayerJoin>();
join->setInput(0, readA);
join->setInput(1, readB);
// make the aggregation
pdb::Handle<pdb::Computation> myAggregation =
pdb::makeObject<FFAggMatrix>();
myAggregation->setInput(join);
pdb::Handle<pdb::Computation> readC =
makeObject<FFMatrixBlockScanner>(database, bo);
pdb::Handle<pdb::Computation> reluBias =
pdb::makeObject<FFTransposeBiasSum>();
reluBias->setInput(0, myAggregation);
reluBias->setInput(1, readC);
// make the writer
pdb::Handle<pdb::Computation> myWriter =
pdb::makeObject<FFMatrixWriter>(database, "yo");
myWriter->setInput(reluBias);
auto begin = std::chrono::high_resolution_clock::now();
// run the computation
if (!pdbClient.executeComputations(errMsg, "inference-3", materializeHash, myWriter)) {
cout << "Computation failed. Message was: " << errMsg << "\n";
exit(1);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Inference-3 Stage Time Duration: "
<< std::chrono::duration_cast<std::chrono::duration<float>>(end - begin).count()
<< " secs." << std::endl;
}
//pdbClient.flushData (errMsg);
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
#ifdef DEBUG_SIMPLE_FF
print_stats(pdbClient, database, wo);
print_stats(pdbClient, database, "y2");
print_stats(pdbClient, database, bo);
print_stats(pdbClient, database, "yo");
#endif
#ifdef DEBUG_SIMPLE_FF_VERBOSE
print(pdbClient, database, wo);
print(pdbClient, database, "y2");
print(pdbClient, database, bo);
print(pdbClient, database, "yo");
#endif
}
}
void inference(pdb::PDBClient &pdbClient, string database, string w1, string w2,
string wo, string inputs, string b1, string b2, string bo,
string output, double dropout_rate, bool enablePartition) {
string errMsg;
inference_compute(pdbClient, database, w1, w2, wo, inputs, b1, b2, bo,
dropout_rate, enablePartition);
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
// make the computation
pdb::Handle<pdb::Computation> readA =
makeObject<FFMatrixBlockScanner>(database, "yo");
pdb::Handle<pdb::Computation> expSum = pdb::makeObject<FFRowAggregate>();
expSum->setInput(readA);
pdb::Handle<pdb::Computation> softmax = pdb::makeObject<FFOutputLayer>();
softmax->setInput(0, readA);
softmax->setInput(1, expSum);
// make the writer
pdb::Handle<pdb::Computation> sumWriter =
pdb::makeObject<FFMatrixWriter>(database, output);
sumWriter->setInput(softmax);
auto begin = std::chrono::high_resolution_clock::now();
// run the computation
if (!pdbClient.executeComputations(errMsg, "inference-3", materializeHash, sumWriter)) {
cout << "Computation failed. Message was: " << errMsg << "\n";
exit(1);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Inference-3 Stage Time Duration: "
<< std::chrono::duration_cast<std::chrono::duration<float>>(end - begin).count()
<< " secs." << std::endl;
}
}
void inference_unit(pdb::PDBClient &pdbClient, string database, string w1,
string wo, string inputs, string b1, string bo,
string output, double dropout_rate, bool enablePartition) {
string errMsg;
{
const pdb::UseTemporaryAllocationBlock tempBlock{1024 * 1024 * 128};
// make the computation
pdb::Handle<pdb::Computation> readA =
makeObject<FFMatrixBlockScanner>(database, w1);
pdb::Handle<pdb::Computation> readB =
makeObject<FFMatrixBlockScanner>(database, inputs);
pdb::Handle<pdb::Computation> join = pdb::makeObject<FFTransposeMult>();
join->setInput(0, readA);
join->setInput(1, readB);
// make the aggregation
pdb::Handle<pdb::Computation> myAggregation =
pdb::makeObject<FFAggMatrix>();
myAggregation->setInput(join);
pdb::Handle<pdb::Computation> readC =
makeObject<FFMatrixBlockScanner>(database, b1);
pdb::Handle<pdb::Computation> reluBias =
pdb::makeObject<FFReluBiasSum>(dropout_rate);
reluBias->setInput(0, myAggregation);
reluBias->setInput(1, readC);
// make the computation
pdb::Handle<pdb::Computation> readD =
makeObject<FFMatrixBlockScanner>(database, wo);
pdb::Handle<pdb::Computation> join1 = pdb::makeObject<FFInputLayerJoin>();
join1->setInput(0, readD);
join1->setInput(1, reluBias);
// make the aggregation
pdb::Handle<pdb::Computation> myAggregation1 =
pdb::makeObject<FFAggMatrix>();
myAggregation1->setInput(join1);
pdb::Handle<pdb::Computation> readE =
makeObject<FFMatrixBlockScanner>(database, bo);
pdb::Handle<pdb::Computation> reluBias1 =
pdb::makeObject<FFTransposeBiasSum>();
reluBias1->setInput(0, myAggregation1);
reluBias1->setInput(1, readE);
pdb::Handle<pdb::Computation> intermediateWriter =
pdb::makeObject<FFMatrixWriter>(database, "yo");
intermediateWriter->setInput(reluBias1);
auto begin0 = std::chrono::high_resolution_clock::now();
// run the computation
if (!pdbClient.executeComputations(errMsg, "inference-unit-intermediate", materializeHash, intermediateWriter)) {
cout << "Computation failed. Message was: " << errMsg << "\n";
exit(1);
}
auto end0 = std::chrono::high_resolution_clock::now();
std::cout << "Inference-unit Intermediate Stage Time Duration: "
<< std::chrono::duration_cast<std::chrono::duration<float>>(end0 - begin0).count()
<< " secs." << std::endl;
pdb::Handle<pdb::Computation> readF =
makeObject<FFMatrixBlockScanner>(database, "yo");
pdb::Handle<pdb::Computation> expSum = pdb::makeObject<FFRowAggregate>();
expSum->setInput(readF);
pdb::Handle<pdb::Computation> softmax = pdb::makeObject<FFOutputLayer>();
softmax->setInput(0, readF);
softmax->setInput(1, expSum);
// make the writer
pdb::Handle<pdb::Computation> sumWriter =
pdb::makeObject<FFMatrixWriter>(database, output);
sumWriter->setInput(softmax);
auto begin = std::chrono::high_resolution_clock::now();
// run the computation
if (!pdbClient.executeComputations(errMsg, "inference-unit", materializeHash, sumWriter)) {
cout << "Computation failed. Message was: " << errMsg << "\n";
exit(1);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Inference-unit Stage Time Duration: "
<< std::chrono::duration_cast<std::chrono::duration<float>>(end - begin).count()
<< " secs." << std::endl;
}
}
void inference(pdb::PDBClient &pdbClient, string database, string w1, string w2,
string wo, string inputs, string b1, string b2, string bo,
pdb::Handle<pdb::Computation> &output, double dropout_rate, bool enablePartition) {
string errMsg;
inference_compute(pdbClient, database, w1, w2, wo, inputs, b1, b2, bo,
dropout_rate, enablePartition);
// make the computation
pdb::Handle<pdb::Computation> readA =
makeObject<FFMatrixBlockScanner>(database, "yo");
pdb::Handle<pdb::Computation> expSum = pdb::makeObject<FFRowAggregate>();
expSum->setInput(readA);
output = pdb::makeObject<FFOutputLayer>();
output->setInput(0, readA);
output->setInput(1, expSum);
}
} // namespace ff
| 35.592751 | 117 | 0.674594 | [
"vector"
] |
f67a4e9685e4a0474b5c4401efb7f776ecef64b8 | 25,669 | cpp | C++ | Engine/Source/Editor/Sequencer/Private/SequencerActorBindingManager.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Editor/Sequencer/Private/SequencerActorBindingManager.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Editor/Sequencer/Private/SequencerActorBindingManager.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "SequencerPrivatePCH.h"
#include "SequencerActorBindingManager.h"
#include "Sequencer.h"
#include "MovieScene.h"
#include "Toolkits/IToolkitHost.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "K2Node_PlayMovieScene.h"
#include "MovieSceneInstance.h"
#include "Engine/LevelScriptBlueprint.h"
#include "Editor/Kismet/Public/BlueprintEditorModule.h"
#include "SNotificationList.h"
#include "NotificationManager.h"
#include "Engine/Selection.h"
#include "LevelEditor.h"
#include "MovieSceneBindings.h"
#define LOCTEXT_NAMESPACE "Sequencer"
namespace EPuppetObjectType
{
enum Type
{
/** Puppet actor */
Actor,
};
}
/**
* Stores the relationship between a spawned puppet object (e.g. actor) and it's data descriptor (e.g. blueprint)
*/
class FBasePuppetInfo
{
public:
/** @return Gets the type of puppet */
virtual EPuppetObjectType::Type GetType() const = 0;
};
/**
* Puppet actor info
*/
struct FPuppetActorInfo : public FBasePuppetInfo
{
public:
virtual ~FPuppetActorInfo() {}
/** @return Gets the type of puppet */
virtual EPuppetObjectType::Type GetType() const override
{
return EPuppetObjectType::Actor;
}
public:
/** Spawnable guid */
FGuid SpawnableGuid;
/** The actual puppet actor that we are actively managing. These actors actually live in the editor level
just like any other actor, but we'll directly manage their lifetimes while in the editor */
TWeakObjectPtr< class AActor > PuppetActor;
};
FSequencerActorBindingManager::FSequencerActorBindingManager( TSharedRef<ISequencerObjectChangeListener> InObjectChangeListener, TSharedRef<FSequencer> InSequencer )
: PlayMovieSceneNode( nullptr )
, Sequencer( InSequencer )
, ObjectChangeListener( InObjectChangeListener )
{
// Register to be notified when object changes should be propagated
InObjectChangeListener->GetOnPropagateObjectChanges().AddRaw( this, &FSequencerActorBindingManager::OnPropagateObjectChanges );
}
FSequencerActorBindingManager::~FSequencerActorBindingManager()
{
if( ObjectChangeListener.IsValid() )
{
ObjectChangeListener.Pin()->GetOnPropagateObjectChanges().RemoveAll( this );
}
if( PlayMovieSceneNode.IsValid() )
{
PlayMovieSceneNode->OnBindingsChanged().RemoveAll( this );
PlayMovieSceneNode.Reset();
}
}
FGuid FSequencerActorBindingManager::FindGuidForObject( const UMovieScene& MovieScene, UObject& Object ) const
{
FGuid ObjectGuid = FindSpawnableGuidForPuppetObject( &Object );
if( !ObjectGuid.IsValid() )
{
// Spawnable
// Is this a game preview object?
const bool bIsGamePreviewObject = !!( Object.GetOutermost()->PackageFlags & PKG_PlayInEditor );
if( bIsGamePreviewObject )
{
// OK, so someone is asking for a handle to an object from a game preview session, probably because
// they want to capture keys during live simulation.
// Check to see if we already have a puppet that was generated from a recording of this game preview object
// @todo sequencer livecapture: We could support recalling counterpart by full name instead of weak pointer, to allow "overdubbing" of previously recorded actors, when the new actors in the current play session have the same path name
// @todo sequencer livecapture: Ideally we could capture from editor-world actors that are "puppeteered" as well (real time)
const FMovieSceneSpawnable* FoundSpawnable = MovieScene.FindSpawnableForCounterpart( &Object );
if( FoundSpawnable != NULL )
{
ObjectGuid = FoundSpawnable->GetGuid();
}
}
else
{
BindToPlayMovieSceneNode( false );
// Possessable
// When editing within the level editor, make sure we're bound to the level script node which contains data about possessables.
if( PlayMovieSceneNode.IsValid() )
{
UObject* Actor;
FString ComponentName;
UActorComponent* ComponentObject = Cast<UActorComponent>(&Object);
if (ComponentObject != nullptr)
{
Actor = ComponentObject->GetOuter();
ComponentName = ComponentObject->GetName();
}
else
{
Actor = &Object;
}
ObjectGuid = PlayMovieSceneNode->FindGuidForObjectInfo( FMovieSceneBoundObjectInfo(Actor, ComponentName) );
}
}
}
return ObjectGuid;
}
void FSequencerActorBindingManager::SpawnOrDestroyObjectsForInstance( TSharedRef<FMovieSceneInstance> MovieSceneInstance, const bool bDestroyAll )
{
bool bAnyLevelActorsChanged = false;
// Get the list of puppet objects for the movie scene
TArray< TSharedRef<FPuppetActorInfo> >& PuppetObjects = InstanceToPuppetObjectsMap.FindOrAdd( MovieSceneInstance );
UMovieScene* MovieScene = MovieSceneInstance->GetMovieScene();
UWorld* ActorWorld = GetWorld();
// Remove any puppet objects that we no longer need
if( MovieScene )
{
for( auto PuppetObjectIndex = 0; PuppetObjectIndex < PuppetObjects.Num(); ++PuppetObjectIndex )
{
if( PuppetObjects[ PuppetObjectIndex ]->GetType() == EPuppetObjectType::Actor )
{
TSharedRef< FPuppetActorInfo > PuppetActorInfo = StaticCastSharedRef< FPuppetActorInfo >( PuppetObjects[ PuppetObjectIndex ] );
// Figure out if we still need this puppet actor
bool bShouldDestroyActor = true;
if( !bDestroyAll )
{
for( auto SpawnableIndex = 0; SpawnableIndex < MovieScene->GetSpawnableCount(); ++SpawnableIndex )
{
auto& Spawnable = MovieScene->GetSpawnable( SpawnableIndex );
if( Spawnable.GetGuid() == PuppetActorInfo->SpawnableGuid )
{
bShouldDestroyActor = false;
break;
}
}
}
if( bShouldDestroyActor )
{
AActor* PuppetActor = PuppetActorInfo->PuppetActor.Get();
if( PuppetActor != NULL )
{
UWorld* PuppetWorld = PuppetActor->GetWorld();
if( ensure( PuppetWorld != NULL ) )
{
// Destroy this actor
{
// Ignored unless called while game is running
const bool bNetForce = false;
// We don't want to dirty the level for puppet actor changes
const bool bShouldModifyLevel = false;
if( !bAnyLevelActorsChanged )
{
DeselectAllPuppetObjects();
}
// Actor should never be selected in the editor at this point. We took care of that up above.
ensure( !PuppetActor->IsSelected() );
const bool bWasDestroyed = PuppetWorld->DestroyActor( PuppetActor, bNetForce, bShouldModifyLevel );
if( bWasDestroyed )
{
bAnyLevelActorsChanged = true;
PuppetObjects.RemoveAt( PuppetObjectIndex-- );
}
else
{
// @todo sequencer: At least one puppet couldn't be cleaned up!
}
}
}
}
else
{
// Actor is no longer valid (probably the world was destroyed)
}
}
}
else
{
check(0); // Unhandled type
}
}
}
if( !bDestroyAll && MovieScene )
{
for( auto SpawnableIndex = 0; SpawnableIndex < MovieScene->GetSpawnableCount(); ++SpawnableIndex )
{
FMovieSceneSpawnable& Spawnable = MovieScene->GetSpawnable( SpawnableIndex );
// Must have a valid world for us to be able to do this
if( ActorWorld != NULL )
{
// Do we already have a puppet for this spawnable?
bool bIsAlreadySpawned = false;
for( auto PuppetIndex = 0; PuppetIndex < PuppetObjects.Num(); ++PuppetIndex )
{
auto& PuppetObject = PuppetObjects[ PuppetIndex ];
if( PuppetObject->SpawnableGuid == Spawnable.GetGuid() )
{
bIsAlreadySpawned = true;
break;
}
}
if( !bIsAlreadySpawned )
{
UClass* GeneratedClass = Spawnable.GetClass();
if ( GeneratedClass != NULL && GeneratedClass->IsChildOf(AActor::StaticClass()))
{
AActor* ActorCDO = CastChecked< AActor >( GeneratedClass->ClassDefaultObject );
const FVector SpawnLocation = ActorCDO->GetRootComponent()->RelativeLocation;
const FRotator SpawnRotation = ActorCDO->GetRootComponent()->RelativeRotation;
// @todo sequencer: We should probably spawn these in a specific sub-level!
// World->CurrentLevel = ???;
const FName PuppetActorName = NAME_None;
// Override the object flags so that RF_Transactional is not set. Puppet actors are never transactional
// @todo sequencer: These actors need to avoid any transaction history. However, RF_Transactional can currently be set on objects on the fly!
const EObjectFlags ObjectFlags = RF_Transient; // NOTE: We are omitting RF_Transactional intentionally
// @todo sequencer livecapture: Consider using SetPlayInEditorWorld() and RestoreEditorWorld() here instead
// @todo sequencer actors: We need to make sure puppet objects aren't copied into PIE/SIE sessions! They should be omitted from that duplication!
// Spawn the puppet actor
FActorSpawnParameters SpawnInfo;
SpawnInfo.Name = PuppetActorName;
SpawnInfo.ObjectFlags = ObjectFlags;
AActor* NewActor = ActorWorld->SpawnActor( GeneratedClass, &SpawnLocation, &SpawnRotation, SpawnInfo );
if( NewActor )
{
// @todo sequencer: We're naming the actor based off of the spawnable's name. Is that really what we want?
FActorLabelUtilities::SetActorLabelUnique(NewActor, Spawnable.GetName());
// Actor was spawned OK!
// Keep track of this actor
TSharedRef< FPuppetActorInfo > NewPuppetInfo( new FPuppetActorInfo() );
NewPuppetInfo->SpawnableGuid = Spawnable.GetGuid();
NewPuppetInfo->PuppetActor = NewActor;
PuppetObjects.Add( NewPuppetInfo );
}
else
{
// Actor failed to spawn
// @todo sequencer: What should we do when this happens to one or more actors?
}
}
}
}
}
}
}
void FSequencerActorBindingManager::RemoveMovieSceneInstance( TSharedRef<FMovieSceneInstance> MovieSceneInstance )
{
SpawnOrDestroyObjectsForInstance( MovieSceneInstance, true );
InstanceToPuppetObjectsMap.Remove( MovieSceneInstance );
}
void FSequencerActorBindingManager::DestroyAllSpawnedObjects()
{
const bool bDestroyAll = true;
for( auto MovieSceneIter = InstanceToPuppetObjectsMap.CreateConstIterator(); MovieSceneIter; ++MovieSceneIter )
{
SpawnOrDestroyObjectsForInstance( MovieSceneIter.Key().Pin().ToSharedRef(), bDestroyAll );
}
InstanceToPuppetObjectsMap.Empty();
}
bool FSequencerActorBindingManager::CanPossessObject( UObject& Object ) const
{
return Object.IsA<AActor>() || Object.IsA<UActorComponent>();
}
void FSequencerActorBindingManager::BindPossessableObject( const FGuid& PossessableGuid, UObject& PossessedObject )
{
// When editing within the level editor, make sure we're bound to the level script node which contains data about possessables.
const bool bCreateIfNotFound = true;
BindToPlayMovieSceneNode( bCreateIfNotFound );
//const FString& PossessableName = Object->GetName();
//const FGuid PossessableGuid = FocusedMovieScene->AddPossessable( PossessableName, Object->GetClass() );
//if (IsShotFilteringOn())
//{
// AddUnfilterableObject(PossessableGuid);
// }
// Bind the object to the handle
UObject* Actor;
FString ComponentName;
UActorComponent* ComponentObject = Cast<UActorComponent>(&PossessedObject);
if (ComponentObject != nullptr)
{
Actor = ComponentObject->GetOuter();
ComponentName = ComponentObject->GetName();
}
else
{
Actor = &PossessedObject;
}
TArray< FMovieSceneBoundObjectInfo > ObjectInfos;
ObjectInfos.Add( FMovieSceneBoundObjectInfo(Actor, ComponentName) );
PlayMovieSceneNode->BindPossessableToObjects( PossessableGuid, ObjectInfos );
// A possessable was created so we need to respawn its puppet
// SpawnOrDestroyPuppetObjects( FocusedMovieSceneInstance );
}
void FSequencerActorBindingManager::UnbindPossessableObjects( const FGuid& PossessableGuid )
{
if (PlayMovieSceneNode.IsValid())
{
PlayMovieSceneNode->UnbindPossessable(PossessableGuid);
}
}
void FSequencerActorBindingManager::GetRuntimeObjects( const TSharedRef<FMovieSceneInstance>& MovieSceneInstance, const FGuid& ObjectGuid, TArray<UObject*>& OutRuntimeObjects ) const
{
UObject* FoundSpawnedObject = FindPuppetObjectForSpawnableGuid( MovieSceneInstance, ObjectGuid );
if( FoundSpawnedObject )
{
// Spawnable
OutRuntimeObjects.Reset();
OutRuntimeObjects.Add( FoundSpawnedObject );
}
else
{
// Possessable
if (!PlayMovieSceneNode.IsValid())
{
BindToPlayMovieSceneNode(false);
}
if (PlayMovieSceneNode.IsValid())
{
for (FMovieSceneBoundObjectInfo& BoundObjectInfo : PlayMovieSceneNode->FindBoundObjectInfos(ObjectGuid))
{
if (BoundObjectInfo.Tag.IsEmpty() == false)
{
AActor* Actor = Cast<AActor>(BoundObjectInfo.Object);
if (Actor != nullptr)
{
for (UActorComponent* ActorComponent : Actor->GetComponents())
{
if (ActorComponent->GetName() == BoundObjectInfo.Tag)
{
OutRuntimeObjects.Add(ActorComponent);
}
}
}
}
else
{
OutRuntimeObjects.Add(BoundObjectInfo.Object);
}
}
}
}
}
bool FSequencerActorBindingManager::TryGetObjectBindingDisplayName(const TSharedRef<FMovieSceneInstance>& MovieSceneInstance, const FGuid& ObjectGuid, FText& DisplayName) const
{
TArray< UObject*> RuntimeObjects;
GetRuntimeObjects(MovieSceneInstance, ObjectGuid, RuntimeObjects);
for (int32 ObjIndex = 0; ObjIndex < RuntimeObjects.Num(); ++ObjIndex)
{
AActor* Actor = Cast<AActor>(RuntimeObjects[ObjIndex]);
if (Actor)
{
DisplayName = FText::FromString(Actor->GetActorLabel());
return true;
}
}
return false;
}
UObject* FSequencerActorBindingManager::GetParentObject( UObject* Object ) const
{
UActorComponent* Component = Cast<UActorComponent>(Object);
if (Component != nullptr)
{
return Component->GetOwner();
}
return nullptr;
}
UK2Node_PlayMovieScene* FSequencerActorBindingManager::FindPlayMovieSceneNodeInLevelScript( const UMovieScene* MovieScene ) const
{
// Grab the world object for this editor
check( MovieScene != NULL );
UWorld* ActorWorld = GetWorld();
// Search all levels in the specified world
for( TArray<ULevel*>::TConstIterator LevelIter( ActorWorld->GetLevels().CreateConstIterator() ); LevelIter; ++LevelIter )
{
auto* Level = *LevelIter;
if( Level != NULL )
{
// We don't want to create a level script if one doesn't exist yet. We just want to grab the one
// that we already have, if one exists.
const bool bDontCreate = true;
ULevelScriptBlueprint* LSB = Level->GetLevelScriptBlueprint( bDontCreate );
if( LSB != NULL )
{
TArray<UK2Node_PlayMovieScene*> EventNodes;
FBlueprintEditorUtils::GetAllNodesOfClass( LSB, EventNodes );
for( auto FoundNodeIter( EventNodes.CreateIterator() ); FoundNodeIter; ++FoundNodeIter )
{
UK2Node_PlayMovieScene* FoundNode = *FoundNodeIter;
if( FoundNode->GetMovieScene() == MovieScene )
{
return FoundNode;
}
}
}
}
}
return NULL;
}
UK2Node_PlayMovieScene* FSequencerActorBindingManager::CreateNewPlayMovieSceneNode( UMovieScene* MovieScene ) const
{
// Grab the world object for this editor
check( MovieScene != NULL );
UWorld* ActorWorld = GetWorld();
ULevel* Level = ActorWorld->GetCurrentLevel();
check( Level != NULL );
// Here, we'll create a level script if one does not yet exist.
const bool bDontCreate = false;
ULevelScriptBlueprint* LSB = Level->GetLevelScriptBlueprint( bDontCreate );
if( LSB != NULL )
{
UEdGraph* TargetGraph = NULL;
if( LSB->UbergraphPages.Num() > 0 )
{
TargetGraph = LSB->UbergraphPages[0]; // Just use the first graph
}
if( ensure( TargetGraph != NULL ) )
{
// Figure out a decent place to stick the node
const FVector2D NewNodePos = TargetGraph->GetGoodPlaceForNewNode();
// Create a new node
UK2Node_PlayMovieScene* TemplateNode = NewObject<UK2Node_PlayMovieScene>();
TemplateNode->SetMovieScene( MovieScene );
return FEdGraphSchemaAction_K2NewNode::SpawnNodeFromTemplate<UK2Node_PlayMovieScene>(TargetGraph, TemplateNode, NewNodePos);;
}
}
return NULL;
}
UK2Node_PlayMovieScene* FSequencerActorBindingManager::BindToPlayMovieSceneNode( const bool bCreateIfNotFound ) const
{
auto* MovieScene = Sequencer.Pin()->GetFocusedMovieScene();
// Update level script
UK2Node_PlayMovieScene* FoundPlayMovieSceneNode = FindPlayMovieSceneNodeInLevelScript( MovieScene );
if( FoundPlayMovieSceneNode == NULL )
{
if( bCreateIfNotFound )
{
// Couldn't find an existing node that uses this MovieScene, so we'll create one now.
FoundPlayMovieSceneNode = CreateNewPlayMovieSceneNode( MovieScene );
if( FoundPlayMovieSceneNode != NULL )
{
// Let the user know that we plopped down a new PlayMovieScene event in their level script graph
{
FNotificationInfo Info( LOCTEXT("AddedPlayMovieSceneEventToLevelScriptGraph", "A new event for this MovieScene was added to this level's script") );
Info.bFireAndForget = true;
Info.bUseThrobber = false;
Info.bUseSuccessFailIcons = false;
Info.bUseLargeFont = false;
Info.ExpireDuration = 5.0f; // Stay visible for awhile so the user has time to click "Show Graph" if they want to
// @todo sequencer: Needs better artwork (see DefaultStyle.cpp)
Info.Image = FEditorStyle::GetBrush( TEXT( "Sequencer.NotificationImage_AddedPlayMovieSceneEvent" ) );
struct Local
{
/**
* Called by our notification's hyperlink to open the Level Script editor and navigate to our newly-created PlayMovieScene node
*
* @param Sequencer The Sequencer we're using
* @param PlayMovieSceneNode The node that we need to jump to
*/
static void NavigateToPlayMovieSceneNode( UK2Node_PlayMovieScene* PlayMovieSceneNode )
{
check( PlayMovieSceneNode != NULL );
IBlueprintEditor* BlueprintEditor = NULL;
auto* LSB = CastChecked< ULevelScriptBlueprint >( PlayMovieSceneNode->GetBlueprint() );
// @todo sequencer: Support using world-centric editing here? (just need to set EToolkitMode::WorldCentric)
FAssetEditorManager::Get().OpenEditorForAsset( LSB );
if( BlueprintEditor != NULL )
{
const bool bRequestRename = false;
BlueprintEditor->JumpToHyperlink( PlayMovieSceneNode, false );
}
else
{
UE_LOG( LogSequencer, Warning, TEXT( "Unable to open Blueprint Editor to edit newly-created PlayMovieScene event" ) );
}
}
};
Info.Hyperlink = FSimpleDelegate::CreateStatic( &Local::NavigateToPlayMovieSceneNode, FoundPlayMovieSceneNode );
Info.HyperlinkText = LOCTEXT("AddedPlayMovieSceneEventToLevelScriptGraph_Hyperlink", "Show Graph");
TSharedPtr< SNotificationItem > NewNotification = FSlateNotificationManager::Get().AddNotification(Info);
}
}
}
}
if( PlayMovieSceneNode.Get() != FoundPlayMovieSceneNode )
{
if( PlayMovieSceneNode.IsValid() )
{
// Unhook from old node
PlayMovieSceneNode.Get()->OnBindingsChanged().RemoveAll( this );
}
PlayMovieSceneNode = FoundPlayMovieSceneNode;
if( PlayMovieSceneNode.IsValid() )
{
// Bind to the new node
PlayMovieSceneNode.Get()->OnBindingsChanged().AddSP( this, &FSequencerActorBindingManager::OnPlayMovieSceneBindingsChanged );
}
}
return PlayMovieSceneNode.Get();
}
UWorld* FSequencerActorBindingManager::GetWorld() const
{
if( FModuleManager::Get().IsModuleLoaded("LevelEditor") )
{
FLevelEditorModule& LevelEditorModule = FModuleManager::Get().GetModuleChecked<FLevelEditorModule>("LevelEditor");
return LevelEditorModule.GetFirstLevelEditor()->GetWorld();
}
return nullptr;
}
void FSequencerActorBindingManager::OnPlayMovieSceneBindingsChanged()
{
const bool bDestroyAll = false;
SpawnOrDestroyObjectsForInstance( Sequencer.Pin()->GetFocusedMovieSceneInstance(), bDestroyAll );
}
void FSequencerActorBindingManager::DeselectAllPuppetObjects()
{
TArray< AActor* > ActorsToDeselect;
for( auto MovieSceneIter( InstanceToPuppetObjectsMap.CreateConstIterator() ); MovieSceneIter; ++MovieSceneIter )
{
const TArray< TSharedRef<FPuppetActorInfo> >& PuppetObjects = MovieSceneIter.Value();
for( auto PuppetObjectIter( PuppetObjects.CreateConstIterator() ); PuppetObjectIter; ++PuppetObjectIter )
{
if( PuppetObjectIter->Get().GetType() == EPuppetObjectType::Actor )
{
TSharedRef< FPuppetActorInfo > PuppetActorInfo = StaticCastSharedRef< FPuppetActorInfo >( *PuppetObjectIter );
AActor* PuppetActor = PuppetActorInfo->PuppetActor.Get();
if( PuppetActor != NULL )
{
ActorsToDeselect.Add( PuppetActor );
}
}
}
}
if( ActorsToDeselect.Num() > 0 )
{
GEditor->GetSelectedActors()->BeginBatchSelectOperation();
GEditor->GetSelectedActors()->MarkBatchDirty();
for( auto ActorIt( ActorsToDeselect.CreateIterator() ); ActorIt; ++ActorIt )
{
GEditor->GetSelectedActors()->Deselect( *ActorIt );
}
GEditor->GetSelectedActors()->EndBatchSelectOperation();
}
}
void FSequencerActorBindingManager::OnPropagateObjectChanges( UObject* Object )
{
// @todo sequencer major: Many other types of changes to the puppet actor may occur which should be propagated (or disallowed?):
// - Deleting the puppet actor (Del key) should probably delete the reference actor and remove it from the MovieScene
// - Attachment changes
// - Replace/Convert operations?
// We only care about actor objects for this type of spawner. Note that sometimes we can get component objects passed in, but we'll
// rely on the caller also calling OnObjectPropertyChange for the outer Actor if a component property changes.
if( Object->IsA<AActor>() )
{
for( auto MovieSceneIter( InstanceToPuppetObjectsMap.CreateConstIterator() ); MovieSceneIter; ++MovieSceneIter )
{
const TArray< TSharedRef<FPuppetActorInfo> >& PuppetObjects = MovieSceneIter.Value();
// Is this an object that we care about?
for( auto PuppetObjectIter( PuppetObjects.CreateConstIterator() ); PuppetObjectIter; ++PuppetObjectIter )
{
if( PuppetObjectIter->Get().GetType() == EPuppetObjectType::Actor )
{
TSharedRef< FPuppetActorInfo > PuppetActorInfo = StaticCastSharedRef< FPuppetActorInfo >( *PuppetObjectIter );
AActor* PuppetActor = PuppetActorInfo->PuppetActor.Get();
if( PuppetActor != NULL )
{
if( PuppetActor == Object )
{
// @todo sequencer propagation: Don't propagate changes that are being auto-keyed or key-adjusted!
// Our puppet actor was modified.
PropagatePuppetActorChanges( PuppetActorInfo );
}
}
}
}
}
}
}
void FSequencerActorBindingManager::PropagatePuppetActorChanges( const TSharedRef< FPuppetActorInfo > PuppetActorInfo )
{
AActor* PuppetActor = PuppetActorInfo->PuppetActor.Get();
AActor* TargetActor = NULL;
{
// Find the spawnable for this puppet actor
FMovieSceneSpawnable* FoundSpawnable = NULL;
TArray< UMovieScene* > MovieScenesBeingEdited = Sequencer.Pin()->GetMovieScenesBeingEdited();
for( auto CurMovieSceneIt( MovieScenesBeingEdited.CreateIterator() ); CurMovieSceneIt; ++CurMovieSceneIt )
{
auto CurMovieScene = *CurMovieSceneIt;
FoundSpawnable = CurMovieScene->FindSpawnable( PuppetActorInfo->SpawnableGuid );
if( FoundSpawnable != NULL )
{
break;
}
}
if (ensure( FoundSpawnable != NULL && PuppetActor != NULL ))
{
UClass* ActorClass = FoundSpawnable->GetClass();
// The puppet actor's class should always be the blueprint that it was spawned from!
UClass* SpawnedActorClass = PuppetActor->GetClass();
check( ActorClass == SpawnedActorClass );
// We'll be copying properties into the class default object of the Blueprint's generated class
TargetActor = CastChecked<AActor>( ActorClass->GetDefaultObject() );
}
}
if( PuppetActor != NULL && TargetActor != NULL )
{
Sequencer.Pin()->CopyActorProperties( PuppetActor, TargetActor );
}
}
FGuid FSequencerActorBindingManager::FindSpawnableGuidForPuppetObject( UObject* Object ) const
{
for( auto MovieSceneIter( InstanceToPuppetObjectsMap.CreateConstIterator() ); MovieSceneIter; ++MovieSceneIter )
{
const TArray< TSharedRef<FPuppetActorInfo> >& PuppetObjects = MovieSceneIter.Value();
// Is this an object that we care about?
for( auto PuppetObjectIter( PuppetObjects.CreateConstIterator() ); PuppetObjectIter; ++PuppetObjectIter )
{
if( PuppetObjectIter->Get().GetType() == EPuppetObjectType::Actor )
{
TSharedRef< FPuppetActorInfo > PuppetActorInfo = StaticCastSharedRef< FPuppetActorInfo >( *PuppetObjectIter );
AActor* PuppetActor = PuppetActorInfo->PuppetActor.Get();
if( PuppetActor != NULL )
{
if( PuppetActor == Object )
{
// Found it!
return PuppetActorInfo->SpawnableGuid;
}
}
}
}
}
// Not found
return FGuid();
}
UObject* FSequencerActorBindingManager::FindPuppetObjectForSpawnableGuid( const TSharedRef<FMovieSceneInstance>& MovieSceneInstance, const FGuid& Guid ) const
{
const TArray< TSharedRef<FPuppetActorInfo> >* PuppetObjects = InstanceToPuppetObjectsMap.Find(MovieSceneInstance);
if (PuppetObjects == NULL)
{
return NULL;
}
for( auto PuppetObjectIter( PuppetObjects->CreateConstIterator() ); PuppetObjectIter; ++PuppetObjectIter )
{
if( PuppetObjectIter->Get().GetType() == EPuppetObjectType::Actor )
{
TSharedRef< FPuppetActorInfo > PuppetActorInfo = StaticCastSharedRef< FPuppetActorInfo >( *PuppetObjectIter );
if( PuppetActorInfo->SpawnableGuid == Guid )
{
return PuppetActorInfo->PuppetActor.Get();
}
}
}
// Not found
return NULL;
}
#undef LOCTEXT_NAMESPACE | 32.410354 | 237 | 0.720986 | [
"object"
] |
f67b7e7a74009ae0d435a2d80aa8cf3da728409a | 10,065 | cpp | C++ | tutorials/31_framebuffer_access/main.cpp | Speedwag00n/RadeonProRenderSDK | 015becd5b81c772c5edfa07b5469e32ecef5e6be | [
"Apache-2.0"
] | null | null | null | tutorials/31_framebuffer_access/main.cpp | Speedwag00n/RadeonProRenderSDK | 015becd5b81c772c5edfa07b5469e32ecef5e6be | [
"Apache-2.0"
] | 1 | 2021-04-03T09:39:52.000Z | 2021-04-03T09:39:52.000Z | tutorials/31_framebuffer_access/main.cpp | isabella232/RadeonProRenderSDK | 838267ae910b21b828dea098bf71ed03fc9ee8b4 | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************\
*
* Module Name simple_render.cpp
* Project Radeon ProRender rendering tutorial
*
* Description Radeon ProRender SDK tutorials
*
* Copyright 2011 - 2020 Advanced Micro Devices, Inc.
*
* All rights reserved. This notice is intended as a precaution against
* inadvertent publication and does not imply publication or any waiver
* of confidentiality. The year included in the foregoing notice is the
* year of creation of the work.
*
\*****************************************************************************/
#include "RadeonProRender.h"
#include "Math/mathutils.h"
#include "../common/common.h"
#include <cassert>
#include <iostream>
#define PI 3.1412f
int main()
{
// enable Radeon ProRender API trace
// set this before any rpr API calls
// rprContextSetParameterByKey1u(0,RPR_CONTEXT_TRACING_ENABLED,1);
std::cout << "Radeon ProRender SDK simple rendering tutorial.\n";
// Indicates whether the last operation has suceeded or not
rpr_int status = RPR_SUCCESS;
// Create OpenCL context using a single GPU
rpr_context context = NULL;
// Register Tahoe ray tracing plugin.
rpr_int tahoePluginID = rprRegisterPlugin(RPR_PLUGIN_FILE_NAME);
CHECK_NE(tahoePluginID , -1)
rpr_int plugins[] = { tahoePluginID };
size_t pluginCount = sizeof(plugins) / sizeof(plugins[0]);
// Create context using a single GPU
CHECK( rprCreateContext(RPR_API_VERSION, plugins, pluginCount, g_ContextCreationFlags, NULL, NULL, &context) );
// Set active plugin.
CHECK( rprContextSetActivePlugin(context, plugins[0]) );
rpr_material_system matsys=nullptr;
CHECK( rprContextCreateMaterialSystem(context, 0, &matsys) );
// Check if it is created successfully
if (status != RPR_SUCCESS)
{
std::cout << "Context creation failed: check your OpenCL runtime and driver versions.\n";
return -1;
}
std::cout << "Context successfully created.\n";
// Create a scene
rpr_scene scene=nullptr;
CHECK( rprContextCreateScene(context, &scene) );
// Create point light
rpr_light light=nullptr;
{
CHECK(rprContextCreatePointLight(context, &light));
// Create a transform: move 5 units in X axis, 8 units up Y axis, -2 units in Z axis
RadeonProRender::matrix lightm = RadeonProRender::translation(RadeonProRender::float3(0, 8, 10));
// Set transform for the light
CHECK(rprLightSetTransform(light, RPR_TRUE, &lightm.m00));
// Set light radiant power in Watts
CHECK(rprPointLightSetRadiantPower3f(light, 80, 80, 80));
// Attach the light to the scene
CHECK(rprSceneAttachLight(scene, light));
}
// Create env light
rpr_light env_light = nullptr;
rpr_image env_img = nullptr;
{
CHECK(rprContextCreateEnvironmentLight(context, &env_light));
const std::string pathImageFile = "../../Resources/Textures/envLightImage.exr";
CHECK(rprContextCreateImageFromFile(context, pathImageFile.c_str(), &env_img));
if (status == RPR_ERROR_IO_ERROR)
{
std::cout << "Error : " << pathImageFile << " not found.\n";
return -1;
}
// Set an image for the light to take the radiance values from
CHECK(rprEnvironmentLightSetImage(env_light, env_img));
// Set IBL as a background for the scene
CHECK(rprSceneAttachLight(scene, env_light));
}
// Create camera
rpr_camera camera=nullptr;
{
CHECK( rprContextCreateCamera(context, &camera) );
// Position camera in world space:
CHECK( rprCameraLookAt(camera, 5, 5, 20, 0, 0, 0, 0, 1, 0) );
CHECK( rprCameraSetFocalLength(camera, 10.f) );
// Set camera for the scene
CHECK( rprSceneSetCamera(scene, camera) );
}
// Set scene to render for the context
CHECK( rprContextSetScene(context, scene) );
// Create cube mesh
rpr_shape cube=nullptr;
{
CHECK(rprContextCreateMesh(context,
(rpr_float const*)&cube_data[0], 24, sizeof(vertex),
(rpr_float const*)((char*)&cube_data[0] + sizeof(rpr_float) * 3), 24, sizeof(vertex),
(rpr_float const*)((char*)&cube_data[0] + sizeof(rpr_float) * 6), 24, sizeof(vertex),
(rpr_int const*)indices, sizeof(rpr_int),
(rpr_int const*)indices, sizeof(rpr_int),
(rpr_int const*)indices, sizeof(rpr_int),
num_face_vertices, 12, &cube));
RadeonProRender::matrix m = RadeonProRender::translation(RadeonProRender::float3(-2, 0, 0));
CHECK(rprShapeSetTransform(cube, RPR_TRUE, &m.m00));
// Add cube into the scene
CHECK(rprSceneAttachShape(scene, cube));
}
// Create plane mesh
rpr_shape plane=nullptr;
{
CHECK(rprContextCreateMesh(context,
(rpr_float const*)&plane_data[0], 4, sizeof(vertex),
(rpr_float const*)((char*)&plane_data[0] + sizeof(rpr_float) * 3), 4, sizeof(vertex),
(rpr_float const*)((char*)&plane_data[0] + sizeof(rpr_float) * 6), 4, sizeof(vertex),
(rpr_int const*)indices, sizeof(rpr_int),
(rpr_int const*)indices, sizeof(rpr_int),
(rpr_int const*)indices, sizeof(rpr_int),
num_face_vertices, 2, &plane));
// Add plane into the scene
CHECK(rprSceneAttachShape(scene, plane));
}
// Create simple diffuse shader
rpr_material_node diffuse=nullptr;
{
CHECK(rprMaterialSystemCreateNode(matsys, RPR_MATERIAL_NODE_DIFFUSE, &diffuse));
// Set diffuse color parameter
CHECK(rprMaterialNodeSetInputFByKey(diffuse, RPR_MATERIAL_INPUT_COLOR, 0.5f, 1.0f, 0.5f, 1.f));
// Set shader for cube & plane meshes
CHECK(rprShapeSetMaterial(cube, diffuse));
CHECK(rprShapeSetMaterial(plane, diffuse));
}
// Create framebuffer to store rendering result
rpr_framebuffer_desc desc = { 800,600 };
// 4 component 32-bit float value each
rpr_framebuffer_format fmt = { 4, RPR_COMPONENT_TYPE_FLOAT32 };
rpr_framebuffer frame_buffer = nullptr;
rpr_framebuffer frame_buffer_resolved = nullptr;
CHECK(rprContextCreateFrameBuffer(context, fmt, &desc, &frame_buffer));
CHECK( rprContextCreateFrameBuffer(context, fmt, &desc, &frame_buffer_resolved) );
// Clear framebuffer to black color
CHECK(rprFrameBufferClear(frame_buffer));
// Set framebuffer for the context
CHECK(rprContextSetAOV(context, RPR_AOV_COLOR, frame_buffer));
// Progressively render an image
CHECK(rprContextSetParameterByKey1u(context,RPR_CONTEXT_ITERATIONS,128));
CHECK( rprContextRender(context) );
CHECK(rprContextResolveFrameBuffer(context,frame_buffer,frame_buffer_resolved,true));
// This can be uncommented to see the framebuffer
//CHECK( rprFrameBufferSaveToFile(frame_buffer_resolved, "31_temp.png") );
///////// Framebuffer Access Tutorial //////////
//
// We are going to take the frame_buffer_resolved data, and use it as a material texture for a plane.
size_t size = 0;
CHECK(rprFrameBufferGetInfo(frame_buffer_resolved, RPR_FRAMEBUFFER_DATA, 0, NULL, &size));
float* buffer = new float[size / sizeof(float)];
CHECK(rprFrameBufferGetInfo(frame_buffer_resolved, RPR_FRAMEBUFFER_DATA, size, buffer, 0));
//Apply this buffer as a texture
rpr_material_node diffuse1=nullptr;
rpr_material_node tex=nullptr;
rpr_image img1=nullptr;
{
rpr_image_format format;
format.num_components = 4;
format.type = RPR_COMPONENT_TYPE_FLOAT32;
rpr_image_desc desc2;
desc2.image_width = desc.fb_width;
desc2.image_height = desc.fb_height;
desc2.image_row_pitch = 0;
desc2.image_slice_pitch = 0;
desc2.image_depth = 0;
CHECK(rprContextCreateImage(context, format, &desc2, buffer, &img1));
CHECK(rprMaterialSystemCreateNode(matsys, RPR_MATERIAL_NODE_IMAGE_TEXTURE, &tex));
// Set image data
CHECK(rprMaterialNodeSetInputImageDataByKey(tex, RPR_MATERIAL_INPUT_DATA, img1));
CHECK(rprMaterialSystemCreateNode(matsys, RPR_MATERIAL_NODE_DIFFUSE, &diffuse1));
// Set diffuse color parameter to gray
CHECK(rprMaterialNodeSetInputNByKey(diffuse1, RPR_MATERIAL_INPUT_COLOR, tex));
//CHECK(rprMaterialNodeSetInputFByKey(diffuse1, RPR_MATERIAL_INPUT_COLOR, 1,0,0,0));
CHECK(rprShapeSetMaterial(plane, diffuse1));
}
//Remove the cube and turn plane to dislay the texture in front of us like a screenshot
CHECK(rprSceneDetachShape(scene, cube));
RadeonProRender::matrix m = RadeonProRender::rotation(RadeonProRender::float3(1, 0, 0), -PI / 2.0f);
CHECK(rprShapeSetTransform(plane, RPR_TRUE, &m.m00));
// set camera to point on the plane
CHECK( rprCameraSetFocalLength(camera, 75.f) );
CHECK( rprCameraLookAt(camera, 0, 0, 150, 0, 0, 0, 0, 1, 0) );
// move point light
RadeonProRender::matrix lightm = RadeonProRender::translation(RadeonProRender::float3(1, 1, 100));
CHECK(rprLightSetTransform(light, RPR_TRUE, &lightm.m00));
CHECK(rprPointLightSetRadiantPower3f(light, 30000, 30000, 30000));
// remove the env light
CHECK(rprSceneDetachLight(scene, env_light));
//Clear the buffer to render again
rprFrameBufferClear(frame_buffer);
// Progressively render an image
CHECK(rprContextSetParameterByKey1u(context,RPR_CONTEXT_ITERATIONS,NUM_ITERATIONS));
CHECK(rprContextRender(context));
CHECK(rprContextResolveFrameBuffer(context,frame_buffer,frame_buffer_resolved,true));
std::cout << "Rendering finished.\n";
//delete buffer;
delete[] buffer; buffer=nullptr;
// Save the result to file
CHECK( rprFrameBufferSaveToFile(frame_buffer_resolved, "31.png") );
// Release the stuff we created
CHECK(rprObjectDelete(tex));tex=nullptr;
CHECK(rprObjectDelete(img1));img1=nullptr;
CHECK(rprObjectDelete(diffuse1));diffuse1=nullptr;
CHECK(rprObjectDelete(matsys));matsys=nullptr;
CHECK(rprObjectDelete(env_light));env_light=nullptr;
CHECK(rprObjectDelete(env_img));env_img=nullptr;
CHECK(rprObjectDelete(plane));plane=nullptr;
CHECK(rprObjectDelete(cube));cube=nullptr;
CHECK(rprObjectDelete(light));light=nullptr;
CHECK(rprObjectDelete(diffuse));diffuse=nullptr;
CHECK(rprObjectDelete(scene));scene=nullptr;
CHECK(rprObjectDelete(camera));camera=nullptr;
CHECK(rprObjectDelete(frame_buffer));frame_buffer=nullptr;
CHECK(rprObjectDelete(frame_buffer_resolved));frame_buffer_resolved=nullptr;
CheckNoLeak(context);
CHECK(rprObjectDelete(context));context=nullptr; // Always delete the RPR Context in last.
return 0;
}
// Things to try in this tutorial:
// 1) Try to access other AOV | 35.565371 | 112 | 0.738897 | [
"mesh",
"render",
"transform"
] |
f67c0abdb9a859da514706354fae033a7fedba03 | 6,727 | hpp | C++ | utils/sdiy/io/numpy.hpp | inealey/SENSEI | 45d073d26e0cf05ebd64cfd81138d04e69f6d39d | [
"BSD-3-Clause-LBNL"
] | 11 | 2021-06-22T19:05:43.000Z | 2022-02-01T13:36:47.000Z | utils/sdiy/io/numpy.hpp | inealey/SENSEI | 45d073d26e0cf05ebd64cfd81138d04e69f6d39d | [
"BSD-3-Clause-LBNL"
] | 28 | 2021-07-22T17:52:57.000Z | 2022-03-31T15:31:28.000Z | utils/sdiy/io/numpy.hpp | inealey/SENSEI | 45d073d26e0cf05ebd64cfd81138d04e69f6d39d | [
"BSD-3-Clause-LBNL"
] | 8 | 2021-06-23T17:06:59.000Z | 2021-09-03T13:26:13.000Z | #ifndef DIY_IO_NMPY_HPP
#define DIY_IO_NMPY_HPP
#include <sstream>
#include <complex>
#include <stdexcept>
#include "../serialization.hpp"
#include "bov.hpp"
namespace sdiy
{
namespace io
{
class NumPy: public BOV
{
public:
NumPy(mpi::io::file& f):
BOV(f) {}
unsigned word_size() const { return word_size_; }
unsigned read_header()
{
BOV::Shape shape;
bool fortran;
size_t offset = parse_npy_header(shape, fortran);
if (fortran)
throw std::runtime_error("sdiy::io::NumPy cannot read data in fortran order");
BOV::set_offset(offset);
BOV::set_shape(shape);
return word_size_;
}
template<class T>
void write_header(int dim, const DiscreteBounds& bounds);
template<class T, class S>
void write_header(const S& shape);
private:
inline size_t parse_npy_header(BOV::Shape& shape, bool& fortran_order);
void save(sdiy::BinaryBuffer& bb, const std::string& s) { bb.save_binary(s.c_str(), s.size()); }
template<class T>
inline void convert_and_save(sdiy::BinaryBuffer& bb, const T& x)
{
std::ostringstream oss;
oss << x;
save(bb, oss.str());
}
private:
unsigned word_size_;
};
namespace detail
{
inline char big_endian();
template<class T>
char map_numpy_type();
}
}
}
// Modified from: https://github.com/rogersce/cnpy
// Copyright (C) 2011 Carl Rogers
// Released under MIT License
// license available at http://www.opensource.org/licenses/mit-license.php
size_t
sdiy::io::NumPy::
parse_npy_header(BOV::Shape& shape, bool& fortran_order)
{
char buffer[256];
file().read_at_all(0, buffer, 256);
std::string header(buffer, buffer + 256);
size_t nl = header.find('\n');
if (nl == std::string::npos)
throw std::runtime_error("parse_npy_header: failed to read the header");
header = header.substr(11, nl - 11 + 1);
size_t header_size = nl + 1;
int loc1, loc2;
//fortran order
loc1 = header.find("fortran_order")+16;
fortran_order = (header.substr(loc1,4) == "True" ? true : false);
//shape
unsigned ndims;
loc1 = header.find("(");
loc2 = header.find(")");
std::string str_shape = header.substr(loc1+1,loc2-loc1-1);
if(str_shape[str_shape.size()-1] == ',') ndims = 1;
else ndims = std::count(str_shape.begin(),str_shape.end(),',')+1;
shape.resize(ndims);
for(unsigned int i = 0;i < ndims;i++) {
loc1 = str_shape.find(",");
shape[i] = atoi(str_shape.substr(0,loc1).c_str());
str_shape = str_shape.substr(loc1+1);
}
//endian, word size, data type
//byte order code | stands for not applicable.
//not sure when this applies except for byte array
loc1 = header.find("descr")+9;
//bool littleEndian = (header[loc1] == '<' || header[loc1] == '|' ? true : false);
//assert(littleEndian);
//char type = header[loc1+1];
//assert(type == map_type(T));
std::string str_ws = header.substr(loc1+2);
loc2 = str_ws.find("'");
word_size_ = atoi(str_ws.substr(0,loc2).c_str());
return header_size;
}
template<class T>
void
sdiy::io::NumPy::
write_header(int dim, const DiscreteBounds& bounds)
{
std::vector<int> shape;
for (int i = 0; i < dim; ++i)
shape.push_back(bounds.max[i] - bounds.min[i] + 1);
write_header< T, std::vector<int> >(shape);
}
template<class T, class S>
void
sdiy::io::NumPy::
write_header(const S& shape)
{
BOV::set_shape(shape);
sdiy::MemoryBuffer dict;
save(dict, "{'descr': '");
sdiy::save(dict, detail::big_endian());
sdiy::save(dict, detail::map_numpy_type<T>());
convert_and_save(dict, sizeof(T));
save(dict, "', 'fortran_order': False, 'shape': (");
convert_and_save(dict, shape[0]);
for (int i = 1; i < (int) shape.size(); i++)
{
save(dict, ", ");
convert_and_save(dict, shape[i]);
}
if(shape.size() == 1) save(dict, ",");
save(dict, "), }");
//pad with spaces so that preamble+dict is modulo 16 bytes. preamble is 10 bytes. dict needs to end with \n
int remainder = 16 - (10 + dict.position) % 16;
for (int i = 0; i < remainder - 1; ++i)
sdiy::save(dict, ' ');
sdiy::save(dict, '\n');
sdiy::MemoryBuffer header;
sdiy::save(header, (char) 0x93);
save(header, "NUMPY");
sdiy::save(header, (char) 0x01); // major version of numpy format
sdiy::save(header, (char) 0x00); // minor version of numpy format
sdiy::save(header, (unsigned short) dict.position);
header.save_binary(&dict.buffer[0], dict.buffer.size());
BOV::set_offset(header.position);
if (file().comm().rank() == 0)
file().write_at(0, &header.buffer[0], header.buffer.size());
}
char
sdiy::io::detail::big_endian()
{
unsigned char x[] = {1,0};
void* x_void = x;
short y = *static_cast<short*>(x_void);
return y == 1 ? '<' : '>';
}
namespace sdiy
{
namespace io
{
namespace detail
{
template<> inline char map_numpy_type<float>() { return 'f'; }
template<> inline char map_numpy_type<double>() { return 'f'; }
template<> inline char map_numpy_type<long double>() { return 'f'; }
template<> inline char map_numpy_type<int>() { return 'i'; }
template<> inline char map_numpy_type<char>() { return 'i'; }
template<> inline char map_numpy_type<short>() { return 'i'; }
template<> inline char map_numpy_type<long>() { return 'i'; }
template<> inline char map_numpy_type<long long>() { return 'i'; }
template<> inline char map_numpy_type<unsigned int>() { return 'u'; }
template<> inline char map_numpy_type<unsigned char>() { return 'u'; }
template<> inline char map_numpy_type<unsigned short>() { return 'u'; }
template<> inline char map_numpy_type<unsigned long>() { return 'u'; }
template<> inline char map_numpy_type<unsigned long long>() { return 'u'; }
template<> inline char map_numpy_type<bool>() { return 'b'; }
template<> inline char map_numpy_type< std::complex<float> >() { return 'c'; }
template<> inline char map_numpy_type< std::complex<double> >() { return 'c'; }
template<> inline char map_numpy_type< std::complex<long double> >() { return 'c'; }
}
}
}
#endif
| 31.434579 | 129 | 0.581388 | [
"shape",
"vector"
] |
f681d314021bb5184e18cb6b99047b3522dd2d50 | 382 | cpp | C++ | src/ShinyColor.cpp | lzanotto/mo802-spitz | 3d3ce9f0fa6d345bd309aea5e2f4f64a8a4f4714 | [
"Apache-2.0"
] | 175 | 2015-01-03T21:50:11.000Z | 2022-03-07T00:20:08.000Z | src/ShinyColor.cpp | KsGin-Fork/RayTracer | 4c9f2dd389ace5f7601af367d2aa0e8db70b2b7d | [
"Apache-2.0"
] | 4 | 2016-08-04T10:13:04.000Z | 2020-10-26T09:36:35.000Z | src/ShinyColor.cpp | KsGin-Fork/RayTracer | 4c9f2dd389ace5f7601af367d2aa0e8db70b2b7d | [
"Apache-2.0"
] | 49 | 2015-03-04T16:13:21.000Z | 2022-02-23T00:27:13.000Z | #include "ShinyColor.h"
#include "Vector.h"
#include "Color.h"
ShinyColor::ShinyColor(std::istream& in) {
in >> color.r >> color.g >> color.b;
in >> shininess;
in >> reflectivity;
}
Color ShinyColor::getColor(Vector point) {
return color;
}
double ShinyColor::getShininess() {
return shininess;
}
double ShinyColor::getReflectivity() {
return reflectivity;
}
| 16.608696 | 42 | 0.67801 | [
"vector"
] |
f683fd48de4102f0a6bbbe867ed7587a80088ce4 | 3,016 | cc | C++ | tests/unittests/v8_unittest.cc | chromium-googlesource-mirror/chromiumembedded | f659ddbeb58e957a3c57a309cdcfc52c999fe719 | [
"BSD-3-Clause"
] | null | null | null | tests/unittests/v8_unittest.cc | chromium-googlesource-mirror/chromiumembedded | f659ddbeb58e957a3c57a309cdcfc52c999fe719 | [
"BSD-3-Clause"
] | null | null | null | tests/unittests/v8_unittest.cc | chromium-googlesource-mirror/chromiumembedded | f659ddbeb58e957a3c57a309cdcfc52c999fe719 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Embedded Framework 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 "include/cef_runnable.h"
#include "include/cef_v8.h"
#include "tests/unittests/test_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Base class for V8 unit tests.
class V8TestHandler : public TestHandler {
public:
explicit V8TestHandler(const std::string& code) {
html_ = "<html><head><script language=\"JavaScript\">" +
code +
"</script></head><body></body></html>";
}
virtual void RunTest() OVERRIDE {
const std::string url = "http://tests/run.html";
AddResource(url, html_, "text/html");
CreateBrowser(url);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
if (!browser->IsPopup() && frame->IsMain()) {
frame->ExecuteJavaScript("gc();", "", 0);
DestroyTest();
}
}
private:
std::string html_;
};
// Base class for V8 unit test handlers.
class V8TestV8Handler : public CefV8Handler {
IMPLEMENT_REFCOUNTING(V8TestV8Handler);
};
} // namespace
TEST(V8Test, ExternalMemoryAllocation) {
class Test : public V8TestV8Handler {
public:
static std::string GetExtensionCode() {
std::string code =
"function createObject() {"
" native function createObject();"
" return createObject();"
"}"
"function checkSize(object) {"
" native function checkSize();"
" return checkSize(object);"
"};";
return code;
}
static std::string GetTestCode() {
return "checkSize(createObject());";
}
Test()
: object_created_(false),
size_checked_(false) {
}
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
static const int kTestSize = 999999999;
if (name == "createObject") {
retval = CefV8Value::CreateObject(
CefRefPtr<CefBase>(), CefRefPtr<CefV8Accessor>());
object_created_ =
(retval->AdjustExternallyAllocatedMemory(kTestSize) == kTestSize);
return true;
} else if (name == "checkSize") {
size_checked_ =
arguments[0]->GetExternallyAllocatedMemory() == kTestSize;
return true;
}
return false;
}
bool object_created_;
bool size_checked_;
};
Test* test = new Test();
CefRegisterExtension("v8/externalMemory", test->GetExtensionCode(), test);
V8TestHandler* test_handler = new V8TestHandler(test->GetTestCode());
test_handler->ExecuteTest();
ASSERT_TRUE(test->object_created_);
ASSERT_TRUE(test->size_checked_);
}
| 28.72381 | 78 | 0.615053 | [
"object"
] |
f68413178bd58bfa9b31427596ff48c3fc6c076d | 21,287 | cpp | C++ | arangod/Indexes/SortedIndexAttributeMatcher.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | 1 | 2020-10-27T12:19:33.000Z | 2020-10-27T12:19:33.000Z | arangod/Indexes/SortedIndexAttributeMatcher.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | null | null | null | arangod/Indexes/SortedIndexAttributeMatcher.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | 1 | 2020-10-01T08:49:12.000Z | 2020-10-01T08:49:12.000Z | ////////////////////////////////////////////////////////////////////////////////
/// 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 Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include "SortedIndexAttributeMatcher.h"
#include "Aql/Ast.h"
#include "Aql/AstNode.h"
#include "Aql/SortCondition.h"
#include "Aql/Variable.h"
#include "Basics/StaticStrings.h"
#include "Indexes/Index.h"
#include "Indexes/SimpleAttributeEqualityMatcher.h"
#include "VocBase/vocbase.h"
#include <velocypack/StringRef.h>
using namespace arangodb;
bool SortedIndexAttributeMatcher::accessFitsIndex(
arangodb::Index const* idx, // index
arangodb::aql::AstNode const* access, // attribute access
arangodb::aql::AstNode const* other, // eg const value
arangodb::aql::AstNode const* op, // binary operation that is parent of access and other
arangodb::aql::Variable const* reference, // variable used in access(es)
std::unordered_map<size_t /*offset in idx->fields()*/, std::vector<arangodb::aql::AstNode const*> /*conjunct - operation*/>& found, // marks operations covered by index-fields
std::unordered_set<std::string>& nonNullAttributes, // set of stringified op-children (access other) that may not be null
bool isExecution // skip usage check in execution phase
) {
if (!idx->canUseConditionPart(access, other, op, reference, nonNullAttributes, isExecution)) {
return false;
}
std::pair<arangodb::aql::Variable const*, std::vector<arangodb::basics::AttributeName>> attributeData;
bool const isPrimaryIndex = idx->type() == arangodb::Index::IndexType::TRI_IDX_TYPE_PRIMARY_INDEX;
if (idx->type() == arangodb::Index::IndexType::TRI_IDX_TYPE_TTL_INDEX &&
(!other->isConstant() || !(other->isIntValue() || other->isDoubleValue()))) {
// TTL index can only be used for numeric lookup values, no date strings or
// anything else
// TODO: move this into the specific index class
return false;
}
if (op->type != arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN) {
if (!access->isAttributeAccessForVariable(attributeData) || attributeData.first != reference) {
// this access is not referencing this collection
return false;
}
if (arangodb::basics::TRI_AttributeNamesHaveExpansion(attributeData.second)) {
// doc.value[*] == 'value'
return false;
}
if (idx->isAttributeExpanded(attributeData.second)) {
// doc.value == 'value' (with an array index)
return false;
}
} else {
// ok, we do have an IN here... check if it's something like 'value' IN
// doc.value[*]
TRI_ASSERT(op->type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN);
if (access->isAttributeAccessForVariable(attributeData) && attributeData.first == reference &&
!arangodb::basics::TRI_AttributeNamesHaveExpansion(attributeData.second) &&
idx->attributeMatches(attributeData.second, isPrimaryIndex)) {
// doc.value IN 'value'
// can use this index
} else if (other->isAttributeAccessForVariable(attributeData) &&
attributeData.first == reference &&
idx->isAttributeExpanded(attributeData.second) &&
idx->attributeMatches(attributeData.second, isPrimaryIndex)) {
// check for 'value' IN doc.value AND 'value' IN doc.value[*]
} else {
return false;
}
}
std::vector<arangodb::basics::AttributeName> const& fieldNames = attributeData.second;
for (size_t i = 0; i < idx->fields().size(); ++i) {
if (idx->fields()[i].size() != fieldNames.size()) {
// attribute path length differs
continue;
}
if (idx->isAttributeExpanded(i) && op->type != arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN) {
// If this attribute is correct or not, it could only serve for IN
continue;
}
bool match = arangodb::basics::AttributeName::isIdentical(idx->fields()[i],
fieldNames, true);
// make exception for primary index as we do not need to match "_key, _id"
// but can go directly for "_id"
if (!match &&
isPrimaryIndex &&
i == 0 &&
fieldNames[i].name == StaticStrings::IdString) {
match = true;
}
if (match) {
// mark ith attribute as being covered
found[i].emplace_back(op);
TRI_IF_FAILURE("PersistentIndex::accessFitsIndex") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
TRI_IF_FAILURE("SkiplistIndex::accessFitsIndex") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
TRI_IF_FAILURE("HashIndex::accessFitsIndex") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
return true;
}
}
return false;
}
void SortedIndexAttributeMatcher::matchAttributes(
arangodb::Index const* idx, arangodb::aql::AstNode const* node,
arangodb::aql::Variable const* reference,
std::unordered_map<size_t, std::vector<arangodb::aql::AstNode const*>>& found,
size_t& postFilterConditions, size_t& values,
std::unordered_set<std::string>& nonNullAttributes, bool isExecution) {
// assert we have a properly formed condition - nary conjunction
TRI_ASSERT(node->type == arangodb::aql::NODE_TYPE_OPERATOR_NARY_AND);
// inspect the the conjuncts - allowed are binary comparisons and a contains check
for (size_t i = 0; i < node->numMembers(); ++i) {
bool matches = false;
auto op = node->getMemberUnchecked(i);
switch (op->type) {
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE:
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ:
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LT:
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE:
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT:
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE:
TRI_ASSERT(op->numMembers() == 2);
matches = accessFitsIndex(idx, op->getMemberUnchecked(0), op->getMemberUnchecked(1), op, reference,
found, nonNullAttributes, isExecution);
matches |= accessFitsIndex(idx, op->getMemberUnchecked(1), op->getMemberUnchecked(0), op, reference,
found, nonNullAttributes, isExecution);
break;
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN:
if (accessFitsIndex(idx, op->getMemberUnchecked(0), op->getMemberUnchecked(1), op,
reference, found, nonNullAttributes, isExecution)) {
matches = true;
if (op->getMemberUnchecked(1)->isAttributeAccessForVariable(reference, /*indexed access*/ false)) {
// 'abc' IN doc.attr[*]
++values;
} else {
size_t av = SimpleAttributeEqualityMatcher::estimateNumberOfArrayMembers(
op->getMemberUnchecked(1));
if (av > 1) {
// attr IN [ a, b, c ] => this will produce multiple items, so
// count them!
values += av - 1;
}
}
}
break;
default:
matches = false;
break;
}
if (!matches) {
// count the number of conditions we will not be able to satisfy
++postFilterConditions;
}
}
}
Index::FilterCosts SortedIndexAttributeMatcher::supportsFilterCondition(
std::vector<std::shared_ptr<arangodb::Index>> const& allIndexes,
arangodb::Index const* idx, arangodb::aql::AstNode const* node,
arangodb::aql::Variable const* reference, size_t itemsInIndex) {
// mmfiles failure point compat
if (idx->type() == Index::TRI_IDX_TYPE_HASH_INDEX) {
TRI_IF_FAILURE("SimpleAttributeMatcher::accessFitsIndex") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
}
std::unordered_map<size_t, std::vector<arangodb::aql::AstNode const*>> found;
std::unordered_set<std::string> nonNullAttributes;
size_t values = 0;
size_t postFilterConditions = 0;
matchAttributes(idx, node, reference, found, postFilterConditions, values, nonNullAttributes, false);
bool lastContainsEquality = true;
size_t attributesCovered = 0;
size_t attributesCoveredByEquality = 0;
double equalityReductionFactor = 20.0;
double estimatedItems = static_cast<double>(itemsInIndex);
for (size_t i = 0; i < idx->fields().size(); ++i) {
auto it = found.find(i);
if (it == found.end() || !lastContainsEquality) {
// index attribute not covered by condition, or unsupported condition.
// must abort
break;
}
++attributesCovered;
// check if the current condition contains an equality condition
auto const& nodes = (*it).second;
bool containsEquality = false;
for (size_t j = 0; j < nodes.size(); ++j) {
if (nodes[j]->type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ ||
nodes[j]->type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN) {
containsEquality = true;
break;
}
}
if (containsEquality) {
++attributesCoveredByEquality;
estimatedItems /= equalityReductionFactor;
// decrease the effect of the equality reduction factor
equalityReductionFactor *= 0.25;
if (equalityReductionFactor < 2.0) {
// equalityReductionFactor shouldn't get too low
equalityReductionFactor = 2.0;
}
} else {
// quick estimate for the potential reductions caused by the conditions
if (nodes.size() >= 2) {
// at least two (non-equality) conditions. probably a range with lower
// and upper bound defined
estimatedItems /= 7.5;
} else {
// one (non-equality). this is either a lower or a higher bound
estimatedItems /= 2.0;
}
}
lastContainsEquality = containsEquality;
}
if (values == 0) {
values = 1;
}
Index::FilterCosts costs = Index::FilterCosts::defaultCosts(itemsInIndex);
costs.coveredAttributes = attributesCovered;
if (attributesCovered > 0 &&
(!idx->sparse() || attributesCovered == idx->fields().size())) {
// if the condition contains at least one index attribute and is not sparse,
// or the index is sparse and all attributes are covered by the condition,
// then it can be used (note: additional checks for condition parts in
// sparse indexes are contained in Index::canUseConditionPart)
costs.supportsCondition = true;
if (itemsInIndex > 0) {
estimatedItems = static_cast<double>(estimatedItems * values);
// check if the index has a selectivity estimate ready
if (idx->hasSelectivityEstimate() &&
attributesCoveredByEquality == idx->fields().size()) {
double estimate = idx->selectivityEstimate();
if (estimate > 0.0) {
estimatedItems = static_cast<double>(1.0 / estimate * values);
}
} else if (attributesCoveredByEquality > 0) {
TRI_ASSERT(attributesCovered > 0);
// the index either does not have a selectivity estimate, or not all
// of its attributes are covered by the condition using an equality lookup
// however, if the search condition uses equality lookups on the prefix
// of the index, then we can check if there is another index which is just
// indexing the prefix, and "steal" the selectivity estimate from that
// index for example, if the condition is "doc.a == 1 && doc.b > 2", and
// the current index is created on ["a", "b"], then we will not use the
// selectivity estimate of the current index (due to the range condition
// used for the second index attribute). however, if there is another
// index on just "a", we know that the current index is at least as
// selective as the index on the single attribute. and that the extra
// condition we have will make it even more selectivity. so in this case
// we will re-use the selectivity estimate from the other index, and are
// happy.
for (auto const& otherIdx : allIndexes) {
auto const* other = otherIdx.get();
if (other == idx || !other->hasSelectivityEstimate()) {
continue;
}
auto const& otherFields = other->fields();
if (otherFields.size() >= attributesCovered) {
// other index has more fields than we have, or the same amount.
// then it will not be helpful
continue;
}
size_t matches = 0;
for (size_t i = 0; i < otherFields.size(); ++i) {
if (otherFields[i] != idx->fields()[i]) {
break;
}
++matches;
}
if (matches == otherFields.size()) {
double estimate = other->selectivityEstimate();
if (estimate > 0.0) {
// reuse the estimate from the other index
estimatedItems = static_cast<double>(1.0 / estimate * values);
break;
}
}
}
}
// costs.estimatedItems is always set here, make it at least 1
costs.estimatedItems = std::max(size_t(1), static_cast<size_t>(estimatedItems));
// seek cost is O(log(n))
costs.estimatedCosts = std::max(double(1.0),
std::log2(double(itemsInIndex)) * values);
// add per-document processing cost
costs.estimatedCosts += estimatedItems * 0.05;
// slightly prefer indexes that cover more attributes
costs.estimatedCosts -= (attributesCovered - 1) * 0.02;
// cost is already low... now slightly prioritize unique indexes
if (idx->unique() || idx->implicitlyUnique()) {
costs.estimatedCosts *= 0.995 - 0.05 * (idx->fields().size() - 1);
}
// box the estimated costs to [0 - inf
costs.estimatedCosts = std::max(double(0.0), costs.estimatedCosts);
}
} else {
// index does not help for this condition
TRI_ASSERT(!costs.supportsCondition);
}
// honor the costs of post-index filter conditions
costs.estimatedCosts += costs.estimatedItems * postFilterConditions;
return costs;
}
Index::SortCosts SortedIndexAttributeMatcher::supportsSortCondition(
arangodb::Index const* idx, arangodb::aql::SortCondition const* sortCondition,
arangodb::aql::Variable const* reference, size_t itemsInIndex) {
TRI_ASSERT(sortCondition != nullptr);
Index::SortCosts costs = Index::SortCosts::defaultCosts(itemsInIndex, idx->isPersistent());
if (!idx->sparse() ||
sortCondition->onlyUsesNonNullSortAttributes(idx->fields())) {
// non-sparse indexes can be used for sorting, but sparse indexes can only be
// used if we can prove that we only need to return non-null index attribute values
if (!idx->hasExpansion() && sortCondition->isUnidirectional() &&
sortCondition->isOnlyAttributeAccess()) {
costs.coveredAttributes = sortCondition->coveredAttributes(reference, idx->fields());
if (costs.coveredAttributes >= sortCondition->numAttributes()) {
// sort is fully covered by index. no additional sort costs!
// forward iteration does not have high costs
costs.estimatedCosts = itemsInIndex * 0.001;
if (idx->isPersistent() && sortCondition->isDescending()) {
// reverse iteration has higher costs than forward iteration
costs.estimatedCosts *= 4;
}
costs.supportsCondition = true;
} else if (costs.coveredAttributes > 0) {
costs.estimatedCosts = (itemsInIndex / costs.coveredAttributes) *
std::log2(double(itemsInIndex));
if (idx->isPersistent() && sortCondition->isDescending()) {
// reverse iteration is more expensive
costs.estimatedCosts *= 4;
}
costs.supportsCondition = true;
}
}
}
return costs;
}
/// @brief specializes the condition for use with the index
arangodb::aql::AstNode* SortedIndexAttributeMatcher::specializeCondition(
arangodb::Index const* idx, arangodb::aql::AstNode* node,
arangodb::aql::Variable const* reference) {
// mmfiles failure compat
if (idx->type() == Index::TRI_IDX_TYPE_HASH_INDEX) {
TRI_IF_FAILURE("SimpleAttributeMatcher::specializeAllChildrenEQ") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
TRI_IF_FAILURE("SimpleAttributeMatcher::specializeAllChildrenIN") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
}
std::unordered_map<size_t, std::vector<arangodb::aql::AstNode const*>> found;
std::unordered_set<std::string> nonNullAttributes;
size_t values = 0; // ignored here
size_t postFilterConditions = 0; // ignored here
matchAttributes(idx, node, reference, found, postFilterConditions, values, nonNullAttributes, false);
std::vector<arangodb::aql::AstNode const*> children;
bool lastContainsEquality = true;
for (size_t i = 0; i < idx->fields().size(); ++i) {
auto it = found.find(i);
if (it == found.end() || !lastContainsEquality) {
// index attribute not covered by condition, or unsupported condition.
// must abort
break;
}
// check if the current condition contains an equality condition
auto& nodes = (*it).second;
lastContainsEquality =
(std::find_if(nodes.begin(), nodes.end(), [](arangodb::aql::AstNode const* node) {
return (node->type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ ||
node->type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN);
}) != nodes.end());
std::sort(nodes.begin(), nodes.end(),
[](arangodb::aql::AstNode const* lhs, arangodb::aql::AstNode const* rhs) -> bool {
return Index::sortWeight(lhs) < Index::sortWeight(rhs);
});
::arangodb::containers::HashSet<int> operatorsFound;
for (auto& it : nodes) {
if (it->type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE) {
// ignore all != operators here
continue;
}
// do not let duplicate or related operators pass
if (isDuplicateOperator(it, operatorsFound)) {
continue;
}
TRI_ASSERT(it->type != arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE);
operatorsFound.emplace(static_cast<int>(it->type));
children.emplace_back(it);
}
}
// must edit in place, no access to AST; TODO change so we can replace with
// copy
TEMPORARILY_UNLOCK_NODE(node);
node->clearMembers();
for (auto& it : children) {
TRI_ASSERT(it->type != arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE);
node->addMember(it);
}
return node;
}
bool SortedIndexAttributeMatcher::isDuplicateOperator(
arangodb::aql::AstNode const* node,
::arangodb::containers::HashSet<int> const& operatorsFound) {
auto type = node->type;
if (operatorsFound.find(static_cast<int>(type)) != operatorsFound.end()) {
// duplicate operator
return true;
}
if (operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ)) !=
operatorsFound.end() ||
operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN)) !=
operatorsFound.end()) {
return true;
}
bool duplicate = false;
switch (type) {
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LT:
duplicate = operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE)) !=
operatorsFound.end();
break;
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE:
duplicate = operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LT)) !=
operatorsFound.end();
break;
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT:
duplicate = operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE)) !=
operatorsFound.end();
break;
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE:
duplicate = operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT)) !=
operatorsFound.end();
break;
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ:
duplicate = operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN)) !=
operatorsFound.end();
break;
case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN:
duplicate = operatorsFound.find(static_cast<int>(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ)) !=
operatorsFound.end();
break;
default: {
// ignore
}
}
return duplicate;
}
| 39.640596 | 180 | 0.647672 | [
"vector"
] |
f68758f42e10ebfb8997d31138daa390ee2ddfec | 20,769 | cpp | C++ | src/armnnOnnxParser/test/Gemm.cpp | sahilbandar/armnn | 249950645b7bc0593582182097c7e2f1d6d97442 | [
"MIT"
] | 1 | 2022-02-10T11:06:30.000Z | 2022-02-10T11:06:30.000Z | src/armnnOnnxParser/test/Gemm.cpp | Elm8116/armnn | e571cde8411803aec545b1070ed677e481f46f3f | [
"MIT"
] | null | null | null | src/armnnOnnxParser/test/Gemm.cpp | Elm8116/armnn | e571cde8411803aec545b1070ed677e481f46f3f | [
"MIT"
] | null | null | null | //
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "armnnOnnxParser/IOnnxParser.hpp"
#include "ParserPrototxtFixture.hpp"
#include "OnnxParserTestUtils.hpp"
TEST_SUITE("OnnxParser_Gemm")
{
struct GemmFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
GemmFixture(const std::string& alpha,
const std::string& beta,
const std::string& transA,
const std::string& transB,
const std::vector<int>& inputAShape,
const std::vector<int>& inputBShape,
const std::vector<int>& inputCShape,
const std::vector<int>& outputShape)
{
m_Prototext = R"(
ir_version: 8
producer_name: "onnx-example"
graph {
node {
input: "A"
input: "B"
input: "C"
output: "Output"
op_type: "Gemm"
attribute {
name: "alpha"
f: )" + alpha + R"(
type: FLOAT
}
attribute {
name: "beta"
f: )" + beta + R"(
type: FLOAT
}
attribute {
name: "transA"
i: )" + transA + R"(
type: INT
}
attribute {
name: "transB"
i: )" + transB + R"(
type: INT
}
}
name: "gem-model"
input {
name: "A"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(inputAShape) + R"(
}
}
}
}
input {
name: "B"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(inputBShape) + R"(
}
}
}
}
input {
name: "C"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(inputCShape) + R"(
}
}
}
}
output {
name: "Output"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(outputShape) + R"(
}
}
}
}
})";
}
};
struct GemmAllAttributesFixture : GemmFixture
{
GemmAllAttributesFixture() : GemmFixture("0.25", "0.35", "1", "1", { 4, 3 }, { 5, 4 }, { 5 }, { 3, 5 })
{
Setup();
}
};
struct GemmSimpleFixture : GemmFixture
{
GemmSimpleFixture() : GemmFixture("1", "1", "0", "0", { 3, 4 }, { 4, 5 }, { 5 }, { 3, 5 })
{
Setup();
}
};
struct GemmTransAFixture : GemmFixture
{
GemmTransAFixture() : GemmFixture("1", "1", "1", "0", { 4, 3 }, { 4, 5 }, { 5 }, { 3, 5 })
{
Setup();
}
};
struct GemmTransBFixture : GemmFixture
{
GemmTransBFixture() : GemmFixture("1", "1", "0", "1", { 3, 4 }, { 5, 4 }, { 5 }, { 3, 5 })
{
Setup();
}
};
struct GemmParseExceptionFixture : GemmFixture
{
GemmParseExceptionFixture() : GemmFixture("1", "1", "0", "1", { 3, 4 }, { 5, 4 }, { 3, 5 }, { 3, 5 }) {}
};
TEST_CASE_FIXTURE(GemmAllAttributesFixture, "GemmTest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }},
{"B", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
11.0f, 12.0f, 13.0f, 14.0f, 15.0f,
16.0f, 17.0f, 18.0f, 19.0f, 20.0f }},
{"C", { 0.10f, 0.20f, 0.30f, 0.40f, 0.50f }}},
{{"Output", { 15.035f, 45.07f, 75.105f, 105.14f, 135.175f,
12.535f, 38.57f, 64.605f, 90.64f, 116.675f,
10.035f, 32.07f, 54.105f, 76.14f, 98.175f }}});
}
TEST_CASE_FIXTURE(GemmSimpleFixture, "GemmSimpleTest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }},
{"B", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
11.0f, 12.0f, 13.0f, 14.0f, 15.0f,
16.0f, 17.0f, 18.0f, 19.0f, 20.0f }},
{"C", { 0.10f, 0.20f, 0.30f, 0.40f, 0.50f }}},
{{"Output", { 332.1f, 374.2f, 416.3f, 458.4f, 500.5f,
196.1f, 222.2f, 248.3f, 274.4f, 300.5f,
60.1f, 70.2f, 80.3f, 90.4f, 100.5f }}});
}
TEST_CASE_FIXTURE(GemmTransAFixture, "GemmTransposeATest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }},
{"B", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
11.0f, 12.0f, 13.0f, 14.0f, 15.0f,
16.0f, 17.0f, 18.0f, 19.0f, 20.0f }},
{"C", { 0.10f, 0.20f, 0.30f, 0.40f, 0.50f }}},
{{"Output", { 180.1f, 210.2f, 240.3f, 270.4f, 300.5f,
146.1f, 172.2f, 198.3f, 224.4f, 250.5f,
112.1f, 134.2f, 156.3f, 178.4f, 200.5f }}});
}
TEST_CASE_FIXTURE(GemmTransBFixture, "GemmTransposeBTest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }},
{"B", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
11.0f, 12.0f, 13.0f, 14.0f, 15.0f,
16.0f, 17.0f, 18.0f, 19.0f, 20.0f }},
{"C", { 0.10f, 0.20f, 0.30f, 0.40f, 0.50f }}},
{{"Output", { 100.1f, 268.2f, 436.3f, 604.4f, 772.5f,
60.1f, 164.2f, 268.3f, 372.4f, 476.5f,
20.1f, 60.2f, 100.3f, 140.4f, 180.5f }}});
}
TEST_CASE_FIXTURE(GemmParseExceptionFixture, "GemmParseExceptionTest")
{
// ParseException because Input C is non-constant and has 2 dimension (should be 1 dimension)
CHECK_THROWS_AS(Setup(), armnn::ParseException);
}
struct GemmConstantFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
GemmConstantFixture()
{
m_Prototext = R"(
ir_version: 8
producer_name: "onnx-example"
graph {
node {
input: "A"
input: "B"
input: "C"
output: "Output"
op_type: "Gemm"
attribute {
name: "alpha"
f: 0.25
type: FLOAT
}
attribute {
name: "beta"
f: 0.35
type: FLOAT
}
attribute {
name: "transA"
i: 1
type: INT
}
attribute {
name: "transB"
i: 1
type: INT
}
}
name: "gem-model"
initializer {
dims: 5
dims: 4
data_type: 1
float_data: 1.0
float_data: 2.0
float_data: 3.0
float_data: 4.0
float_data: 5.0
float_data: 6.0
float_data: 7.0
float_data: 8.0
float_data: 9.0
float_data: 10.0
float_data: 11.0
float_data: 12.0
float_data: 13.0
float_data: 14.0
float_data: 15.0
float_data: 16.0
float_data: 17.0
float_data: 18.0
float_data: 19.0
float_data: 20.0
name: "B"
}
initializer {
dims: 1
dims: 5
data_type: 1
float_data: 0.1
float_data: 0.2
float_data: 0.3
float_data: 0.4
float_data: 0.5
name: "C"
}
input {
name: "A"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 4
}
dim {
dim_value: 3
}
}
}
}
}
output {
name: "Output"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 3
}
dim {
dim_value: 5
}
}
}
}
}
})";
Setup();
}
};
TEST_CASE_FIXTURE(GemmConstantFixture, "GemmConstantTest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }}},
{{"Output", { 15.035f, 45.07f, 75.105f, 105.14f, 135.175f,
12.535f, 38.57f, 64.605f, 90.64f, 116.675f,
10.035f, 32.07f, 54.105f, 76.14f, 98.175f }}});
}
struct GemmConstantSimpleFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
GemmConstantSimpleFixture()
{
m_Prototext = R"(
ir_version: 8
producer_name: "onnx-example"
graph {
node {
input: "A"
input: "B"
input: "C"
output: "Output"
op_type: "Gemm"
attribute {
name: "alpha"
f: 1
type: FLOAT
}
attribute {
name: "beta"
f: 1
type: FLOAT
}
attribute {
name: "transA"
i: 0
type: INT
}
attribute {
name: "transB"
i: 0
type: INT
}
}
name: "gem-model"
initializer {
dims: 4
dims: 5
data_type: 1
float_data: 1.0
float_data: 2.0
float_data: 3.0
float_data: 4.0
float_data: 5.0
float_data: 6.0
float_data: 7.0
float_data: 8.0
float_data: 9.0
float_data: 10.0
float_data: 11.0
float_data: 12.0
float_data: 13.0
float_data: 14.0
float_data: 15.0
float_data: 16.0
float_data: 17.0
float_data: 18.0
float_data: 19.0
float_data: 20.0
name: "B"
}
initializer {
dims: 1
dims: 5
data_type: 1
float_data: 0.1
float_data: 0.2
float_data: 0.3
float_data: 0.4
float_data: 0.5
name: "C"
}
input {
name: "A"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 3
}
dim {
dim_value: 4
}
}
}
}
}
output {
name: "Output"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 3
}
dim {
dim_value: 5
}
}
}
}
}
})";
Setup();
}
};
TEST_CASE_FIXTURE(GemmConstantSimpleFixture, "GemmConstantSimpleTest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }}},
{{"Output", { 332.1f, 374.2f, 416.3f, 458.4f, 500.5f,
196.1f, 222.2f, 248.3f, 274.4f, 300.5f,
60.1f, 70.2f, 80.3f, 90.4f, 100.5f }}});
}
struct GemmABFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
GemmABFixture(const std::string& alpha,
const std::string& beta,
const std::string& transA,
const std::string& transB,
const std::vector<int>& inputAShape,
const std::vector<int>& inputBShape,
const std::vector<int>& outputShape)
{
m_Prototext = R"(
ir_version: 8
producer_name: "onnx-example"
graph {
node {
input: "A"
input: "B"
output: "Output"
op_type: "Gemm"
attribute {
name: "alpha"
f: )" + alpha + R"(
type: FLOAT
}
attribute {
name: "beta"
f: )" + beta + R"(
type: FLOAT
}
attribute {
name: "transA"
i: )" + transA + R"(
type: INT
}
attribute {
name: "transB"
i: )" + transB + R"(
type: INT
}
}
name: "gem-model"
input {
name: "A"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(inputAShape) + R"(
}
}
}
}
input {
name: "B"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(inputBShape) + R"(
}
}
}
}
output {
name: "Output"
type {
tensor_type {
elem_type: 1
shape {
)" + armnnUtils::ConstructTensorShapeString(outputShape) + R"(
}
}
}
}
})";
Setup();
}
};
struct GemmAlphaTransAFixture : GemmABFixture
{
GemmAlphaTransAFixture() : GemmABFixture("0.25", "0.35", "1", "0", { 4, 3 }, { 4, 5 }, { 3, 5 }) {}
};
struct GemmAlphaTransBFixture : GemmABFixture
{
GemmAlphaTransBFixture() : GemmABFixture("0.25", "0.35", "0", "1", { 3, 4 }, { 5, 4 }, { 3, 5 }) {}
};
TEST_CASE_FIXTURE(GemmAlphaTransAFixture, "GemmAlphaTransATest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }},
{"B", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
11.0f, 12.0f, 13.0f, 14.0f, 15.0f,
16.0f, 17.0f, 18.0f, 19.0f, 20.0f }}},
{{"Output", { 45.0f, 52.5f, 60.0f, 67.5f, 75.0f,
36.5f, 43.0f, 49.5f, 56.0f, 62.5f,
28.0f, 33.5f, 39.0f, 44.5f, 50.0f }}});
}
TEST_CASE_FIXTURE(GemmAlphaTransBFixture, "GemmAlphaTransBTest")
{
RunTest<2, float>({{"A", { 12.0f, 11.0f, 10.0f, 9.0f, 8.0f, 7.0f,
6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }},
{"B", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
11.0f, 12.0f, 13.0f, 14.0f, 15.0f,
16.0f, 17.0f, 18.0f, 19.0f, 20.0f }}},
{{"Output", { 25.0f, 67.0f, 109.0f, 151.0f, 193.0f,
15.0f, 41.0f, 67.0f, 93.0f, 119.0f,
5.0f, 15.0f, 25.0f, 35.0f, 45.0f }}});
}
}
| 37.287253 | 108 | 0.305985 | [
"shape",
"vector",
"model"
] |
f6875fe8ff33615eda803d302c9399e3bc7b22b3 | 67,822 | cc | C++ | zircon/system/utest/core/threads/threads.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | zircon/system/utest/core/threads/threads.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/core/threads/threads.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 2 | 2020-10-25T01:13:49.000Z | 2020-10-26T02:32:13.000Z | // Copyright 2016 The Fuchsia Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/test-exceptions/exception-catcher.h>
#include <lib/test-exceptions/exception-handling.h>
#include <lib/zx/clock.h>
#include <lib/zx/event.h>
#include <lib/zx/handle.h>
#include <lib/zx/process.h>
#include <lib/zx/thread.h>
#include <lib/zx/vmo.h>
#include <stddef.h>
#include <unistd.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/debug.h>
#include <zircon/syscalls/exception.h>
#include <zircon/syscalls/object.h>
#include <zircon/syscalls/port.h>
#include <zircon/types.h>
#include <atomic>
#include <mini-process/mini-process.h>
#include <runtime/thread.h>
#include <zxtest/zxtest.h>
#include "register-set.h"
#include "thread-functions/thread-functions.h"
static const char kThreadName[] = "test-thread";
// We have to poll a thread's state as there is no way to wait for it to
// transition states. Wait this amount of time. Generally the thread won't
// take very long so this is a compromise between polling too frequently and
// waiting too long.
constexpr zx_duration_t THREAD_BLOCKED_WAIT_DURATION = ZX_MSEC(1);
static void get_koid(zx_handle_t handle, zx_koid_t* koid) {
zx_info_handle_basic_t info;
size_t records_read;
ASSERT_EQ(
zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), &records_read, NULL),
ZX_OK);
ASSERT_EQ(records_read, 1u);
*koid = info.koid;
}
static bool get_thread_info(zx_handle_t thread, zx_info_thread_t* info) {
return zx_object_get_info(thread, ZX_INFO_THREAD, info, sizeof(*info), NULL, NULL) == ZX_OK;
}
// Suspend the given thread and block until it reaches the suspended state. The suspend token
// is written to the output parameter.
static void suspend_thread_synchronous(zx_handle_t thread, zx_handle_t* suspend_token) {
ASSERT_EQ(zx_task_suspend_token(thread, suspend_token), ZX_OK);
zx_signals_t observed = 0u;
ASSERT_EQ(zx_object_wait_one(thread, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, &observed), ZX_OK);
}
// Resume the given thread and block until it reaches the running state.
static void resume_thread_synchronous(zx_handle_t thread, zx_handle_t suspend_token) {
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
zx_signals_t observed = 0u;
ASSERT_EQ(zx_object_wait_one(thread, ZX_THREAD_RUNNING, ZX_TIME_INFINITE, &observed), ZX_OK);
}
// Updates the thread state to advance over a software breakpoint instruction, assuming the
// breakpoint was just hit. This does not resume the thread, only updates its state.
static void advance_over_breakpoint(zx_handle_t thread) {
#if defined(__aarch64__)
// Advance 4 bytes to the next instruction after the debug break.
zx_thread_state_general_regs regs;
ASSERT_EQ(zx_thread_read_state(thread, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)), ZX_OK);
regs.pc += 4;
ASSERT_EQ(zx_thread_write_state(thread, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
#elif defined(__x86_64__)
// x86 sets the instruction pointer to the following instruction so needs no update.
#else
#error Not supported on this platform.
#endif
}
// Waits for the exception type excp_type, ignoring exceptions of type ignore_type (these will
// just resume the thread), and issues errors for anything else.
//
// Fills |exception_out| with the resulting exception object.
static void wait_thread_excp_type(zx_handle_t thread, zx_handle_t exception_channel,
uint32_t excp_type, uint32_t ignore_type,
zx_handle_t* exception_out) {
while (true) {
ASSERT_EQ(zx_object_wait_one(exception_channel, ZX_CHANNEL_READABLE, ZX_TIME_INFINITE, nullptr),
ZX_OK);
zx_exception_info_t info;
zx_handle_t exception;
ASSERT_EQ(
zx_channel_read(exception_channel, 0, &info, &exception, sizeof(info), 1, nullptr, nullptr),
ZX_OK);
// Use EXPECTs rather than ASSERTs here so that if something fails
// we log all the relevant information about the packet contents.
zx_koid_t koid = ZX_KOID_INVALID;
get_koid(thread, &koid);
EXPECT_EQ(info.tid, koid);
if (info.type != ignore_type) {
EXPECT_EQ(info.type, excp_type);
*exception_out = exception;
break;
} else {
uint32_t state = ZX_EXCEPTION_STATE_HANDLED;
ASSERT_EQ(zx_object_set_property(exception, ZX_PROP_EXCEPTION_STATE, &state, sizeof(state)),
ZX_OK);
zx_handle_close(exception);
}
}
}
namespace {
// Class to encapsulate the various handles and calculations required to start a thread.
//
// This is only necessary to use directly if you need to do something between creating
// and starting the thread - otherwise just use start_thread() for simplicity.
//
// See comment on start_thread (below) about constraints on the entry point.
class ThreadStarter {
public:
void CreateThread(zxr_thread_t* thread_out, zx_handle_t* thread_h, bool start_suspended = false) {
// TODO: Don't leak these when the thread dies.
// If the thread should start suspended, give it a 0-size VMO for a stack so
// that it will crash if it gets to userspace.
ASSERT_EQ(zx::vmo::create(start_suspended ? 0 : kStackSize, ZX_VMO_RESIZABLE, &stack_handle_),
ZX_OK);
ASSERT_NE(stack_handle_.get(), ZX_HANDLE_INVALID);
ASSERT_EQ(zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0,
stack_handle_.get(), 0, kStackSize, &stack_),
ZX_OK);
ASSERT_EQ(zxr_thread_create(zx_process_self(), "test_thread", false, thread_out), ZX_OK);
thread_ = thread_out;
if (thread_h) {
ASSERT_EQ(
zx_handle_duplicate(zxr_thread_get_handle(thread_out), ZX_RIGHT_SAME_RIGHTS, thread_h),
ZX_OK);
}
}
void GrowStackVmo() { ASSERT_EQ(stack_handle_.set_size(kStackSize), ZX_OK); }
bool StartThread(zxr_thread_entry_t entry, void* arg) {
return zxr_thread_start(thread_, stack_, kStackSize, entry, arg) == ZX_OK;
}
// Destroy a thread structure that is either created but unstarted or is
// known to belong to a thread that has been zx_task_kill'd and has not been
// joined.
bool DestroyThread() { return zxr_thread_destroy(thread_) == ZX_OK; }
private:
static constexpr size_t kStackSize = 256u << 10;
zx::vmo stack_handle_;
uintptr_t stack_ = 0u;
zxr_thread_t* thread_ = nullptr;
};
} // namespace
// NOTE! The entry point code here must be built specially so it doesn't
// require full proper ABI setup, which ThreadStarter does not do. The
// thread-functions.cc functions are fine, since that file is explicitly built
// without instrumentation or fancy ABI features. Anything else must be
// annotated with __NO_SAFESTACK and not call any other function not so
// annotated, which basically means nothing but the raw vDSO entry points.
static bool start_thread(zxr_thread_entry_t entry, void* arg, zxr_thread_t* thread_out,
zx_handle_t* thread_h) {
ThreadStarter starter;
starter.CreateThread(thread_out, thread_h);
return starter.StartThread(entry, arg);
}
// Wait for |thread| to enter blocked state |reason|.
// We wait forever and let Unittest's watchdog handle errors.
static void wait_thread_blocked(zx_handle_t thread, zx_thread_state_t reason) {
while (true) {
zx_info_thread_t info;
ASSERT_TRUE(get_thread_info(thread, &info));
if (info.state == reason)
break;
zx_nanosleep(zx_deadline_after(THREAD_BLOCKED_WAIT_DURATION));
}
}
static bool CpuMaskBitSet(const zx_cpu_set_t& set, uint32_t i) {
if (i >= ZX_CPU_SET_MAX_CPUS) {
return false;
}
uint32_t word = i / ZX_CPU_SET_BITS_PER_WORD;
uint32_t bit = i % ZX_CPU_SET_BITS_PER_WORD;
return ((set.mask[word] >> bit) & 1u) != 0;
}
TEST(Threads, Basics) {
zxr_thread_t thread;
zx_handle_t thread_h;
ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)zx_deadline_after(ZX_MSEC(100)), &thread,
&thread_h));
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, InvalidRights) {
zxr_thread_t thread;
zx_handle_t ro_process_h;
ASSERT_EQ(zx_handle_duplicate(zx_process_self(), ZX_RIGHT_DESTROY, &ro_process_h), ZX_OK);
ASSERT_EQ(zxr_thread_create(ro_process_h, "test_thread", false, &thread), ZX_ERR_ACCESS_DENIED);
ASSERT_EQ(zx_handle_close(ro_process_h), ZX_OK);
}
TEST(Threads, Detach) {
zxr_thread_t thread;
zx_handle_t event;
ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
zx_handle_t thread_h;
ASSERT_TRUE(start_thread(threads_test_wait_detach_fn, &event, &thread, &thread_h));
// We're not detached yet
ASSERT_FALSE(zxr_thread_detached(&thread));
ASSERT_EQ(zxr_thread_detach(&thread), ZX_OK);
ASSERT_TRUE(zxr_thread_detached(&thread));
// Tell thread to exit
ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
// Wait for thread to exit
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, EmptyNameSucceeds) {
zx_handle_t thread;
ASSERT_EQ(zx_thread_create(zx_process_self(), "", 0, 0, &thread), ZX_OK);
static char thread_name[ZX_MAX_NAME_LEN];
ASSERT_EQ(zx_object_get_property(thread, ZX_PROP_NAME, thread_name, ZX_MAX_NAME_LEN), ZX_OK);
ASSERT_EQ(strcmp(thread_name, ""), 0);
ASSERT_EQ(zx_handle_close(thread), ZX_OK);
}
TEST(Threads, LongNameSucceeds) {
// Creating a thread with a super long name should succeed.
static const char long_name[] =
"0123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789";
ASSERT_GT(strlen(long_name), (size_t)ZX_MAX_NAME_LEN - 1, "too short to truncate");
zxr_thread_t thread;
ASSERT_EQ(zxr_thread_create(zx_process_self(), long_name, false, &thread), ZX_OK);
static char thread_name[ZX_MAX_NAME_LEN];
ASSERT_EQ(zx_object_get_property(zxr_thread_get_handle(&thread), ZX_PROP_NAME, thread_name,
ZX_MAX_NAME_LEN),
ZX_OK);
ASSERT_EQ(strncmp(thread_name, long_name, ZX_MAX_NAME_LEN - 1), 0);
zxr_thread_destroy(&thread);
}
// zx_thread_start() is not supposed to be usable for creating a
// process's first thread. That's what zx_process_start() is for.
// Check that zx_thread_start() returns an error in this case.
TEST(Threads, ThreadStartOnInitialThread) {
static const char kProcessName[] = "test-proc-thread1";
zx_handle_t process;
zx_handle_t vmar;
zx_handle_t thread;
ASSERT_OK(zx_process_create(zx_job_default(), kProcessName, sizeof(kProcessName) - 1, 0, &process,
&vmar));
ASSERT_OK(zx_thread_create(process, kThreadName, sizeof(kThreadName) - 1, 0, &thread));
ASSERT_EQ(ZX_ERR_BAD_STATE, zx_thread_start(thread, 0, 1, 1, 1));
ASSERT_OK(zx_handle_close(thread));
ASSERT_OK(zx_handle_close(vmar));
ASSERT_OK(zx_handle_close(process));
}
// Test that we don't get an assertion failure (and kernel panic) if we
// pass a zero instruction pointer when starting a thread (in this case via
// zx_thread_create()).
TEST(Threads, ThreadStartWithZeroInstructionPointer) {
zx_handle_t thread;
ASSERT_EQ(zx_thread_create(zx_process_self(), kThreadName, sizeof(kThreadName) - 1, 0, &thread),
ZX_OK);
test_exceptions::ExceptionCatcher catcher(*zx::unowned_process(zx_process_self()));
ASSERT_EQ(zx_thread_start(thread, 0, 0, 0, 0), ZX_OK);
auto result = catcher.ExpectException();
ASSERT_TRUE(result.is_ok());
ASSERT_OK(test_exceptions::ExitExceptionZxThread(std::move(result.value())));
ASSERT_EQ(zx_handle_close(thread), ZX_OK);
}
TEST(Threads, NonstartedThread) {
// Perform apis against non started threads (in the INITIAL STATE).
zx_handle_t thread;
ASSERT_EQ(zx_thread_create(zx_process_self(), "thread", 5, 0, &thread), ZX_OK);
ASSERT_EQ(zx_handle_close(thread), ZX_OK);
}
TEST(Threads, InfoTaskStatsFails) {
// Spin up a thread.
zxr_thread_t thread;
zx_handle_t thandle;
ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)zx_deadline_after(ZX_MSEC(100)), &thread,
&thandle));
ASSERT_EQ(zx_object_wait_one(thandle, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
// Ensure that task_stats doesn't work on it.
zx_info_task_stats_t info;
EXPECT_NE(zx_object_get_info(thandle, ZX_INFO_TASK_STATS, &info, sizeof(info), NULL, NULL), ZX_OK,
"Just added thread support to info_task_status?");
// If so, replace this with a real test; see example in process.cpp.
ASSERT_EQ(zx_handle_close(thandle), ZX_OK);
}
TEST(Threads, InfoThreadStatsFails) {
// Spin up a thread.
zxr_thread_t thread;
zx_handle_t thandle;
ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)zx_deadline_after(ZX_MSEC(100)), &thread,
&thandle));
ASSERT_EQ(zx_object_wait_one(thandle, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
// Ensure that thread_stats doesn't work on it.
zx_info_task_stats_t info;
EXPECT_EQ(zx_object_get_info(thandle, ZX_INFO_THREAD_STATS, &info, sizeof(info), NULL, NULL),
ZX_ERR_BAD_STATE, "THREAD_STATS shouldn't work after a thread exits");
ASSERT_EQ(zx_handle_close(thandle), ZX_OK);
}
TEST(Threads, GetLastScheduledCpu) {
zx_handle_t event;
ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
// Create a thread.
zxr_thread_t thread;
zx_handle_t thread_h;
ThreadStarter starter;
starter.CreateThread(&thread, &thread_h);
// Ensure "last_cpu" is ZX_INFO_INVALID_CPU prior to the thread starting.
zx_info_thread_stats_t info;
ASSERT_EQ(
zx_object_get_info(thread_h, ZX_INFO_THREAD_STATS, &info, sizeof(info), nullptr, nullptr),
ZX_OK);
ASSERT_EQ(info.last_scheduled_cpu, ZX_INFO_INVALID_CPU);
// Start the thread.
ASSERT_TRUE(starter.StartThread(threads_test_run_fn, &event));
// Wait for worker to start.
ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, /*pending=*/nullptr),
ZX_OK);
// Ensure the last-reported thread looks reasonable.
ASSERT_EQ(
zx_object_get_info(thread_h, ZX_INFO_THREAD_STATS, &info, sizeof(info), nullptr, nullptr),
ZX_OK);
ASSERT_NE(info.last_scheduled_cpu, ZX_INFO_INVALID_CPU);
ASSERT_LT(info.last_scheduled_cpu, ZX_CPU_SET_MAX_CPUS);
// Shut down and clean up.
ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_1), ZX_OK);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, nullptr), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, GetInfoRuntime) {
zx::event event;
ASSERT_EQ(zx::event::create(0, &event), ZX_OK);
// Create a thread.
zxr_thread_t thread;
zx::thread thread_h;
ThreadStarter starter;
starter.CreateThread(&thread, thread_h.reset_and_get_address());
// Ensure runtime is 0 prior to thread starting.
zx_info_task_runtime_t info;
ASSERT_EQ(thread_h.get_info(ZX_INFO_TASK_RUNTIME, &info, sizeof(info), nullptr, nullptr), ZX_OK);
ASSERT_EQ(info.cpu_time, 0);
ASSERT_EQ(info.queue_time, 0);
// Start the thread.
ASSERT_TRUE(starter.StartThread(threads_test_run_fn, &event));
// Wait for worker to start.
ASSERT_EQ(event.wait_one(ZX_USER_SIGNAL_0, zx::time::infinite(), /*pending=*/nullptr), ZX_OK);
// Ensure the last-reported thread looks reasonable.
ASSERT_EQ(thread_h.get_info(ZX_INFO_TASK_RUNTIME, &info, sizeof(info), nullptr, nullptr), ZX_OK);
ASSERT_GT(info.cpu_time, 0);
ASSERT_GT(info.queue_time, 0);
// Shut down and clean up.
ASSERT_EQ(event.signal(0, ZX_USER_SIGNAL_1), ZX_OK);
ASSERT_EQ(thread_h.wait_one(ZX_THREAD_TERMINATED, zx::time::infinite(), nullptr), ZX_OK);
// Ensure the runtime can still be read after the task exits.
ASSERT_EQ(thread_h.get_info(ZX_INFO_TASK_RUNTIME, &info, sizeof(info), nullptr, nullptr), ZX_OK);
ASSERT_GT(info.cpu_time, 0);
ASSERT_GT(info.queue_time, 0);
// Test that removing ZX_RIGHT_INSPECT causes runtime calls to fail.
zx_info_handle_basic_t basic;
ASSERT_OK(thread_h.get_info(ZX_INFO_HANDLE_BASIC, &basic, sizeof(basic), nullptr, nullptr));
zx::thread thread_dup;
ASSERT_OK(thread_h.duplicate(basic.rights & ~ZX_RIGHT_INSPECT, &thread_dup));
ASSERT_EQ(thread_dup.get_info(ZX_INFO_TASK_RUNTIME, &info, sizeof(info), nullptr, nullptr),
ZX_ERR_ACCESS_DENIED);
}
TEST(Threads, GetAffinity) {
// Create a thread.
zxr_thread_t thread;
zx_handle_t thread_h;
ThreadStarter starter;
starter.CreateThread(&thread, &thread_h);
// Fetch affinity mask.
zx_info_thread_t info;
ASSERT_EQ(zx_object_get_info(thread_h, ZX_INFO_THREAD, &info, sizeof(info), nullptr, nullptr),
ZX_OK);
// We expect that a new thread should be runnable on at least 1 CPU.
int num_cpus = 0;
for (int i = 0; i < ZX_CPU_SET_MAX_CPUS; i++) {
if (CpuMaskBitSet(info.cpu_affinity_mask, i)) {
num_cpus++;
}
}
ASSERT_GT(num_cpus, 0);
// In the current system, we expect that a new thread will be runnable
// on a contiguous range of CPUs, from 0 to (N - 1).
for (int i = 0; i < ZX_CPU_SET_MAX_CPUS; i++) {
EXPECT_EQ(CpuMaskBitSet(info.cpu_affinity_mask, i), i < num_cpus);
}
// Shut down and clean up.
starter.DestroyThread();
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, ResumeSuspended) {
zx_handle_t event;
zxr_thread_t thread;
zx_handle_t thread_h;
ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
ASSERT_TRUE(start_thread(threads_test_wait_fn, &event, &thread, &thread_h));
// threads_test_wait_fn() uses zx_object_wait_one() so we watch for that.
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
// The thread should still be blocked on the event when it wakes up.
// It needs to run for a bit to transition from suspended back to blocked
// so we need to wait for it.
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
// Check that signaling the event while suspended results in the expected behavior.
suspend_token = ZX_HANDLE_INVALID;
suspend_thread_synchronous(thread_h, &suspend_token);
// Verify thread is suspended.
zx_info_thread_t info;
ASSERT_TRUE(get_thread_info(thread_h, &info));
ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
ASSERT_EQ(info.wait_exception_channel_type, ZX_EXCEPTION_CHANNEL_TYPE_NONE);
// Resuming the thread should mark the thread as blocked again.
resume_thread_synchronous(thread_h, suspend_token);
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
// When the thread is suspended the signaling should not take effect.
suspend_token = ZX_HANDLE_INVALID;
suspend_thread_synchronous(thread_h, &suspend_token);
ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, zx_deadline_after(ZX_MSEC(100)), NULL),
ZX_ERR_TIMED_OUT);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(event), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, SuspendSleeping) {
const zx_time_t sleep_deadline = zx_deadline_after(ZX_MSEC(100));
zxr_thread_t thread;
zx_handle_t thread_h;
ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)sleep_deadline, &thread, &thread_h));
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_SLEEPING);
// Suspend the thread.
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
zx_status_t status = zx_task_suspend_token(thread_h, &suspend_token);
if (status != ZX_OK) {
ASSERT_EQ(status, ZX_ERR_BAD_STATE);
// This might happen if the thread exits before we tried suspending it
// (due to e.g. a long context-switch away). The system is too loaded
// and so we might not have a chance at success here without a massive
// sleep duration.
zx_info_thread_t info;
ASSERT_EQ(zx_object_get_info(thread_h, ZX_INFO_THREAD, &info, sizeof(info), NULL, NULL), ZX_OK);
ASSERT_EQ(info.state, ZX_THREAD_STATE_DEAD);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
// Early bail from the test, since we hit a possible race from an
// overloaded machine.
return;
}
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
// Wait for the sleep to finish
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
const zx_time_t now = zx_clock_get_monotonic();
ASSERT_GE(now, sleep_deadline, "thread did not sleep long enough");
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, SuspendChannelCall) {
zxr_thread_t thread;
zx_handle_t channel;
channel_call_suspend_test_arg thread_arg;
ASSERT_EQ(zx_channel_create(0, &thread_arg.channel, &channel), ZX_OK);
thread_arg.call_status = ZX_ERR_BAD_STATE;
zx_handle_t thread_h;
ASSERT_TRUE(start_thread(threads_test_channel_call_fn, &thread_arg, &thread, &thread_h));
// Wait for the thread to send a channel call before suspending it
ASSERT_EQ(zx_object_wait_one(channel, ZX_CHANNEL_READABLE, ZX_TIME_INFINITE, NULL), ZX_OK);
// Suspend the thread.
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
suspend_thread_synchronous(thread_h, &suspend_token);
// Read the message
uint8_t buf[9];
uint32_t actual_bytes;
ASSERT_EQ(zx_channel_read(channel, 0, buf, NULL, sizeof(buf), 0, &actual_bytes, NULL), ZX_OK);
ASSERT_EQ(actual_bytes, sizeof(buf));
ASSERT_EQ(memcmp(buf + sizeof(zx_txid_t), &"abcdefghi"[sizeof(zx_txid_t)],
sizeof(buf) - sizeof(zx_txid_t)),
0);
// Write a reply
buf[8] = 'j';
ASSERT_EQ(zx_channel_write(channel, 0, buf, sizeof(buf), NULL, 0), ZX_OK);
// Make sure the remote channel didn't get signaled
EXPECT_EQ(zx_object_wait_one(thread_arg.channel, ZX_CHANNEL_READABLE, 0, NULL), ZX_ERR_TIMED_OUT);
// Make sure we can't read from the remote channel (the message should have
// been reserved for the other thread, even though it is suspended).
EXPECT_EQ(zx_channel_read(thread_arg.channel, 0, buf, NULL, sizeof(buf), 0, &actual_bytes, NULL),
ZX_ERR_SHOULD_WAIT);
// Wake the suspended thread
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
// Wait for the thread to finish
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
EXPECT_EQ(thread_arg.call_status, ZX_OK);
ASSERT_EQ(zx_handle_close(channel), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, SuspendPortCall) {
zxr_thread_t thread;
zx_handle_t port[2];
ASSERT_EQ(zx_port_create(0, &port[0]), ZX_OK);
ASSERT_EQ(zx_port_create(0, &port[1]), ZX_OK);
zx_handle_t thread_h;
ASSERT_TRUE(start_thread(threads_test_port_fn, port, &thread, &thread_h));
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_PORT);
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
zx_port_packet_t packet1 = {100ull, ZX_PKT_TYPE_USER, 0u, {}};
zx_port_packet_t packet2 = {300ull, ZX_PKT_TYPE_USER, 0u, {}};
ASSERT_EQ(zx_port_queue(port[0], &packet1), ZX_OK);
ASSERT_EQ(zx_port_queue(port[0], &packet2), ZX_OK);
zx_port_packet_t packet;
ASSERT_EQ(zx_port_wait(port[1], zx_deadline_after(ZX_MSEC(100)), &packet), ZX_ERR_TIMED_OUT);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
ASSERT_EQ(zx_port_wait(port[1], ZX_TIME_INFINITE, &packet), ZX_OK);
EXPECT_EQ(packet.key, 105ull);
ASSERT_EQ(zx_port_wait(port[0], ZX_TIME_INFINITE, &packet), ZX_OK);
EXPECT_EQ(packet.key, 300ull);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
ASSERT_EQ(zx_handle_close(port[0]), ZX_OK);
ASSERT_EQ(zx_handle_close(port[1]), ZX_OK);
}
TEST(Threads, SuspendStopsThread) {
zxr_thread_t thread;
volatile int value = kTestAtomicClobberValue;
zx_handle_t thread_h;
ASSERT_TRUE(
start_thread(threads_test_atomic_store, const_cast<int*>(&value), &thread, &thread_h));
while (atomic_load(&value) != kTestAtomicSetValue) {
zx_nanosleep(0);
}
// Suspend the thread and wait for the suspend to happen.
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, nullptr), ZX_OK);
// Clobber the value, wait, and "check" that the thread didn't reset the value.
// This isn't fool proof, but it's hard to check that something "doesn't" happen.
atomic_store(&value, kTestAtomicClobberValue);
zx_nanosleep(zx_deadline_after(ZX_MSEC(50)));
ASSERT_EQ(atomic_load(&value), kTestAtomicClobberValue);
// Let the thread resume and then wait for it to reset the value.
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
while (atomic_load(&value) != kTestAtomicSetValue) {
zx_nanosleep(0);
}
// Clean up.
atomic_store(&value, kTestAtomicExitValue);
// Wait for the thread termination to complete. We should do this so
// that any later tests which handle process debug exceptions do not
// receive an ZX_EXCP_THREAD_EXITING event.
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, SuspendMultiple) {
zx_handle_t event;
zxr_thread_t thread;
zx_handle_t thread_h;
ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
ASSERT_TRUE(start_thread(threads_test_wait_break_fn, &event, &thread, &thread_h));
// The thread will now be blocked on the event. Wake it up and catch the trap (undefined
// exception).
zx_handle_t exception_channel, exception;
ASSERT_EQ(zx_task_create_exception_channel(zx_process_self(), ZX_EXCEPTION_CHANNEL_DEBUGGER,
&exception_channel),
ZX_OK);
ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
wait_thread_excp_type(thread_h, exception_channel, ZX_EXCP_SW_BREAKPOINT, ZX_EXCP_THREAD_STARTING,
&exception);
// The thread should now be blocked on a debugger exception.
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_EXCEPTION);
zx_info_thread_t info;
ASSERT_TRUE(get_thread_info(thread_h, &info));
ASSERT_EQ(info.wait_exception_channel_type, ZX_EXCEPTION_CHANNEL_TYPE_DEBUGGER);
advance_over_breakpoint(thread_h);
// Suspend twice (on top of the existing exception). Don't use the synchronous suspend since
// suspends don't escape out of exception handling, unlike blocking
// syscalls where suspend will escape out of them.
zx_handle_t suspend_token1 = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token1), ZX_OK);
zx_handle_t suspend_token2 = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token2), ZX_OK);
// Resume one token, it should remain blocked.
ASSERT_EQ(zx_handle_close(suspend_token1), ZX_OK);
ASSERT_TRUE(get_thread_info(thread_h, &info));
// Note: If this check is flaky, it's failing. It should not transition out of the blocked
// state, but if it does so, it will do so asynchronously which might cause
// nondeterministic failures.
ASSERT_EQ(info.state, ZX_THREAD_STATE_BLOCKED_EXCEPTION);
// Resume the exception. It should be SUSPENDED now that the exception is complete (one could
// argue that it could still be BLOCKED also, but it's not in the current implementation).
// The transition to SUSPENDED happens asynchronously unlike some of the exception states.
uint32_t state = ZX_EXCEPTION_STATE_HANDLED;
ASSERT_EQ(zx_object_set_property(exception, ZX_PROP_EXCEPTION_STATE, &state, sizeof(state)),
ZX_OK);
ASSERT_EQ(zx_handle_close(exception), ZX_OK);
zx_signals_t observed = 0u;
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, &observed), ZX_OK);
ASSERT_TRUE(get_thread_info(thread_h, &info));
ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
// 2nd resume, should be running and then exit.
ASSERT_EQ(zx_handle_close(suspend_token2), ZX_OK);
//
// We have to close the exception channel because it will keep the thread in DYING state.
ASSERT_EQ(zx_handle_close(exception_channel), ZX_OK);
// Clean up.
EXPECT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, nullptr), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
TEST(Threads, SuspendSelf) {
zx_handle_t suspend_token;
EXPECT_EQ(zx_task_suspend(zx_thread_self(), &suspend_token), ZX_ERR_NOT_SUPPORTED);
}
TEST(Threads, SuspendAfterDeath) {
zxr_thread_t thread;
zx_handle_t thread_h;
ASSERT_TRUE(start_thread(threads_test_sleep_fn, (void*)zx_deadline_after(ZX_MSEC(100)), &thread,
&thread_h));
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
EXPECT_EQ(zx_task_suspend(thread_h, &suspend_token), ZX_ERR_BAD_STATE);
EXPECT_EQ(suspend_token, ZX_HANDLE_INVALID);
EXPECT_EQ(zx_handle_close(suspend_token), ZX_OK);
EXPECT_EQ(zx_handle_close(thread_h), ZX_OK);
}
// Suspend a thread before starting and make sure it starts into suspended state.
TEST(Threads, StartSuspendedThread) {
zxr_thread_t thread;
zx_handle_t thread_h;
ThreadStarter starter;
starter.CreateThread(&thread, &thread_h, true);
// Suspend first, then start the thread.
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend(thread_h, &suspend_token), ZX_OK);
std::atomic<int> value = 0;
ASSERT_TRUE(starter.StartThread(threads_test_atomic_store, &value));
// Make sure the thread goes directly to suspended state without executing at all.
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_SUSPENDED, ZX_TIME_INFINITE, NULL), ZX_OK);
// Once we know it's suspended, give it a real stack.
starter.GrowStackVmo();
// Make sure the thread still resumes properly.
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_RUNNING, ZX_TIME_INFINITE, NULL), ZX_OK);
while (value != kTestAtomicSetValue) {
zx_nanosleep(0);
}
// Clean up.
value.store(kTestAtomicExitValue);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
// Suspend and resume a thread before starting, it should start as normal.
TEST(Threads, StartSuspendedAndResumedThread) {
zxr_thread_t thread;
zx_handle_t thread_h;
ThreadStarter starter;
starter.CreateThread(&thread, &thread_h);
// Suspend and resume.
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend(thread_h, &suspend_token), ZX_OK);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
// Start the thread, it should behave normally.
std::atomic<int> value = 0;
ASSERT_TRUE(starter.StartThread(threads_test_atomic_store, &value));
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_RUNNING, ZX_TIME_INFINITE, NULL), ZX_OK);
while (value != 1) {
zx_nanosleep(0);
}
// Clean up.
value.store(kTestAtomicExitValue);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
static void port_wait_for_signal(zx_handle_t port, zx_handle_t thread, zx_time_t deadline,
zx_signals_t mask, zx_port_packet_t* packet) {
ASSERT_EQ(zx_object_wait_async(thread, port, 0u, mask, 0), ZX_OK);
ASSERT_EQ(zx_port_wait(port, deadline, packet), ZX_OK);
ASSERT_EQ(packet->type, ZX_PKT_TYPE_SIGNAL_ONE);
}
// Test signal delivery of suspended threads via async wait.
static void TestSuspendWaitAsyncSignalDeliveryWorker() {
zx_handle_t event;
zx_handle_t port;
zxr_thread_t thread;
zx_handle_t thread_h;
const zx_signals_t run_susp_mask = ZX_THREAD_RUNNING | ZX_THREAD_SUSPENDED;
ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
ASSERT_TRUE(start_thread(threads_test_wait_fn, &event, &thread, &thread_h));
ASSERT_EQ(zx_port_create(0, &port), ZX_OK);
zx_port_packet_t packet;
// There should be a RUNNING signal packet present and not SUSPENDED.
// This is from when the thread first started to run.
port_wait_for_signal(port, thread_h, 0u, run_susp_mask, &packet);
ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_RUNNING);
// Make sure there are no more packets.
// RUNNING or SUSPENDED is always asserted.
ASSERT_EQ(zx_object_wait_async(thread_h, port, 0u, ZX_THREAD_SUSPENDED, 0), ZX_OK);
ASSERT_EQ(zx_port_wait(port, 0u, &packet), ZX_ERR_TIMED_OUT);
ASSERT_EQ(zx_port_cancel(port, thread_h, 0u), ZX_OK);
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
suspend_thread_synchronous(thread_h, &suspend_token);
zx_info_thread_t info;
ASSERT_TRUE(get_thread_info(thread_h, &info));
ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
resume_thread_synchronous(thread_h, suspend_token);
ASSERT_TRUE(get_thread_info(thread_h, &info));
// At this point the thread may be running or blocked waiting for an
// event. Either one is fine. threads_test_wait_fn() uses
// zx_object_wait_one() so we watch for that.
ASSERT_TRUE(info.state == ZX_THREAD_STATE_RUNNING ||
info.state == ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
// We should see just RUNNING,
// and it should be immediately present (no deadline).
port_wait_for_signal(port, thread_h, 0u, run_susp_mask, &packet);
ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_RUNNING);
// The thread should still be blocked on the event when it wakes up.
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
// Check that suspend/resume while blocked in a syscall results in
// the expected behavior and is visible via async wait.
suspend_token = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_task_suspend_token(thread_h, &suspend_token), ZX_OK);
port_wait_for_signal(port, thread_h, zx_deadline_after(ZX_MSEC(100)), ZX_THREAD_SUSPENDED,
&packet);
ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_SUSPENDED);
ASSERT_TRUE(get_thread_info(thread_h, &info));
ASSERT_EQ(info.state, ZX_THREAD_STATE_SUSPENDED);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
port_wait_for_signal(port, thread_h, zx_deadline_after(ZX_MSEC(100)), ZX_THREAD_RUNNING, &packet);
ASSERT_EQ(packet.signal.observed & run_susp_mask, ZX_THREAD_RUNNING);
// Resumption from being suspended back into a blocking syscall will be
// in the RUNNING state and then BLOCKED.
wait_thread_blocked(thread_h, ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_object_wait_one(thread_h, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(port), ZX_OK);
ASSERT_EQ(zx_handle_close(event), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_h), ZX_OK);
}
// Test signal delivery of suspended threads via single async wait.
TEST(Threads, SuspendSingleWaitAsyncSignalDelivery) { TestSuspendWaitAsyncSignalDeliveryWorker(); }
// Test signal delivery of suspended threads via repeating async wait.
TEST(Threads, SuspendRepeatingWaitAsyncSignalDelivery) {
TestSuspendWaitAsyncSignalDeliveryWorker();
}
// Helper class for setting up a test for reading register state from a worker thread.
template <typename RegisterStruct>
class RegisterReadSetup {
public:
using ThreadFunc = void (*)(RegisterStruct*);
RegisterReadSetup() = default;
~RegisterReadSetup() { ExitThread(); }
zx_handle_t thread_handle() const { return thread_handle_; }
// Run |thread_func| with |state|. Once the thread reaches |expected_pc|, return, leaving the
// thread suspended.
void RunUntil(ThreadFunc thread_func, RegisterStruct* state, uintptr_t expected_pc) {
ASSERT_TRUE(start_thread((void (*)(void*))thread_func, state, &thread_, &thread_handle_));
while (true) {
ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_MSEC(1))), ZX_OK);
Suspend();
zx_thread_state_general_regs_t regs;
ASSERT_EQ(
zx_thread_read_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
if (regs.REG_PC == expected_pc) {
break;
}
Resume();
}
}
void Resume() { resume_thread_synchronous(thread_handle_, suspend_token_); }
void Suspend() { suspend_thread_synchronous(thread_handle_, &suspend_token_); }
void ExitThread() {
zx_info_thread_t info;
ASSERT_TRUE(get_thread_info(thread_handle_, &info));
if (info.state != ZX_THREAD_STATE_SUSPENDED) {
Suspend();
}
zx_thread_state_general_regs_t regs;
ASSERT_EQ(
zx_thread_read_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
#if defined(__aarch64__)
regs.pc = reinterpret_cast<uintptr_t>(zx_thread_exit);
#elif defined(__x86_64__)
regs.rip = reinterpret_cast<uintptr_t>(zx_thread_exit);
#else
#error "what machine?"
#endif
ASSERT_EQ(
zx_thread_write_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
ASSERT_EQ(zx_handle_close(suspend_token_), ZX_OK);
// Wait for the thread termination to complete.
zx_object_wait_one(thread_handle_, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL);
zx_handle_close(thread_handle_);
}
private:
zxr_thread_t thread_;
zx_handle_t thread_handle_ = ZX_HANDLE_INVALID;
zx_handle_t suspend_token_ = ZX_HANDLE_INVALID;
};
// This tests the registers reported by zx_thread_read_state() for a
// suspended thread. It starts a thread which sets all the registers to
// known test values.
TEST(Threads, ReadingGeneralRegisterState) {
zx_thread_state_general_regs_t gen_regs_expected;
general_regs_fill_test_values(&gen_regs_expected);
gen_regs_expected.REG_PC = (uintptr_t)spin_address;
RegisterReadSetup<zx_thread_state_general_regs_t> setup;
setup.RunUntil(&spin_with_general_regs, &gen_regs_expected,
reinterpret_cast<uintptr_t>(&spin_address));
zx_thread_state_general_regs_t regs;
ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS, ®s,
sizeof(regs)),
ZX_OK);
ASSERT_NO_FATAL_FAILURES(general_regs_expect_eq(regs, gen_regs_expected));
}
TEST(Threads, ReadingFpRegisterState) {
zx_thread_state_fp_regs_t fp_regs_expected;
fp_regs_fill_test_values(&fp_regs_expected);
RegisterReadSetup<zx_thread_state_fp_regs_t> setup;
setup.RunUntil(&spin_with_fp_regs, &fp_regs_expected, reinterpret_cast<uintptr_t>(&spin_address));
zx_thread_state_fp_regs_t regs;
zx_status_t status =
zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_FP_REGS, ®s, sizeof(regs));
#if defined(__x86_64__)
ASSERT_EQ(status, ZX_OK);
ASSERT_NO_FATAL_FAILURES(fp_regs_expect_eq(regs, fp_regs_expected));
#elif defined(__aarch64__)
ASSERT_EQ(status, ZX_ERR_NOT_SUPPORTED);
#else
#error unsupported platform
#endif
}
TEST(Threads, ReadingVectorRegisterState) {
zx_thread_state_vector_regs_t vector_regs_expected;
vector_regs_fill_test_values(&vector_regs_expected);
RegisterReadSetup<zx_thread_state_vector_regs_t> setup;
setup.RunUntil(&spin_with_vector_regs, &vector_regs_expected,
reinterpret_cast<uintptr_t>(&spin_address));
zx_thread_state_vector_regs_t regs;
memset(®s, 0xff, sizeof(regs));
ASSERT_EQ(
zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS, ®s, sizeof(regs)),
ZX_OK);
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_unsupported_are_zero(regs));
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_eq(regs, vector_regs_expected));
}
// Procedure:
// 1. Call Init() which will start a thread and suspend it.
// 2. Write the register state you want to the thread_handle().
// 3. Call DoSave with the save function and pointer. This will execute that code in the context of
// the thread.
template <typename RegisterStruct>
class RegisterWriteSetup {
public:
using SaveFunc = void (*)();
RegisterWriteSetup() = default;
~RegisterWriteSetup() { zx_handle_close(thread_handle_); }
zx_handle_t thread_handle() const { return thread_handle_; }
void Init() {
ASSERT_TRUE(start_thread(threads_test_atomic_store, &p_, &thread_, &thread_handle_));
// Wait for the thread to begin executing.
while (p_.load() == 0) {
zx_nanosleep(zx_deadline_after(THREAD_BLOCKED_WAIT_DURATION));
}
suspend_thread_synchronous(thread_handle_, &suspend_token_);
}
// The IP and SP set in the general registers will be filled in to the optional output
// parameters. This is for the general register test since we change those values out from
// under it.
void DoSave(SaveFunc save_func, RegisterStruct* out, uint64_t* general_ip = nullptr,
uint64_t* general_sp = nullptr) {
// Modify the PC to point to the routine, and the SP to point to the output struct.
zx_thread_state_general_regs_t general_regs;
ASSERT_EQ(zx_thread_read_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS, &general_regs,
sizeof(general_regs)),
ZX_OK);
struct {
// A small stack that is used for calling zx_thread_exit().
char stack[1024] __ALIGNED(16);
RegisterStruct regs_got; // STACK_PTR will point here.
} stack;
general_regs.REG_PC = (uintptr_t)save_func;
general_regs.REG_STACK_PTR = (uintptr_t)(stack.stack + sizeof(stack.stack));
ASSERT_EQ(zx_thread_write_state(thread_handle_, ZX_THREAD_STATE_GENERAL_REGS, &general_regs,
sizeof(general_regs)),
ZX_OK);
if (general_ip)
*general_ip = general_regs.REG_PC;
if (general_sp)
*general_sp = general_regs.REG_STACK_PTR;
// Unsuspend the thread and wait for it to finish executing, this will run the code
// and fill the RegisterStruct we passed.
ASSERT_EQ(zx_handle_close(suspend_token_), ZX_OK);
suspend_token_ = ZX_HANDLE_INVALID;
ASSERT_EQ(zx_object_wait_one(thread_handle_, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL),
ZX_OK);
memcpy(out, &stack.regs_got, sizeof(RegisterStruct));
}
private:
std::atomic<int> p_ = 0;
zxr_thread_t thread_;
zx_handle_t thread_handle_ = ZX_HANDLE_INVALID;
zx_handle_t suspend_token_ = ZX_HANDLE_INVALID;
};
// This tests writing registers using zx_thread_write_state(). After
// setting registers using that syscall, it reads back the registers and
// checks their values.
TEST(Threads, WritingGeneralRegisterState) {
RegisterWriteSetup<zx_thread_state_general_regs_t> setup;
setup.Init();
// Set the general registers.
zx_thread_state_general_regs_t regs_to_set;
general_regs_fill_test_values(®s_to_set);
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS, ®s_to_set,
sizeof(regs_to_set)),
ZX_OK);
zx_thread_state_general_regs_t regs;
uint64_t ip = 0, sp = 0;
setup.DoSave(&save_general_regs_and_exit_thread, ®s, &ip, &sp);
// Fix up the expected values with the IP/SP required for the register read.
regs_to_set.REG_PC = ip;
regs_to_set.REG_STACK_PTR = sp;
ASSERT_NO_FATAL_FAILURES(general_regs_expect_eq(regs_to_set, regs));
}
// This tests writing single step state using zx_thread_write_state().
TEST(Threads, WritingSingleStepState) {
RegisterWriteSetup<zx_thread_state_single_step_t> setup;
setup.Init();
// 0 is valid.
zx_thread_state_single_step_t single_step = 0;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_SINGLE_STEP, &single_step,
sizeof(single_step)),
ZX_OK);
// 1 is valid.
single_step = 1;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_SINGLE_STEP, &single_step,
sizeof(single_step)),
ZX_OK);
// All other values are invalid.
single_step = 2;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_SINGLE_STEP, &single_step,
sizeof(single_step)),
ZX_ERR_INVALID_ARGS);
single_step = UINT32_MAX;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_SINGLE_STEP, &single_step,
sizeof(single_step)),
ZX_ERR_INVALID_ARGS);
// Buffer can be larger than necessary.
single_step = 0;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_SINGLE_STEP, &single_step,
sizeof(single_step) + 1),
ZX_OK);
// But not smaller.
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_SINGLE_STEP, &single_step,
sizeof(single_step) - 1),
ZX_ERR_BUFFER_TOO_SMALL);
}
TEST(Threads, WritingFpRegisterState) {
RegisterWriteSetup<zx_thread_state_fp_regs_t> setup;
setup.Init();
// The busyloop code executed initially by the setup class will have executed an MMX instruction
// so that the MMX state is available to write.
zx_thread_state_fp_regs_t regs_to_set;
fp_regs_fill_test_values(®s_to_set);
zx_status_t status = zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_FP_REGS,
®s_to_set, sizeof(regs_to_set));
#if defined(__x86_64__)
ASSERT_EQ(status, ZX_OK);
zx_thread_state_fp_regs_t regs;
setup.DoSave(&save_fp_regs_and_exit_thread, ®s);
ASSERT_NO_FATAL_FAILURES(fp_regs_expect_eq(regs_to_set, regs));
#elif defined(__aarch64__)
ASSERT_EQ(status, ZX_ERR_NOT_SUPPORTED);
#else
#error unsupported platform
#endif
}
TEST(Threads, WritingVectorRegisterState) {
RegisterWriteSetup<zx_thread_state_vector_regs_t> setup;
setup.Init();
zx_thread_state_vector_regs_t regs_to_set;
vector_regs_fill_test_values(®s_to_set);
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_unsupported_are_zero(regs_to_set));
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS, ®s_to_set,
sizeof(regs_to_set)),
ZX_OK);
zx_thread_state_vector_regs_t regs;
setup.DoSave(&save_vector_regs_and_exit_thread, ®s);
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_eq(regs_to_set, regs));
}
TEST(Threads, WritingVectorRegisterState_UnsupportedFieldsIgnored) {
RegisterWriteSetup<zx_thread_state_vector_regs_t> setup;
setup.Init();
zx_thread_state_vector_regs_t regs;
vector_regs_fill_test_values(®s);
#if defined(__x86_64__)
// Fill in the fields corresponding to unsupported features so we can later verify they are zeroed
// out by |zx_thread_read_state|.
for (int reg = 0; reg < 16; reg++) {
for (int i = 5; i < 8; i++) {
regs.zmm[reg].v[i] = 0xfffffffffffffffful;
}
}
for (int reg = 16; reg < 32; reg++) {
for (int i = 0; i < 8; i++) {
regs.zmm[reg].v[i] = 0xfffffffffffffffful;
}
}
#endif
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS, ®s,
sizeof(regs)),
ZX_OK);
ASSERT_EQ(
zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS, ®s, sizeof(regs)),
ZX_OK);
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_unsupported_are_zero(regs));
zx_thread_state_vector_regs_t vector_regs_expected;
vector_regs_fill_test_values(&vector_regs_expected);
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_eq(regs, vector_regs_expected));
}
// Test for fxbug.dev/50632: Make sure zx_thread_write_state doesn't overwrite
// reserved bits in mxcsr (x64 only).
TEST(Threads, WriteThreadStateWithInvalidMxcsrIsInvalidArgs) {
#if defined(__x86_64__)
RegisterWriteSetup<zx_thread_state_vector_regs_t> setup;
setup.Init();
zx_thread_state_vector_regs_t start_values;
ASSERT_OK(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS, &start_values,
sizeof(start_values)));
zx_thread_state_vector_regs_t regs_to_set;
vector_regs_fill_test_values(®s_to_set);
regs_to_set.mxcsr = 0xffffffff;
EXPECT_EQ(ZX_ERR_INVALID_ARGS,
zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_VECTOR_REGS, ®s_to_set,
sizeof(regs_to_set)));
zx_thread_state_vector_regs_t end_values;
setup.DoSave(&save_vector_regs_and_exit_thread, &end_values);
ASSERT_NO_FATAL_FAILURES(vector_regs_expect_eq(start_values, end_values));
#endif // defined(__x86_64__)
}
// This test starts a thread which reads and writes from TLS.
TEST(Threads, ThreadLocalRegisterState) {
RegisterWriteSetup<struct thread_local_regs> setup;
setup.Init();
zx_thread_state_general_regs_t regs = {};
#if defined(__x86_64__)
// The thread will read these from the fs and gs base addresses
// into the output regs struct, and then write different numbers.
uint64_t fs_base_value = 0x1234;
uint64_t gs_base_value = 0x5678;
regs.fs_base = (uintptr_t)&fs_base_value;
regs.gs_base = (uintptr_t)&gs_base_value;
#elif defined(__aarch64__)
uint64_t tpidr_value = 0x1234;
regs.tpidr = (uintptr_t)&tpidr_value;
#endif
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS, ®s,
sizeof(regs)),
ZX_OK);
struct thread_local_regs tls_regs;
setup.DoSave(&save_thread_local_regs_and_exit_thread, &tls_regs);
#if defined(__x86_64__)
EXPECT_EQ(tls_regs.fs_base_value, 0x1234);
EXPECT_EQ(tls_regs.gs_base_value, 0x5678);
EXPECT_EQ(fs_base_value, 0x12345678);
EXPECT_EQ(gs_base_value, 0x7890abcd);
#elif defined(__aarch64__)
EXPECT_EQ(tls_regs.tpidr_value, 0x1234);
EXPECT_EQ(tpidr_value, 0x12345678);
#endif
}
#if defined(__x86_64__)
#include <cpuid.h>
// This is based on code from kernel/ which isn't usable by code in system/.
enum { X86_CPUID_ADDR_WIDTH = 0x80000008 };
static uint32_t x86_linear_address_width() {
uint32_t eax, ebx, ecx, edx;
__cpuid(X86_CPUID_ADDR_WIDTH, eax, ebx, ecx, edx);
return (eax >> 8) & 0xff;
}
#endif
TEST(Threads, ThreadStartInvalidEntry) {
auto test_thread_start = [&](uintptr_t pc, zx_status_t expected) {
zx_handle_t process = zx_process_self();
zx_handle_t thread = ZX_HANDLE_INVALID;
ASSERT_OK(
zx_thread_create(process, kThreadName, sizeof(kThreadName) - 1, 0 /* options */, &thread));
char stack[1024] __ALIGNED(16); // a small stack for the thread.
uintptr_t thread_stack = reinterpret_cast<uintptr_t>(&stack[1024]);
EXPECT_EQ(expected, zx_thread_start(thread, pc, thread_stack, 0 /* arg0 */, 0 /* arg1 */));
zx_handle_close(thread);
};
uintptr_t non_user_pc = 0x1UL;
uintptr_t kernel_pc = 0xffffff8000000000UL;
test_thread_start(non_user_pc, ZX_ERR_INVALID_ARGS);
test_thread_start(kernel_pc, ZX_ERR_INVALID_ARGS);
#if defined(__x86_64__)
uintptr_t non_canonical_pc = ((uintptr_t)1) << (x86_linear_address_width() - 1);
test_thread_start(non_canonical_pc, ZX_ERR_INVALID_ARGS);
#endif // defined(__x86_64__)
}
// Test that zx_thread_write_state() does not allow setting RIP to a
// non-canonical address for a thread that was suspended inside a syscall,
// because if the kernel returns to that address using SYSRET, that can
// cause a fault in kernel mode that is exploitable. See
// sysret_problem.md.
TEST(Threads, NoncanonicalRipAddressSyscall) {
#if defined(__x86_64__)
zx_handle_t event;
ASSERT_EQ(zx_event_create(0, &event), ZX_OK);
zxr_thread_t thread;
zx_handle_t thread_handle;
ASSERT_TRUE(start_thread(threads_test_wait_fn, &event, &thread, &thread_handle));
// Wait until the thread has entered the syscall.
wait_thread_blocked(thread_handle, ZX_THREAD_STATE_BLOCKED_WAIT_ONE);
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
suspend_thread_synchronous(thread_handle, &suspend_token);
zx_thread_state_general_regs_t regs;
ASSERT_EQ(zx_thread_read_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
// Example addresses to test.
uintptr_t noncanonical_addr = ((uintptr_t)1) << (x86_linear_address_width() - 1);
uintptr_t canonical_addr = noncanonical_addr - 1;
uint64_t kKernelAddr = 0xffffff8000000000UL;
zx_thread_state_general_regs_t regs_modified = regs;
// This RIP address must be disallowed.
regs_modified.rip = noncanonical_addr;
ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s_modified,
sizeof(regs_modified)),
ZX_ERR_INVALID_ARGS);
regs_modified.rip = canonical_addr;
ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s_modified,
sizeof(regs_modified)),
ZX_OK);
// This RIP address does not need to be disallowed, but it is currently
// disallowed because this simplifies the check and it's not useful to
// allow this address.
regs_modified.rip = kKernelAddr;
ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s_modified,
sizeof(regs_modified)),
ZX_ERR_INVALID_ARGS);
// Clean up: Restore the original register state.
ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
// Allow the child thread to resume and exit.
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
ASSERT_EQ(zx_object_signal(event, 0, ZX_USER_SIGNAL_0), ZX_OK);
// Wait for the child thread to signal that it has continued.
ASSERT_EQ(zx_object_wait_one(event, ZX_USER_SIGNAL_1, ZX_TIME_INFINITE, NULL), ZX_OK);
// Wait for the child thread to exit.
ASSERT_EQ(zx_object_wait_one(thread_handle, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
ASSERT_EQ(zx_handle_close(event), ZX_OK);
ASSERT_EQ(zx_handle_close(thread_handle), ZX_OK);
#endif
}
// Test that zx_thread_write_state() does not allow setting RIP to a
// non-canonical address for a thread that was suspended inside an interrupt,
// because if the kernel returns to that address using IRET, that can
// cause a fault in kernel mode that is exploitable.
// See docs/concepts/kernel/sysret_problem.md
TEST(Threads, NoncanonicalRipAddressIRETQ) {
#if defined(__x86_64__)
// Example addresses to test.
uintptr_t noncanonical_addr = ((uintptr_t)1) << (x86_linear_address_width() - 1);
uintptr_t kernel_addr = 0xffffff8000000000UL;
// canonical address that is safe to resume the thread to.
uintptr_t canonical_addr = reinterpret_cast<uintptr_t>(&spin_address);
auto test_rip_value = [&](uintptr_t address, zx_status_t expected) {
zx_thread_state_general_regs_t func_regs;
RegisterReadSetup<zx_thread_state_general_regs_t> setup;
setup.RunUntil(&spin_with_general_regs, &func_regs, reinterpret_cast<uintptr_t>(&spin_address));
zx_thread_state_general_regs_t regs;
ASSERT_OK(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS, ®s,
sizeof(regs)));
regs.rip = address;
EXPECT_EQ(expected, zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_GENERAL_REGS,
®s, sizeof(regs)));
// Resume and re-suspend the thread. Even if the zx_thread_write_state
// returns an error but sets the registers, we still want to observe the
// crash. Note that there is no guarantee that it would happen, as the
// thread might get supsended before it even resumes execution.
setup.Resume();
setup.Suspend();
};
test_rip_value(canonical_addr, ZX_OK);
test_rip_value(noncanonical_addr, ZX_ERR_INVALID_ARGS);
test_rip_value(kernel_addr, ZX_ERR_INVALID_ARGS);
#endif // defined(__x86_64__)
}
// Test that, on ARM64, userland cannot use zx_thread_write_state() to
// modify flag bits such as I and F (bits 7 and 6), which are the IRQ and
// FIQ interrupt disable flags. We don't want userland to be able to set
// those flags to 1, since that would disable interrupts. Also, userland
// should not be able to read these bits.
TEST(Threads, WritingArmFlagsRegister) {
#if defined(__aarch64__)
std::atomic<int> value = 0;
zxr_thread_t thread;
zx_handle_t thread_handle;
ASSERT_TRUE(start_thread(threads_test_atomic_store, &value, &thread, &thread_handle));
// Wait for the thread to start executing and enter its main loop.
while (value != 1) {
ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_USEC(1))), ZX_OK);
}
zx_handle_t suspend_token = ZX_HANDLE_INVALID;
suspend_thread_synchronous(thread_handle, &suspend_token);
zx_thread_state_general_regs_t regs;
ASSERT_EQ(zx_thread_read_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
// Check that zx_thread_read_state() does not report any more flag bits
// than are readable via userland instructions.
const uint64_t kUserVisibleFlags = 0xf0000000;
EXPECT_EQ(regs.cpsr & ~kUserVisibleFlags, 0u);
// Try setting more flag bits.
uint64_t original_cpsr = regs.cpsr;
regs.cpsr |= ~kUserVisibleFlags;
ASSERT_EQ(zx_thread_write_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
// Firstly, if we read back the register flag, the extra flag bits
// should have been ignored and should not be reported as set.
ASSERT_EQ(zx_thread_read_state(thread_handle, ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)),
ZX_OK);
EXPECT_EQ(regs.cpsr, original_cpsr);
// Secondly, if we resume the thread, we should be able to kill it. If
// zx_thread_write_state() set the interrupt disable flags, then if the
// thread gets scheduled, it will never get interrupted and we will not
// be able to kill and join the thread.
value.store(0);
ASSERT_EQ(zx_handle_close(suspend_token), ZX_OK);
// Wait until the thread has actually resumed execution.
while (value.load() != kTestAtomicSetValue) {
ASSERT_EQ(zx_nanosleep(zx_deadline_after(ZX_USEC(1))), ZX_OK);
}
value.store(kTestAtomicExitValue);
ASSERT_EQ(zx_object_wait_one(thread_handle, ZX_THREAD_TERMINATED, ZX_TIME_INFINITE, NULL), ZX_OK);
// Clean up.
#endif
}
TEST(Threads, WriteReadDebugRegisterState) {
#if defined(__x86_64__)
zx_thread_state_debug_regs_t debug_regs_to_write;
zx_thread_state_debug_regs_t debug_regs_expected;
debug_regs_fill_test_values(&debug_regs_to_write, &debug_regs_expected);
// Because setting debug state is priviledged, we need to do it through syscalls:
// 1. Start the thread into a routine that simply spins idly.
// 2. Suspend it.
// 3. Write the expected debug state through a syscall.
// 4. Resume the thread.
// 5. Suspend it again.
// 6. Read the state and compare it.
RegisterReadSetup<zx_thread_state_debug_regs_t> setup;
setup.RunUntil(&spin_with_debug_regs, &debug_regs_to_write,
reinterpret_cast<uintptr_t>(&spin_address));
// Write the test values to the debug registers.
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS,
&debug_regs_to_write, sizeof(debug_regs_to_write)),
ZX_OK);
// Resume and re-suspend the thread.
setup.Resume();
setup.Suspend();
// Get the current debug state of the suspended thread.
zx_thread_state_debug_regs_t regs;
ASSERT_EQ(
zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, ®s, sizeof(regs)),
ZX_OK);
ASSERT_NO_FATAL_FAILURES(debug_regs_expect_eq(__FILE__, __LINE__, regs, debug_regs_expected));
#elif defined(__aarch64__)
// We get how many breakpoints we have.
zx_thread_state_debug_regs_t actual_regs = {};
RegisterReadSetup<zx_thread_state_debug_regs_t> setup;
setup.RunUntil(&spin_with_debug_regs, &actual_regs, reinterpret_cast<uintptr_t>(&spin_address));
ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &actual_regs,
sizeof(actual_regs)),
ZX_OK);
// Arm ensures at least 2 breakpoints.
ASSERT_GE(actual_regs.hw_bps_count, 2u);
ASSERT_LE(actual_regs.hw_bps_count, 16u);
// TODO(donosoc): Once the context switch state tracking is done, add the resume-suspect test
// to ensure that it's keeping the state correctly. This is what is done in the
// x86 portion of this test.
zx_thread_state_debug_regs_t regs, expected;
debug_regs_fill_test_values(®s, &expected);
ASSERT_EQ(
zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, ®s, sizeof(regs)),
ZX_OK);
ASSERT_EQ(
zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, ®s, sizeof(regs)),
ZX_OK);
ASSERT_NO_FATAL_FAILURES(debug_regs_expect_eq(__FILE__, __LINE__, regs, expected));
#endif
}
// All writeable bits as 0.
#define DR6_ZERO_MASK (0xffff0ff0ul)
#define DR7_ZERO_MASK (0x700ul)
TEST(Threads, DebugRegistersValidation) {
#if defined(__x86_64__)
zx_thread_state_debug_regs_t debug_regs = {};
RegisterReadSetup<zx_thread_state_debug_regs_t> setup;
setup.RunUntil(&spin_with_debug_regs, &debug_regs, reinterpret_cast<uintptr_t>(&spin_address));
// Writing all 0s should work and should mask values.
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_OK);
ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_OK);
for (size_t i = 0; i < 4; i++)
ASSERT_EQ(debug_regs.dr[i], 0);
ASSERT_EQ(debug_regs.dr6, DR6_ZERO_MASK);
ASSERT_EQ(debug_regs.dr7, DR7_ZERO_MASK);
// Writing an invalid address should fail.
debug_regs = {};
debug_regs.dr[1] = 0x1000;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_ERR_INVALID_ARGS);
// Writing an kernel address should fail.
debug_regs = {};
debug_regs.dr[2] = 0xffff00000000;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_ERR_INVALID_ARGS);
// Invalid values should be masked out.
debug_regs = {};
debug_regs.dr6 = ~DR6_ZERO_MASK;
// We avoid the General Detection flag, which would make us throw an exception on next write.
debug_regs.dr7 = ~DR7_ZERO_MASK;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_OK);
ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_OK);
for (size_t i = 0; i < 4; i++)
ASSERT_EQ(debug_regs.dr[i], 0);
// DR6: Should not have been written.
ASSERT_EQ(debug_regs.dr6, DR6_ZERO_MASK);
ASSERT_EQ(debug_regs.dr7, 0xffff07ff);
#elif defined(__aarch64__)
zx_thread_state_debug_regs_t debug_regs = {};
zx_thread_state_debug_regs_t actual_regs = {};
RegisterReadSetup<zx_thread_state_debug_regs_t> setup;
setup.RunUntil(&spin_with_debug_regs, &actual_regs, reinterpret_cast<uintptr_t>(&spin_address));
// We read the initial state to know how many HW breakpoints we have.
ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &actual_regs,
sizeof(actual_regs)),
ZX_OK);
// Writing a kernel address should fail.
debug_regs.hw_bps_count = actual_regs.hw_bps_count;
debug_regs.hw_bps[0].dbgbvr = (uint64_t)-1;
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_ERR_INVALID_ARGS, "Kernel address should fail");
// Validation should mask unwanted values from the control register.
// Only bit 0 is unset. This means the breakpoint is disabled.
debug_regs.hw_bps[0].dbgbcr = 0xfffffffe;
debug_regs.hw_bps[0].dbgbvr = 0; // 0 is a valid value.
debug_regs.hw_bps[1].dbgbcr = 0x1; // Only the enabled value is set.
// We use the address of a function we know is in userspace.
debug_regs.hw_bps[1].dbgbvr = reinterpret_cast<uint64_t>(wait_thread_blocked);
ASSERT_EQ(zx_thread_write_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &debug_regs,
sizeof(debug_regs)),
ZX_OK, "Validation should correctly mask invalid values");
// Re-read the state and verify.
ASSERT_EQ(zx_thread_read_state(setup.thread_handle(), ZX_THREAD_STATE_DEBUG_REGS, &actual_regs,
sizeof(actual_regs)),
ZX_OK);
EXPECT_EQ(actual_regs.hw_bps_count, debug_regs.hw_bps_count);
EXPECT_EQ(actual_regs.hw_bps[0].dbgbcr, 0);
EXPECT_EQ(actual_regs.hw_bps[0].dbgbvr, 0);
EXPECT_EQ(actual_regs.hw_bps[1].dbgbcr, 0x000001e5);
EXPECT_EQ(actual_regs.hw_bps[1].dbgbvr, debug_regs.hw_bps[1].dbgbvr);
#endif
}
// This is a regression test for fxbug.dev/34166. Verify that upon entry to the kernel via fault on
// hardware that lacks SMAP, a subsequent usercopy does not panic.
TEST(Threads, X86AcFlagUserCopy) {
#if defined(__x86_64__)
zx::process process;
zx::thread thread;
zx::event event;
ASSERT_EQ(zx::event::create(0, &event), ZX_OK);
ASSERT_EQ(start_mini_process(zx_job_default(), event.get(), process.reset_and_get_address(),
thread.reset_and_get_address()),
ZX_OK);
// Suspend the process so we can set its AC flag.
zx::handle suspend_token;
suspend_thread_synchronous(thread.get(), suspend_token.reset_and_get_address());
zx_thread_state_general_regs_t regs{};
ASSERT_EQ(thread.read_state(ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)), ZX_OK);
// Set AC and change its RIP to 0 so that upon resuming, it will fault and enter the kernel.
regs.rflags |= (1 << 18);
regs.rip = 0;
ASSERT_EQ(thread.write_state(ZX_THREAD_STATE_GENERAL_REGS, ®s, sizeof(regs)), ZX_OK);
// We can't catch this exception in userspace, the test requires the
// kernel do a usercopy from an interrupt context which only happens when
// the exception falls through unhandled.
printf("Crashing a test process, the following dump is intentional\n");
// Resume.
suspend_token.reset();
// See that it has terminated.
ASSERT_EQ(process.wait_one(ZX_THREAD_TERMINATED, zx::time::infinite(), nullptr), ZX_OK);
zx_info_process_t proc_info{};
ASSERT_EQ(process.get_info(ZX_INFO_PROCESS, &proc_info, sizeof(proc_info), nullptr, nullptr),
ZX_OK);
ASSERT_EQ(proc_info.return_code, ZX_TASK_RETCODE_EXCEPTION_KILL);
#endif
}
| 39.203468 | 100 | 0.742134 | [
"object"
] |
f68ea0c9869378681dcd8dde06bf91ac1cb5304f | 6,392 | cc | C++ | zetasql/common/errors.cc | dictav/zetasql | f4b7df010ae94941a984930a82175ee8836d9c0e | [
"Apache-2.0"
] | null | null | null | zetasql/common/errors.cc | dictav/zetasql | f4b7df010ae94941a984930a82175ee8836d9c0e | [
"Apache-2.0"
] | null | null | null | zetasql/common/errors.cc | dictav/zetasql | f4b7df010ae94941a984930a82175ee8836d9c0e | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2019 ZetaSQL 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 "zetasql/common/errors.h"
#include "zetasql/base/logging.h"
#include "zetasql/common/status_payload_utils.h"
#include "zetasql/public/error_helpers.h"
#include "zetasql/public/error_location.pb.h"
#include "absl/strings/str_cat.h"
#include "zetasql/base/canonical_errors.h"
#include "zetasql/base/ret_check.h"
#include "zetasql/base/status_macros.h"
namespace zetasql {
// Returns true if <status> has a internalErrorLocation payload.
static bool HasInternalErrorLocation(const zetasql_base::Status& status) {
return internal::HasPayloadTyped<InternalErrorLocation>(status);
}
zetasql_base::Status StatusWithInternalErrorLocation(
const zetasql_base::Status& status, const ParseLocationPoint& error_location) {
if (status.ok()) return status;
zetasql_base::Status result = status;
internal::AttachPayload(&result, error_location.ToInternalErrorLocation());
return result;
}
ErrorSource MakeErrorSource(
const zetasql_base::Status& status, const std::string& text, ErrorMessageMode mode) {
DCHECK(!status.ok());
// Sanity check that status does not have an InternalErrorLocation.
DCHECK(!HasInternalErrorLocation(status));
ErrorSource error_source;
error_source.set_error_message(std::string(status.message()));
ErrorLocation status_error_location;
if (GetErrorLocation(status, &status_error_location)) {
*error_source.mutable_error_location() = status_error_location;
if (mode == ErrorMessageMode::ERROR_MESSAGE_MULTI_LINE_WITH_CARET &&
!text.empty()) {
error_source.set_error_message_caret_string(
GetErrorStringWithCaret(text, status_error_location));
}
}
return error_source;
}
// Returns ErrorSources from <status>, if present.
const absl::optional<::google::protobuf::RepeatedPtrField<ErrorSource>> GetErrorSources(
const zetasql_base::Status& status) {
if (internal::HasPayloadTyped<ErrorLocation>(status)) {
// Sanity check that an OK status does not have a payload.
DCHECK(!status.ok());
return internal::GetPayload<ErrorLocation>(status).error_source();
}
return absl::nullopt;
}
std::string DeprecationWarningsToDebugString(
const std::vector<FreestandingDeprecationWarning>& warnings) {
if (warnings.empty()) return "";
return absl::StrCat("(", warnings.size(), " deprecation warning",
(warnings.size() > 1 ? "s" : ""), ")");
}
zetasql_base::StatusOr<FreestandingDeprecationWarning> StatusToDeprecationWarning(
const zetasql_base::Status& from_status, absl::string_view sql) {
ZETASQL_RET_CHECK(zetasql_base::IsInvalidArgument(from_status))
<< "Deprecation statuses must have code INVALID_ARGUMENT";
FreestandingDeprecationWarning warning;
warning.set_message(std::string(from_status.message()));
ZETASQL_RET_CHECK(internal::HasPayload(from_status))
<< "Deprecation statuses must have payloads";
ZETASQL_RET_CHECK(!internal::HasPayloadTyped<InternalErrorLocation>(from_status))
<< "Deprecation statuses cannot have InternalErrorLocation payloads";
ZETASQL_RET_CHECK(internal::HasPayloadTyped<ErrorLocation>(from_status))
<< "Deprecation statuses must have ErrorLocation payloads";
*warning.mutable_error_location() =
internal::GetPayload<ErrorLocation>(from_status);
ZETASQL_RET_CHECK(internal::HasPayloadTyped<DeprecationWarning>(from_status))
<< "Deprecation statuses must have DeprecationWarning payloads";
*warning.mutable_deprecation_warning() =
internal::GetPayload<DeprecationWarning>(from_status);
ZETASQL_RET_CHECK_EQ(internal::GetPayloadCount(from_status), 2)
<< "Found invalid extra payload in deprecation status";
warning.set_caret_string(
GetErrorStringWithCaret(sql, warning.error_location()));
return warning;
}
zetasql_base::StatusOr<std::vector<FreestandingDeprecationWarning>>
StatusesToDeprecationWarnings(const std::vector<zetasql_base::Status>& from_statuses,
absl::string_view sql) {
std::vector<FreestandingDeprecationWarning> warnings;
for (const zetasql_base::Status& from_status : from_statuses) {
ZETASQL_ASSIGN_OR_RETURN(const FreestandingDeprecationWarning warning,
StatusToDeprecationWarning(from_status, sql));
warnings.emplace_back(warning);
}
return warnings;
}
zetasql_base::Status ConvertInternalErrorLocationToExternal(zetasql_base::Status status,
absl::string_view query) {
if (!internal::HasPayloadTyped<InternalErrorLocation>(status)) {
// Nothing to do.
return status;
}
const InternalErrorLocation internal_error_location =
internal::GetPayload<InternalErrorLocation>(status);
const ParseLocationPoint error_point =
ParseLocationPoint::FromInternalErrorLocation(internal_error_location);
ParseLocationTranslator location_translator(query);
std::pair<int, int> line_and_column;
ZETASQL_ASSIGN_OR_RETURN(
line_and_column,
location_translator.GetLineAndColumnAfterTabExpansion(error_point),
_ << "Location " << error_point.GetString() << " from status \""
<< internal::StatusToString(status) << "\" not found in query:\n"
<< query);
ErrorLocation error_location;
if (internal_error_location.has_filename()) {
error_location.set_filename(internal_error_location.filename());
}
error_location.set_line(line_and_column.first);
error_location.set_column(line_and_column.second);
// Copy ErrorSource information if present.
*error_location.mutable_error_source() =
internal_error_location.error_source();
zetasql_base::Status copy = status;
internal::ErasePayloadTyped<InternalErrorLocation>(©);
internal::AttachPayload(©, error_location);
return copy;
}
} // namespace zetasql
| 38.275449 | 89 | 0.751252 | [
"vector"
] |
f690efb148322366e7e9f4a3840003b34eb13343 | 13,137 | hh | C++ | aspects/fluid/conductor/test/UtGunnsFluidPressureSensitiveValve.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | aspects/fluid/conductor/test/UtGunnsFluidPressureSensitiveValve.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | aspects/fluid/conductor/test/UtGunnsFluidPressureSensitiveValve.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | #ifndef UtGunnsFluidPressureSensitiveValve_EXISTS
#define UtGunnsFluidPressureSensitiveValve_EXISTS
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup UT_TSM_GUNNS_FLUID_CONDUCTOR_PRESSURE_SENSITIVE_VALVE Pressure Sensitive Valve Unit Test
/// @ingroup UT_TSM_GUNNS_FLUID_CONDUCTOR
///
/// @copyright Copyright 2019 United States Government as represented by the Administrator of the
/// National Aeronautics and Space Administration. All Rights Reserved.
///
/// @details Unit Tests for the GUNNS Fluid Pressure Sensitive Valve link model.
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>
#include <iostream>
#include "aspects/fluid/conductor/GunnsFluidPressureSensitiveValve.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Inherit from GunnsFluidPressureSensitiveValve and befriend UtGunnsFluidPressureSensitiveValve.
///
/// @reqt testUpdateStateNominal R.TS222-0063 TS21 ECLSS models shall perform pressure regulator control.
/// @reqt testUpdateStateMalfunction R.TS222-0068 TS21 ECLSS models shall provide malfunctions to freeze valves at non-target positions.
/// @reqt testUpdateStateNominal R.TS222-0082 TS21 ECLSS models shall simulate the functionality of valves.
/// @reqt testUpdateStateMalfunction R.TS222-0083 TS21 ECLSS models shall malfunction valves.
/// @reqt testUpdateStateNominal R.TS228-0001 TS21 thermal models shall simulate the functionality of valves.
/// @reqt testUpdateStateMalfunction R.TS228-0029 TS21 thermal models shall provide valve malfunctions.
///
/// @details Class derived from the unit under test. It just has a constructor with the same
/// arguments as the parent and a default destructor, but it befriends the unit test case
/// driver class to allow it access to protected data members.
////////////////////////////////////////////////////////////////////////////////////////////////////
class FriendlyGunnsFluidPressureSensitiveValve : public GunnsFluidPressureSensitiveValve
{
public:
FriendlyGunnsFluidPressureSensitiveValve();
virtual ~FriendlyGunnsFluidPressureSensitiveValve();
friend class UtGunnsFluidPressureSensitiveValve;
};
inline FriendlyGunnsFluidPressureSensitiveValve::FriendlyGunnsFluidPressureSensitiveValve() : GunnsFluidPressureSensitiveValve() {};
inline FriendlyGunnsFluidPressureSensitiveValve::~FriendlyGunnsFluidPressureSensitiveValve() {}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief GUNNS Fluid Pressure Sensitive Valve unit tests.
////
/// @details This class provides the unit tests for the GUNNS Fluid Pressure Sensitive Valve link
/// model within the CPPUnit framework.
////////////////////////////////////////////////////////////////////////////////////////////////////
class UtGunnsFluidPressureSensitiveValve: public CppUnit::TestFixture
{
public:
/// @brief Default constructs this Pressure Sensitive Valve unit test.
UtGunnsFluidPressureSensitiveValve();
/// @brief Default destructs this Pressure Sensitive Valve unit test.
virtual ~UtGunnsFluidPressureSensitiveValve();
void setUp();
/// @brief Executes after each test.
void tearDown();
/// @brief Tests config and input data.
void testConfigAndInput();
/// @brief Tests default construction.
void testDefaultConstruction();
/// @brief Tests initialize method.
void testNominalInitialization();
/// @brief Tests accessor methods.
void testAccessors();
/// @brief Tests modifier methods.
void testModifiers();
/// @brief Tests step method.
void testStep();
/// @brief Tests compute flows method.
void testComputeFlows();
/// @brief Tests compute flows method with internal fluid.
void testComputeFlowsWithInternalFluid();
/// @brief Tests tuning method.
void testTuning();
/// @brief Tests update state method (nominal).
void testUpdateStateNominal();
/// @brief Tests update state method (malfunction).
void testUpdateStateMalfunction();
/// @brief Tests initialize method exceptions.
void testInitializationExceptions();
private:
CPPUNIT_TEST_SUITE(UtGunnsFluidPressureSensitiveValve);
CPPUNIT_TEST(testConfigAndInput);
CPPUNIT_TEST(testDefaultConstruction);
CPPUNIT_TEST(testNominalInitialization);
CPPUNIT_TEST(testAccessors);
CPPUNIT_TEST(testModifiers);
CPPUNIT_TEST(testStep);
CPPUNIT_TEST(testComputeFlows);
CPPUNIT_TEST(testComputeFlowsWithInternalFluid);
CPPUNIT_TEST(testTuning);
CPPUNIT_TEST(testUpdateStateNominal);
CPPUNIT_TEST(testUpdateStateMalfunction);
CPPUNIT_TEST(testInitializationExceptions);
CPPUNIT_TEST_SUITE_END();
/// @brief Enumeration for the number of nodes and fluid constituents.
enum {N_NODES = 4, N_FLUIDS = 2};
FluidProperties::FluidType mTypes[N_FLUIDS]; /**< (--) Constituent fluid types array. */
double mFractions[N_FLUIDS]; /**< (--) Constituent fluid mass fractions array. */
DefinedFluidProperties* mFluidProperties; /**< (--) Predefined fluid properties. */
PolyFluidConfigData* mFluidConfig; /**< (--) Fluid config data. */
PolyFluidInputData* mFluidInput0; /**< (--) Fluid input data for node 0. */
PolyFluidInputData* mFluidInput1; /**< (--) Fluid input data for node 1. */
PolyFluidInputData* mFluidInput2; /**< (--) Fluid input data for node 2. */
PolyFluidInputData* mFluidInput3; /**< (--) Fluid input data for node 3. */
std::vector<GunnsBasicLink*> mLinks; /**< (--) Link vector. */
std::string mName; /**< (--) Nominal name. */
GunnsFluidNode mNodes[N_NODES]; /**< (--) Nominal connected nodes. */
GunnsNodeList mNodeList; /**< (--) Network node structure. */
int mPort0; /**< (--) Nominal inlet port node index. */
int mPort1; /**< (--) Nominal outlet port node index. */
int mPort2; /**< (--) Nominal inlet pressure port node index. */
int mPort3; /**< (--) Nominal outlet pressure port node index. */
double mMaxConductivity; /**< (m2) Nominal maximum conductivity. */
double mExpansionScaleFactor; /**< (--) Nominal scale factor for isentropic gas cooling. */
double mRateLimit; /**< (one/s) Nominal fractional position rate limit. */
double mThermalLength; /**< (m) Tube length for thermal convection. */
double mThermalDiameter; /**< (m) Tube inner diameter for thermal convection. */
double mSurfaceRoughness; /**< (m) Tube wall surface roughness for thermal convection. */
double mThermalSurfaceArea; /**< (m2) Tube inner surface area for thermal convection */
double mThermalROverD; /**< (--) Tube surface roughness over diameter for convection */
GunnsFluidPressureSensitiveValveConfigData* mConfigData; /**< (--) Pointer to the nominal configuration data. */
bool mMalfBlockageFlag; /**< (--) Blockage malfunction flag. */
double mMalfBlockageValue; /**< (--) Blockage malfunction value. */
double mPosition; /**< (--) Fractional position of this valve. */
bool mMalfLeakThruFlag; /**< (--) Leak through rate malfunction flag. */
double mMalfLeakThruValue; /**< (kg/s) Leak through rate malfunction value. */
bool mMalfPressureBiasFlag; /**< (--) Control pressure bias malfunction flag. */
double mMalfPressureBiasValue; /**< (kPa) Control pressure bias malfunction value. */
double mSetPointPressureBias; /**< (kPa) Set point pressure bias value. */
double mWallTemperature; /**< (K) Tube wall temperature for thermal convection */
bool mMalfStuckFlag; /**< (--) Stuck at current position malfunction flag. */
bool mMalfFailToFlag; /**< (--) Fail to position malfunction flag. */
double mMalfFailToValue; /**< (--) Fail to position malfunction value. */
GunnsFluidPressureSensitiveValveInputData* mInputData; /**< (--) Pointer to the nominal input data. */
FriendlyGunnsFluidPressureSensitiveValve* mArticle; /**< (--) Pointer to the friendly Pressure Sensitive Valve under test. */
double mPreviousLeakRate; /**< (kg/s) Previous leak thru rate value. */
double mLeakConductivity; /**< (m2) Conductivity equivalent to the leak. */
GunnsFluidUtils::TuningMode mTuneMode; /**< (--) Auto-tunes the link to desired flow type. */
double mTuneMassFlow; /**< (kg/s) The desired mass flow for link tuning. */
double mTuneVolFlow; /**< (m3/s) The desired volumetric flow for link tuning. */
double mTuneDeltaT; /**< (K) The desired delta-temperature for link tuning. */
double mEffectiveConductivity; /**< (m2) Effective conductivity of the link. */
double mSystemConductance; /**< (kg*mol/kPa/s) Limited molar conductance. */
double mLastSystemConductance; /**< (kg*mol/kPa/s) Last-pass value of mSystemConductance. */
double mControlPressure; /**< (kPa) Valve control pressure. */
double mWallHeatFlux; /**< (W) Convection heat flux from the fluid to the tube wall */
double mTimeStep; /**< (s) Nominal time step. */
double mTolerance; /**< (--) Nominal tolerance for comparison of expected and returned values. */
static int TEST_ID; /**< (--) Test identification number. */
/// @brief Copy constructor unavailable since declared private and not implemented.
UtGunnsFluidPressureSensitiveValve(const UtGunnsFluidPressureSensitiveValve& that);
/// @brief Assignment operator unavailable since declared private and not implemented.
UtGunnsFluidPressureSensitiveValve& operator =(const UtGunnsFluidPressureSensitiveValve& that);
};
///@}
#endif
| 80.103659 | 168 | 0.50727 | [
"vector",
"model"
] |
f69211d0227fc583da808d939224e2b427c9b7ac | 60,847 | cpp | C++ | tests/vklayertests_best_practices.cpp | kedarthangudu/Vulkan-ValidationLayers | f4a485f0aedde2064c85907fa89aa489b398d253 | [
"Apache-2.0"
] | null | null | null | tests/vklayertests_best_practices.cpp | kedarthangudu/Vulkan-ValidationLayers | f4a485f0aedde2064c85907fa89aa489b398d253 | [
"Apache-2.0"
] | null | null | null | tests/vklayertests_best_practices.cpp | kedarthangudu/Vulkan-ValidationLayers | f4a485f0aedde2064c85907fa89aa489b398d253 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015-2020 The Khronos Group Inc.
* Copyright (c) 2015-2020 Valve Corporation
* Copyright (c) 2015-2020 LunarG, Inc.
* Copyright (c) 2015-2020 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Author: Camden Stocker <camden@lunarg.com>
*/
#include "cast_utils.h"
#include "layer_validation_tests.h"
void VkBestPracticesLayerTest::InitBestPracticesFramework() {
// Enable all vendor-specific checks
VkLayerSettingValueDataEXT bp_setting_string_value{};
bp_setting_string_value.arrayString.pCharArray = "VALIDATION_CHECK_ENABLE_VENDOR_SPECIFIC_ALL";
bp_setting_string_value.arrayString.count = sizeof(bp_setting_string_value.arrayString.pCharArray);
VkLayerSettingValueEXT bp_vendor_all_setting_val = {"enables", VK_LAYER_SETTING_VALUE_TYPE_STRING_ARRAY_EXT,
bp_setting_string_value};
VkLayerSettingsEXT bp_settings{static_cast<VkStructureType>(VK_STRUCTURE_TYPE_INSTANCE_LAYER_SETTINGS_EXT), nullptr, 1,
&bp_vendor_all_setting_val};
features_.pNext = &bp_settings;
InitFramework(m_errorMonitor, &features_);
}
TEST_F(VkBestPracticesLayerTest, ValidateReturnCodes) {
uint32_t version = SetTargetApiVersion(VK_API_VERSION_1_2);
if (version < VK_API_VERSION_1_1) {
printf("%s At least Vulkan version 1.2 is required, skipping test.\n", kSkipPrefix);
return;
}
if (!AddSurfaceInstanceExtension()) {
printf("%s surface extensions not supported, skipping test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitBestPracticesFramework());
if (!AddSwapchainDeviceExtension()) {
printf("%s swapchain extensions not supported, skipping CmdCopySwapchainImage test\n", kSkipPrefix);
return;
}
ASSERT_NO_FATAL_FAILURE(InitState());
if (!InitSwapchain()) {
printf("%s Cannot create surface or swapchain, skipping CmdCopySwapchainImage test\n", kSkipPrefix);
return;
}
// Attempt to force an invalid return code for an unsupported format
VkImageFormatProperties2 image_format_prop = {};
image_format_prop.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
VkPhysicalDeviceImageFormatInfo2 image_format_info = {};
image_format_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
image_format_info.format = VK_FORMAT_R32G32B32_SFLOAT;
image_format_info.tiling = VK_IMAGE_TILING_LINEAR;
image_format_info.type = VK_IMAGE_TYPE_3D;
image_format_info.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
VkResult result = vk::GetPhysicalDeviceImageFormatProperties2(m_device->phy().handle(), &image_format_info, &image_format_prop);
// Only run this test if this super-wierd format is not supported
if (VK_SUCCESS != result) {
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "UNASSIGNED-BestPractices-Error-Result");
vk::GetPhysicalDeviceImageFormatProperties2(m_device->phy().handle(), &image_format_info, &image_format_prop);
m_errorMonitor->VerifyFound();
}
if (IsPlatform(kMockICD) || DeviceSimulation()) {
printf("%s Test not supported by MockICD, skipping test case.\n", kSkipPrefix);
return;
}
// Force a non-success success code by only asking for a subset of query results
uint32_t format_count;
std::vector<VkSurfaceFormatKHR> formats;
result = vk::GetPhysicalDeviceSurfaceFormatsKHR(gpu(), m_surface, &format_count, NULL);
if (result != VK_SUCCESS || format_count <= 1) {
printf("%s test requires 2 or more extensions available, skipping test.\n", kSkipPrefix);
return;
}
format_count -= 1;
formats.resize(format_count);
m_errorMonitor->SetDesiredFailureMsg(kInformationBit, "UNASSIGNED-BestPractices-NonSuccess-Result");
result = vk::GetPhysicalDeviceSurfaceFormatsKHR(gpu(), m_surface, &format_count, formats.data());
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, UseDeprecatedInstanceExtensions) {
TEST_DESCRIPTION("Create an instance with a deprecated extension.");
uint32_t version = SetTargetApiVersion(VK_API_VERSION_1_1);
if (version < VK_API_VERSION_1_1) {
printf("%s At least Vulkan version 1.1 is required, skipping test.\n", kSkipPrefix);
return;
}
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Did not find %s extension, skipped.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitBestPracticesFramework());
// Create a 1.1 vulkan instance and request an extension promoted to core in 1.1
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "UNASSIGNED-BestPractices-vkCreateInstance-deprecated-extension");
VkInstance dummy;
auto features = features_;
auto ici = GetInstanceCreateInfo();
features.pNext = ici.pNext;
ici.pNext = &features;
vk::CreateInstance(&ici, nullptr, &dummy);
m_errorMonitor->VerifyFound();
// Create a 1.0 vulkan instance and request an extension promoted to core in 1.1
m_errorMonitor->ExpectSuccess(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT);
m_errorMonitor->SetUnexpectedError("UNASSIGNED-khronos-Validation-debug-build-warning-message");
VkApplicationInfo* new_info = new VkApplicationInfo;
new_info->apiVersion = VK_API_VERSION_1_0;
new_info->pApplicationName = ici.pApplicationInfo->pApplicationName;
new_info->applicationVersion = ici.pApplicationInfo->applicationVersion;
new_info->pEngineName = ici.pApplicationInfo->pEngineName;
new_info->engineVersion = ici.pApplicationInfo->engineVersion;
ici.pApplicationInfo = new_info;
vk::CreateInstance(&ici, nullptr, &dummy);
vk::DestroyInstance(dummy, nullptr);
m_errorMonitor->VerifyNotFound();
}
TEST_F(VkBestPracticesLayerTest, UseDeprecatedDeviceExtensions) {
TEST_DESCRIPTION("Create a device with a deprecated extension.");
uint32_t version = SetTargetApiVersion(VK_API_VERSION_1_2);
if (version < VK_API_VERSION_1_2) {
printf("%s At least Vulkan version 1.2 is required, skipping test.\n", kSkipPrefix);
return;
}
if (InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
m_instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Did not find %s extension, skipped.\n", kSkipPrefix, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return;
}
ASSERT_NO_FATAL_FAILURE(InitBestPracticesFramework());
if (DeviceValidationVersion() < VK_API_VERSION_1_2) {
printf("%s At least Vulkan version 1.2 is required for device, skipping test\n", kSkipPrefix);
return;
}
if (DeviceExtensionSupported(gpu(), nullptr, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME)) {
m_device_extension_names.push_back(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
return;
}
VkDevice local_device;
VkDeviceCreateInfo dev_info = {};
VkDeviceQueueCreateInfo queue_info = {};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = NULL;
queue_info.queueFamilyIndex = 0;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = nullptr;
dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dev_info.pNext = nullptr;
dev_info.queueCreateInfoCount = 1;
dev_info.pQueueCreateInfos = &queue_info;
dev_info.enabledLayerCount = 0;
dev_info.ppEnabledLayerNames = NULL;
dev_info.enabledExtensionCount = m_device_extension_names.size();
dev_info.ppEnabledExtensionNames = m_device_extension_names.data();
m_errorMonitor->SetDesiredFailureMsg(kWarningBit, "UNASSIGNED-BestPractices-vkCreateDevice-deprecated-extension");
vk::CreateDevice(this->gpu(), &dev_info, NULL, &local_device);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, CmdClearAttachmentTest) {
TEST_DESCRIPTION("Test for validating usage of vkCmdClearAttachments");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
// Main thing we care about for this test is that the VkImage obj we're
// clearing matches Color Attachment of FB
// Also pass down other dummy params to keep driver and paramchecker happy
VkClearAttachment color_attachment;
color_attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_attachment.clearValue.color.float32[0] = 1.0;
color_attachment.clearValue.color.float32[1] = 1.0;
color_attachment.clearValue.color.float32[2] = 1.0;
color_attachment.clearValue.color.float32[3] = 1.0;
color_attachment.colorAttachment = 0;
VkClearRect clear_rect = {{{0, 0}, {(uint32_t)m_width, (uint32_t)m_height}}, 0, 1};
// Call for full-sized FB Color attachment prior to issuing a Draw
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-DrawState-ClearCmdBeforeDraw");
vk::CmdClearAttachments(m_commandBuffer->handle(), 1, &color_attachment, 1, &clear_rect);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, VtxBufferBadIndex) {
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-DrawState-VtxIndexOutOfBounds");
// This test may also trigger other warnings
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation");
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkPipelineMultisampleStateCreateInfo pipe_ms_state_ci = {};
pipe_ms_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
pipe_ms_state_ci.pNext = NULL;
pipe_ms_state_ci.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
pipe_ms_state_ci.sampleShadingEnable = 0;
pipe_ms_state_ci.minSampleShading = 1.0;
pipe_ms_state_ci.pSampleMask = NULL;
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.pipe_ms_state_ci_ = pipe_ms_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
// Don't care about actual data, just need to get to draw to flag error
const float vbo_data[3] = {1.f, 0.f, 1.f};
VkConstantBufferObj vbo(m_device, sizeof(vbo_data), (const void*)&vbo_data, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
m_commandBuffer->BindVertexBuffer(&vbo, (VkDeviceSize)0, 1); // VBO idx 1, but no VBO in PSO
m_commandBuffer->Draw(1, 0, 0, 0);
m_errorMonitor->VerifyFound();
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
}
// This is a positive test. No failures are expected.
TEST_F(VkBestPracticesLayerTest, TestDestroyFreeNullHandles) {
VkResult err;
TEST_DESCRIPTION("Call all applicable destroy and free routines with NULL handles, expecting no validation errors");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_errorMonitor->ExpectSuccess();
vk::DestroyBuffer(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyBufferView(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyCommandPool(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyDescriptorPool(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyDescriptorSetLayout(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyDevice(VK_NULL_HANDLE, NULL);
vk::DestroyEvent(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyFence(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyFramebuffer(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyImage(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyImageView(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyInstance(VK_NULL_HANDLE, NULL);
vk::DestroyPipeline(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyPipelineCache(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyPipelineLayout(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyQueryPool(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyRenderPass(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroySampler(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroySemaphore(m_device->device(), VK_NULL_HANDLE, NULL);
vk::DestroyShaderModule(m_device->device(), VK_NULL_HANDLE, NULL);
VkCommandPool command_pool;
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = m_device->graphics_queue_node_index_;
pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vk::CreateCommandPool(m_device->device(), &pool_create_info, nullptr, &command_pool);
VkCommandBuffer command_buffers[3] = {};
VkCommandBufferAllocateInfo command_buffer_allocate_info{};
command_buffer_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_allocate_info.commandPool = command_pool;
command_buffer_allocate_info.commandBufferCount = 1;
command_buffer_allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
vk::AllocateCommandBuffers(m_device->device(), &command_buffer_allocate_info, &command_buffers[1]);
vk::FreeCommandBuffers(m_device->device(), command_pool, 3, command_buffers);
vk::DestroyCommandPool(m_device->device(), command_pool, NULL);
VkDescriptorPoolSize ds_type_count = {};
ds_type_count.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
ds_type_count.descriptorCount = 1;
VkDescriptorPoolCreateInfo ds_pool_ci = {};
ds_pool_ci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
ds_pool_ci.pNext = NULL;
ds_pool_ci.maxSets = 1;
ds_pool_ci.poolSizeCount = 1;
ds_pool_ci.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
ds_pool_ci.pPoolSizes = &ds_type_count;
VkDescriptorPool ds_pool;
err = vk::CreateDescriptorPool(m_device->device(), &ds_pool_ci, NULL, &ds_pool);
ASSERT_VK_SUCCESS(err);
VkDescriptorSetLayoutBinding dsl_binding = {};
dsl_binding.binding = 2;
dsl_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
dsl_binding.descriptorCount = 1;
dsl_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
dsl_binding.pImmutableSamplers = NULL;
const VkDescriptorSetLayoutObj ds_layout(m_device, {dsl_binding});
VkDescriptorSet descriptor_sets[3] = {};
VkDescriptorSetAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorSetCount = 1;
alloc_info.descriptorPool = ds_pool;
alloc_info.pSetLayouts = &ds_layout.handle();
err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, &descriptor_sets[1]);
ASSERT_VK_SUCCESS(err);
vk::FreeDescriptorSets(m_device->device(), ds_pool, 3, descriptor_sets);
vk::DestroyDescriptorPool(m_device->device(), ds_pool, NULL);
vk::FreeMemory(m_device->device(), VK_NULL_HANDLE, NULL);
m_errorMonitor->VerifyNotFound();
}
TEST_F(VkBestPracticesLayerTest, CommandBufferReset) {
TEST_DESCRIPTION("Test for validating usage of vkCreateCommandPool with COMMAND_BUFFER_RESET_BIT");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit,
"UNASSIGNED-BestPractices-vkCreateCommandPool-command-buffer-reset");
VkCommandPool command_pool;
VkCommandPoolCreateInfo pool_create_info{};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = m_device->graphics_queue_node_index_;
pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vk::CreateCommandPool(m_device->device(), &pool_create_info, nullptr, &command_pool);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, SimultaneousUse) {
TEST_DESCRIPTION("Test for validating usage of vkBeginCommandBuffer with SIMULTANEOUS_USE");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-vkBeginCommandBuffer-simultaneous-use");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBeginCommandBuffer-one-time-submit");
VkCommandBufferBeginInfo cmd_begin_info{};
cmd_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cmd_begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
vk::BeginCommandBuffer(m_commandBuffer->handle(), &cmd_begin_info);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, SmallAllocation) {
TEST_DESCRIPTION("Test for small memory allocations");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation");
// Find appropriate memory type for given reqs
VkMemoryPropertyFlags mem_props = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
VkPhysicalDeviceMemoryProperties dev_mem_props = m_device->phy().memory_properties();
uint32_t mem_type_index = 0;
for (mem_type_index = 0; mem_type_index < dev_mem_props.memoryTypeCount; ++mem_type_index) {
if (mem_props == (mem_props & dev_mem_props.memoryTypes[mem_type_index].propertyFlags)) break;
}
EXPECT_LT(mem_type_index, dev_mem_props.memoryTypeCount) << "Could not find a suitable memory type.";
const uint32_t kSmallAllocationSize = 1024;
VkMemoryAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = kSmallAllocationSize;
alloc_info.memoryTypeIndex = mem_type_index;
VkDeviceMemory memory;
vk::AllocateMemory(m_device->device(), &alloc_info, nullptr, &memory);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, SmallDedicatedAllocation) {
TEST_DESCRIPTION("Test for small dedicated memory allocations");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit,
"UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation");
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.extent = {64, 64, 1};
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.arrayLayers = 1;
image_info.mipLevels = 1;
// Create a small image with a dedicated allocation
VkImageObj image(m_device);
image.init_no_mem(*m_device, image_info);
vk_testing::DeviceMemory mem;
mem.init(*m_device, vk_testing::DeviceMemory::get_resource_alloc_info(*m_device, image.memory_requirements(),
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT));
vk::BindImageMemory(device(), image.handle(), mem.handle(), 0);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, MSImageRequiresMemory) {
TEST_DESCRIPTION("Test for MS image that requires memory");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit,
"UNASSIGNED-BestPractices-vkCreateRenderPass-image-requires-memory");
VkAttachmentDescription attachment{};
attachment.samples = VK_SAMPLE_COUNT_4_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
VkRenderPassCreateInfo rp_info{};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.attachmentCount = 1;
rp_info.pAttachments = &attachment;
VkRenderPass rp;
vk::CreateRenderPass(m_device->device(), &rp_info, nullptr, &rp);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, AttachmentShouldNotBeTransient) {
TEST_DESCRIPTION("Test for non-lazy multisampled images");
InitBestPracticesFramework();
InitState();
if (IsPlatform(kPixel2XL) || IsPlatform(kPixel3) || IsPlatform(kPixel3aXL) || IsPlatform(kShieldTV) || IsPlatform(kShieldTVb) ||
IsPlatform(kNexusPlayer)) {
printf("%s This test seems super-picky on Android platforms\n", kSkipPrefix);
return;
}
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit,
"UNASSIGNED-BestPractices-vkCreateFramebuffer-attachment-should-not-be-transient");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindImageMemory-non-lazy-transient-image");
VkAttachmentDescription attachment{};
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
VkRenderPassCreateInfo rp_info{};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.attachmentCount = 1;
rp_info.pAttachments = &attachment;
VkRenderPass rp = VK_NULL_HANDLE;
vk::CreateRenderPass(m_device->device(), &rp_info, nullptr, &rp);
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.extent = {1920, 1080, 1};
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.arrayLayers = 1;
image_info.mipLevels = 1;
VkImageObj image(m_device);
image.init(&image_info);
VkImageViewCreateInfo iv_info{};
iv_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
iv_info.format = VK_FORMAT_R8G8B8A8_UNORM;
iv_info.image = image.handle();
iv_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
iv_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
iv_info.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
VkImageView image_view = VK_NULL_HANDLE;
vk::CreateImageView(m_device->device(), &iv_info, nullptr, &image_view);
VkFramebufferCreateInfo fb_info{};
fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
fb_info.renderPass = rp;
fb_info.layers = 1;
fb_info.width = 1920;
fb_info.height = 1080;
fb_info.attachmentCount = 1;
fb_info.pAttachments = &image_view;
VkFramebuffer fb = VK_NULL_HANDLE;
vk::CreateFramebuffer(m_device->device(), &fb_info, nullptr, &fb);
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, TooManyInstancedVertexBuffers) {
TEST_DESCRIPTION("Test for too many instanced vertex buffers");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit,
"UNASSIGNED-BestPractices-vkCreateGraphicsPipelines-too-many-instanced-vertex-buffers");
// This test may also trigger the small allocation warnings
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation");
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
std::vector<VkVertexInputBindingDescription> bindings(2, VkVertexInputBindingDescription{});
std::vector<VkVertexInputAttributeDescription> attributes(2, VkVertexInputAttributeDescription{});
bindings[0].binding = 0;
bindings[0].stride = 4;
bindings[0].inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
attributes[0].binding = 0;
bindings[1].binding = 1;
bindings[1].stride = 8;
bindings[1].inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
attributes[1].binding = 1;
VkPipelineVertexInputStateCreateInfo vi_state_ci{};
vi_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vi_state_ci.vertexBindingDescriptionCount = static_cast<uint32_t>(bindings.size());
vi_state_ci.pVertexBindingDescriptions = bindings.data();
vi_state_ci.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributes.size());
vi_state_ci.pVertexAttributeDescriptions = attributes.data();
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.vi_ci_ = vi_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
m_errorMonitor->VerifyFound();
}
TEST_F(VkBestPracticesLayerTest, ClearAttachmentsAfterLoad) {
TEST_DESCRIPTION("Test for clearing attachments after load");
InitBestPracticesFramework();
InitState();
m_clear_via_load_op = false; // Force LOAD_OP_LOAD
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-vkCmdClearAttachments-clear-after-load");
// On tiled renderers, this can also trigger a warning about LOAD_OP_LOAD causing a readback
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdBeginRenderPass-attachment-needs-readback");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-DrawState-ClearCmdBeforeDraw");
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
VkClearAttachment color_attachment;
color_attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_attachment.clearValue.color.float32[0] = 1.0;
color_attachment.clearValue.color.float32[1] = 1.0;
color_attachment.clearValue.color.float32[2] = 1.0;
color_attachment.clearValue.color.float32[3] = 1.0;
color_attachment.colorAttachment = 0;
VkClearRect clear_rect = {{{0, 0}, {(uint32_t)m_width, (uint32_t)m_height}}, 0, 1};
vk::CmdClearAttachments(m_commandBuffer->handle(), 1, &color_attachment, 1, &clear_rect);
m_errorMonitor->VerifyFound();
}
// Tests for Arm-specific best practices
TEST_F(VkArmBestPracticesLayerTest, TooManySamples) {
TEST_DESCRIPTION("Test for multisampled images with too many samples");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateImage-too-large-sample-count");
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.extent = {1920, 1080, 1};
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
image_info.samples = VK_SAMPLE_COUNT_8_BIT;
image_info.arrayLayers = 1;
image_info.mipLevels = 1;
VkImage image = VK_NULL_HANDLE;
vk::CreateImage(m_device->device(), &image_info, nullptr, &image);
m_errorMonitor->VerifyFound();
if (image) {
vk::DestroyImage(m_device->device(), image, nullptr);
}
}
TEST_F(VkArmBestPracticesLayerTest, NonTransientMSImage) {
TEST_DESCRIPTION("Test for non-transient multisampled images");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateImage-non-transient-ms-image");
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.extent = {1920, 1080, 1};
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
image_info.samples = VK_SAMPLE_COUNT_4_BIT;
image_info.arrayLayers = 1;
image_info.mipLevels = 1;
VkImage image;
vk::CreateImage(m_device->device(), &image_info, nullptr, &image);
m_errorMonitor->VerifyFound();
}
TEST_F(VkArmBestPracticesLayerTest, SamplerCreation) {
TEST_DESCRIPTION("Test for various checks during sampler creation");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSampler-different-wrapping-modes");
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping");
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSampler-lod-bias");
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSampler-border-clamp-color");
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSampler-unnormalized-coordinates");
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSampler-anisotropy");
VkSamplerCreateInfo sampler_info{};
sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK;
sampler_info.minLod = 0.0f;
sampler_info.maxLod = 4.0f;
sampler_info.mipLodBias = 1.0f;
sampler_info.unnormalizedCoordinates = VK_TRUE;
sampler_info.anisotropyEnable = VK_TRUE;
sampler_info.maxAnisotropy = 4.0f;
VkSampler sampler = VK_NULL_HANDLE;
vk::CreateSampler(m_device->device(), &sampler_info, nullptr, &sampler);
m_errorMonitor->VerifyFound();
if (sampler) {
vk::DestroySampler(m_device->device(), sampler, nullptr);
}
}
TEST_F(VkArmBestPracticesLayerTest, MultisampledBlending) {
TEST_DESCRIPTION("Test for multisampled blending");
InitBestPracticesFramework();
InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreatePipelines-multisampled-blending");
VkAttachmentDescription attachment{};
attachment.samples = VK_SAMPLE_COUNT_4_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.format = VK_FORMAT_R16G16B16A16_SFLOAT;
VkAttachmentReference color_ref{};
color_ref.attachment = 0;
color_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_ref;
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
VkRenderPassCreateInfo rp_info{};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.attachmentCount = 1;
rp_info.pAttachments = &attachment;
rp_info.subpassCount = 1;
rp_info.pSubpasses = &subpass;
vk::CreateRenderPass(m_device->device(), &rp_info, nullptr, &m_renderPass);
m_renderPass_info = rp_info;
VkPipelineMultisampleStateCreateInfo pipe_ms_state_ci = {};
pipe_ms_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
pipe_ms_state_ci.rasterizationSamples = VK_SAMPLE_COUNT_4_BIT;
VkPipelineColorBlendAttachmentState blend_att = {};
blend_att.blendEnable = VK_TRUE;
blend_att.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo pipe_cb_state_ci = {};
pipe_cb_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
pipe_cb_state_ci.attachmentCount = 1;
pipe_cb_state_ci.pAttachments = &blend_att;
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.pipe_ms_state_ci_ = pipe_ms_state_ci;
pipe.cb_ci_ = pipe_cb_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
m_errorMonitor->VerifyFound();
}
TEST_F(VkArmBestPracticesLayerTest, AttachmentNeedsReadback) {
TEST_DESCRIPTION("Test for attachments that need readback");
InitBestPracticesFramework();
InitState();
m_clear_via_load_op = false; // Force LOAD_OP_LOAD
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCmdBeginRenderPass-attachment-needs-readback");
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_errorMonitor->VerifyFound();
}
TEST_F(VkArmBestPracticesLayerTest, ManySmallIndexedDrawcalls) {
InitBestPracticesFramework();
InitState();
if (IsPlatform(kNexusPlayer) || IsPlatform(kShieldTV) || IsPlatform(kShieldTVb)) {
return;
}
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCmdDrawIndexed-many-small-indexed-drawcalls");
// This test may also trigger other warnings
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation");
m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation");
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkPipelineMultisampleStateCreateInfo pipe_ms_state_ci = {};
pipe_ms_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
pipe_ms_state_ci.pNext = NULL;
pipe_ms_state_ci.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
pipe_ms_state_ci.sampleShadingEnable = 0;
pipe_ms_state_ci.minSampleShading = 1.0;
pipe_ms_state_ci.pSampleMask = NULL;
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.pipe_ms_state_ci_ = pipe_ms_state_ci;
pipe.InitState();
pipe.CreateGraphicsPipeline();
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
for (int i = 0; i < 10; i++) {
m_commandBuffer->DrawIndexed(3, 1, 0, 0, 0);
}
m_errorMonitor->VerifyFound();
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
}
TEST_F(VkArmBestPracticesLayerTest, SuboptimalDescriptorReuseTest) {
TEST_DESCRIPTION("Test for validation warnings of potentially suboptimal re-use of descriptor set allocations");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
VkDescriptorPoolSize ds_type_count = {};
ds_type_count.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
ds_type_count.descriptorCount = 3;
VkDescriptorPoolCreateInfo ds_pool_ci = {};
ds_pool_ci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
ds_pool_ci.pNext = NULL;
ds_pool_ci.maxSets = 6;
ds_pool_ci.poolSizeCount = 1;
ds_pool_ci.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
ds_pool_ci.pPoolSizes = &ds_type_count;
VkDescriptorPool ds_pool;
VkResult err = vk::CreateDescriptorPool(m_device->device(), &ds_pool_ci, NULL, &ds_pool);
ASSERT_VK_SUCCESS(err);
VkDescriptorSetLayoutBinding ds_binding = {};
ds_binding.binding = 0;
ds_binding.descriptorCount = 1;
ds_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
VkDescriptorSetLayoutCreateInfo ds_layout_info = {};
ds_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
ds_layout_info.bindingCount = 1;
ds_layout_info.pBindings = &ds_binding;
VkDescriptorSetLayout ds_layout;
err = vk::CreateDescriptorSetLayout(m_device->device(), &ds_layout_info, nullptr, &ds_layout);
ASSERT_VK_SUCCESS(err);
auto ds_layouts = std::vector<VkDescriptorSetLayout>(ds_pool_ci.maxSets, ds_layout);
std::vector<VkDescriptorSet> descriptor_sets = {};
descriptor_sets.resize(ds_layouts.size());
// allocate N/2 descriptor sets
VkDescriptorSetAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorPool = ds_pool;
alloc_info.descriptorSetCount = descriptor_sets.size() / 2;
alloc_info.pSetLayouts = ds_layouts.data();
err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, descriptor_sets.data());
ASSERT_VK_SUCCESS(err);
// free one descriptor set
VkDescriptorSet* ds = descriptor_sets.data();
err = vk::FreeDescriptorSets(m_device->device(), ds_pool, 1, ds);
// the previous allocate and free should not cause any warning
ASSERT_VK_SUCCESS(err);
m_errorMonitor->VerifyNotFound();
// allocate the previously freed descriptor set
alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorPool = ds_pool;
alloc_info.descriptorSetCount = 1;
alloc_info.pSetLayouts = ds_layouts.data();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkAllocateDescriptorSets-suboptimal-reuse");
err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, ds);
// this should create a validation warning, in addition to the appropriate warning message
m_errorMonitor->VerifyFound();
// allocate the remaining descriptor sets (N - (N/2))
alloc_info.descriptorSetCount = descriptor_sets.size() - (descriptor_sets.size() / 2);
err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, ds);
// this should create no validation warnings
m_errorMonitor->VerifyNotFound();
}
TEST_F(VkArmBestPracticesLayerTest, SparseIndexBufferTest) {
TEST_DESCRIPTION(
"Test for appropriate warnings to be thrown when recording an indexed draw call with sparse/non-sparse index buffers.");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
if (IsPlatform(kMockICD) || DeviceSimulation()) {
printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix);
return;
}
// create a non-sparse index buffer
std::vector<uint16_t> nonsparse_indices;
nonsparse_indices.resize(128);
for (unsigned i = 0; i < nonsparse_indices.size(); i++) {
nonsparse_indices[i] = i;
}
std::vector<uint16_t> sparse_indices = nonsparse_indices;
// The buffer (0, 1, 2, ..., n) is completely un-sparse. However, if n < 0xFFFF, by adding 0xFFFF at the end, we
// should trigger a warning due to loading all the indices in the range 0 to 0xFFFF, despite indices in the range
// (n+1) to (0xFFFF - 1) not being used.
sparse_indices[sparse_indices.size() - 1] = 0xFFFF;
VkConstantBufferObj nonsparse_ibo(m_device, nonsparse_indices.size() * sizeof(uint16_t), nonsparse_indices.data(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
VkConstantBufferObj sparse_ibo(m_device, sparse_indices.size() * sizeof(uint16_t), sparse_indices.data(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.InitState();
pipe.ia_ci_.primitiveRestartEnable = VK_FALSE;
pipe.CreateGraphicsPipeline();
// pipeline with primitive restarts enabled
CreatePipelineHelper pr_pipe(*this);
pr_pipe.InitInfo();
pr_pipe.InitState();
pr_pipe.ia_ci_.primitiveRestartEnable = VK_TRUE;
pr_pipe.CreateGraphicsPipeline();
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
auto test_pipelines = [&](VkConstantBufferObj& ibo, size_t index_count, bool expect_error) -> void {
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
m_commandBuffer->BindIndexBuffer(&ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16);
m_errorMonitor->VerifyNotFound();
// the validation layer will only be able to analyse mapped memory, it's too expensive otherwise to do in the layer itself
ibo.memory().map();
if (expect_error)
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCmdDrawIndexed-sparse-index-buffer");
m_commandBuffer->DrawIndexed(index_count, 0, 0, 0, 0);
m_errorMonitor->VerifyFound();
ibo.memory().unmap();
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pr_pipe.pipeline_);
m_commandBuffer->BindIndexBuffer(&ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16);
m_errorMonitor->VerifyNotFound();
ibo.memory().map();
if (expect_error)
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCmdDrawIndexed-sparse-index-buffer");
m_commandBuffer->DrawIndexed(index_count, 0, 0, 0, 0);
m_errorMonitor->VerifyFound();
ibo.memory().unmap();
};
// our non-sparse indices should not trigger a warning for both pipelines in this case
test_pipelines(nonsparse_ibo, nonsparse_indices.size(), false);
// our sparse indices should trigger warnings for both pipelines in this case
test_pipelines(sparse_ibo, sparse_indices.size(), true);
}
TEST_F(VkArmBestPracticesLayerTest, PostTransformVertexCacheThrashingIndicesTest) {
TEST_DESCRIPTION(
"Test for appropriate warnings to be thrown when recording an indexed draw call where the indices thrash the "
"post-transform vertex cache.");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
if (IsPlatform(kMockICD) || DeviceSimulation()) {
printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix);
return;
}
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.InitState();
pipe.CreateGraphicsPipeline();
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_);
std::vector<uint16_t> worst_indices;
worst_indices.resize(128 * 16);
for (size_t i = 0; i < 16; i++) {
for (size_t j = 0; j < 128; j++) {
// worst case index buffer sequence for re-use
// (0, 1, 2, 3, ..., 127, 0, 1, 2, 3, ..., 127, 0, 1, 2, ...<x16>)
worst_indices[j + i * 128] = j;
}
}
std::vector<uint16_t> best_indices;
best_indices.resize(128 * 16);
for (size_t i = 0; i < 16; i++) {
for (size_t j = 0; j < 128; j++) {
// best case index buffer sequence for re-use
// (0, 0, 0, ...<x16>, 1, 1, 1, ...<x16>, 2, 2, 2, ...<x16> , ..., 127)
best_indices[i + j * 16] = j;
}
}
// make sure the worst-case indices throw a warning
VkConstantBufferObj worst_ibo(m_device, worst_indices.size() * sizeof(uint16_t), worst_indices.data(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
m_commandBuffer->BindIndexBuffer(&worst_ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16);
m_errorMonitor->VerifyNotFound();
// the validation layer will only be able to analyse mapped memory, it's too expensive otherwise to do in the layer itself
worst_ibo.memory().map();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCmdDrawIndexed-post-transform-cache-thrashing");
m_commandBuffer->DrawIndexed(worst_indices.size(), 0, 0, 0, 0);
m_errorMonitor->VerifyFound();
worst_ibo.memory().unmap();
// make sure that the best-case indices don't throw a warning
VkConstantBufferObj best_ibo(m_device, best_indices.size() * sizeof(uint16_t), best_indices.data(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
m_commandBuffer->BindIndexBuffer(&best_ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16);
m_errorMonitor->VerifyNotFound();
best_ibo.memory().map();
m_commandBuffer->DrawIndexed(best_indices.size(), 0, 0, 0, 0);
m_errorMonitor->VerifyNotFound();
best_ibo.memory().unmap();
}
TEST_F(VkBestPracticesLayerTest, TripleBufferingTest) {
TEST_DESCRIPTION("Test for usage of triple buffering");
AddSurfaceInstanceExtension();
InitBestPracticesFramework();
AddSwapchainDeviceExtension();
InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSwapchainKHR-suboptimal-swapchain-image-count");
InitSurface();
VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
VkSurfaceTransformFlagBitsKHR preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
VkSurfaceCapabilitiesKHR capabilities;
vk::GetPhysicalDeviceSurfaceCapabilitiesKHR(m_device->phy().handle(), m_surface, &capabilities);
uint32_t format_count;
vk::GetPhysicalDeviceSurfaceFormatsKHR(m_device->phy().handle(), m_surface, &format_count, nullptr);
vector<VkSurfaceFormatKHR> formats;
if (format_count != 0) {
formats.resize(format_count);
vk::GetPhysicalDeviceSurfaceFormatsKHR(m_device->phy().handle(), m_surface, &format_count, formats.data());
}
uint32_t present_mode_count;
vk::GetPhysicalDeviceSurfacePresentModesKHR(m_device->phy().handle(), m_surface, &present_mode_count, nullptr);
vector<VkPresentModeKHR> present_modes;
if (present_mode_count != 0) {
present_modes.resize(present_mode_count);
vk::GetPhysicalDeviceSurfacePresentModesKHR(m_device->phy().handle(), m_surface, &present_mode_count, present_modes.data());
}
VkSwapchainCreateInfoKHR swapchain_create_info = {};
swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchain_create_info.pNext = 0;
swapchain_create_info.surface = m_surface;
swapchain_create_info.minImageCount = 2;
swapchain_create_info.imageFormat = formats[0].format;
swapchain_create_info.imageColorSpace = formats[0].colorSpace;
swapchain_create_info.imageExtent = {capabilities.minImageExtent.width, capabilities.minImageExtent.height};
swapchain_create_info.imageArrayLayers = 1;
swapchain_create_info.imageUsage = imageUsage;
swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchain_create_info.preTransform = preTransform;
#ifdef VK_USE_PLATFORM_ANDROID_KHR
swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
#else
swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
#endif
swapchain_create_info.presentMode = present_modes[0];
swapchain_create_info.clipped = VK_FALSE;
swapchain_create_info.oldSwapchain = 0;
VkResult err = vk::CreateSwapchainKHR(device(), &swapchain_create_info, nullptr, &m_swapchain);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSwapchainKHR-suboptimal-swapchain-image-count");
swapchain_create_info.minImageCount = 3;
err = vk::CreateSwapchainKHR(device(), &swapchain_create_info, nullptr, &m_swapchain);
m_errorMonitor->VerifyNotFound();
ASSERT_VK_SUCCESS(err)
DestroySwapchain();
}
TEST_F(VkArmBestPracticesLayerTest, PresentModeTest) {
TEST_DESCRIPTION("Test for usage of Presentation Modes");
AddSurfaceInstanceExtension();
InitBestPracticesFramework();
AddSwapchainDeviceExtension();
InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo");
InitSurface();
VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
VkSurfaceTransformFlagBitsKHR preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
VkSurfaceCapabilitiesKHR capabilities;
vk::GetPhysicalDeviceSurfaceCapabilitiesKHR(m_device->phy().handle(), m_surface, &capabilities);
uint32_t format_count;
vk::GetPhysicalDeviceSurfaceFormatsKHR(m_device->phy().handle(), m_surface, &format_count, nullptr);
vector<VkSurfaceFormatKHR> formats;
if (format_count != 0) {
formats.resize(format_count);
vk::GetPhysicalDeviceSurfaceFormatsKHR(m_device->phy().handle(), m_surface, &format_count, formats.data());
}
uint32_t present_mode_count;
vk::GetPhysicalDeviceSurfacePresentModesKHR(m_device->phy().handle(), m_surface, &present_mode_count, nullptr);
vector<VkPresentModeKHR> present_modes;
if (present_mode_count != 0) {
present_modes.resize(present_mode_count);
vk::GetPhysicalDeviceSurfacePresentModesKHR(m_device->phy().handle(), m_surface, &present_mode_count, present_modes.data());
}
VkSwapchainCreateInfoKHR swapchain_create_info = {};
swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchain_create_info.pNext = 0;
swapchain_create_info.surface = m_surface;
swapchain_create_info.minImageCount = capabilities.minImageCount;
swapchain_create_info.imageFormat = formats[0].format;
swapchain_create_info.imageColorSpace = formats[0].colorSpace;
swapchain_create_info.imageExtent = {capabilities.minImageExtent.width, capabilities.minImageExtent.height};
swapchain_create_info.imageArrayLayers = 1;
swapchain_create_info.imageUsage = imageUsage;
swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchain_create_info.preTransform = preTransform;
swapchain_create_info.clipped = VK_FALSE;
swapchain_create_info.oldSwapchain = 0;
#ifdef VK_USE_PLATFORM_ANDROID_KHR
swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
#else
swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
#endif
if (present_modes.size() <= 1) {
printf("TEST SKIPPED: Only %i presentation mode is available!", int(present_modes.size()));
return;
}
for (size_t i = 0; i < present_modes.size(); i++) {
if (present_modes[i] != VK_PRESENT_MODE_FIFO_KHR) {
swapchain_create_info.presentMode = present_modes[i];
break;
}
}
VkResult err = vk::CreateSwapchainKHR(device(), &swapchain_create_info, nullptr, &m_swapchain);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo");
swapchain_create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
err = vk::CreateSwapchainKHR(device(), &swapchain_create_info, nullptr, &m_swapchain);
m_errorMonitor->VerifyNotFound();
ASSERT_VK_SUCCESS(err)
DestroySwapchain();
}
TEST_F(VkArmBestPracticesLayerTest, PipelineDepthBiasZeroTest) {
TEST_DESCRIPTION("Test for unnecessary rasterization due to using 0 for depthBiasConstantFactor and depthBiasSlopeFactor");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitViewport());
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
CreatePipelineHelper pipe(*this);
pipe.InitInfo();
pipe.rs_state_ci_.depthBiasEnable = VK_TRUE;
pipe.rs_state_ci_.depthBiasConstantFactor = 0.0f;
pipe.rs_state_ci_.depthBiasSlopeFactor = 0.0f;
pipe.InitState();
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreatePipelines-depthbias-zero");
pipe.CreateGraphicsPipeline();
m_errorMonitor->VerifyFound();
pipe.rs_state_ci_.depthBiasEnable = VK_FALSE;
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreatePipelines-depthbias-zero");
pipe.CreateGraphicsPipeline();
m_errorMonitor->VerifyNotFound();
}
TEST_F(VkArmBestPracticesLayerTest, RobustBufferAccessTest) {
TEST_DESCRIPTION("Test for appropriate warnings to be thrown when robustBufferAccess is enabled.");
InitBestPracticesFramework();
VkDevice local_device;
VkDeviceQueueCreateInfo queue_info = {};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = nullptr;
queue_info.queueFamilyIndex = 0;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = nullptr;
VkDeviceCreateInfo dev_info = {};
dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dev_info.pNext = nullptr;
dev_info.queueCreateInfoCount = 1;
dev_info.pQueueCreateInfos = &queue_info;
dev_info.enabledLayerCount = 0;
dev_info.ppEnabledLayerNames = nullptr;
dev_info.enabledExtensionCount = m_device_extension_names.size();
dev_info.ppEnabledExtensionNames = m_device_extension_names.data();
VkPhysicalDeviceFeatures supported_features;
vk::GetPhysicalDeviceFeatures(this->gpu(), &supported_features);
if (supported_features.robustBufferAccess) {
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-BestPractices-vkCreateDevice-RobustBufferAccess");
VkPhysicalDeviceFeatures device_features = {};
device_features.robustBufferAccess = VK_TRUE;
dev_info.pEnabledFeatures = &device_features;
vk::CreateDevice(this->gpu(), &dev_info, nullptr, &local_device);
m_errorMonitor->VerifyFound();
} else {
printf("%s robustBufferAccess is not available, skipping test\n", kSkipPrefix);
return;
}
}
TEST_F(VkArmBestPracticesLayerTest, DepthPrePassUsage) {
InitBestPracticesFramework();
InitState();
if (IsPlatform(kNexusPlayer)) {
printf("%s This test crashes on the NexusPlayer platform\n", kSkipPrefix);
return;
}
InitRenderTarget();
VkAttachmentDescription attachment{};
attachment.samples = VK_SAMPLE_COUNT_4_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkRenderPassCreateInfo rp_info{};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.attachmentCount = 1;
rp_info.pAttachments = &attachment;
rp_info.pNext = nullptr;
VkRenderPass rp = VK_NULL_HANDLE;
vk::CreateRenderPass(m_device->device(), &rp_info, nullptr, &rp);
// set up pipelines
VkPipelineColorBlendAttachmentState color_write_off = {};
VkPipelineColorBlendAttachmentState color_write_on = {};
color_write_on.colorWriteMask = 0xF;
VkPipelineColorBlendStateCreateInfo cb_depth_only_ci = {};
cb_depth_only_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
cb_depth_only_ci.attachmentCount = 1;
cb_depth_only_ci.pAttachments = &color_write_off;
VkPipelineColorBlendStateCreateInfo cb_depth_equal_ci = {};
cb_depth_equal_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
cb_depth_equal_ci.attachmentCount = 1;
cb_depth_equal_ci.pAttachments = &color_write_on;
VkPipelineDepthStencilStateCreateInfo ds_depth_only_ci = {};
ds_depth_only_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds_depth_only_ci.depthTestEnable = VK_TRUE;
ds_depth_only_ci.depthWriteEnable = VK_TRUE;
ds_depth_only_ci.depthCompareOp = VK_COMPARE_OP_LESS;
VkPipelineDepthStencilStateCreateInfo ds_depth_equal_ci = {};
ds_depth_equal_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds_depth_equal_ci.depthTestEnable = VK_TRUE;
ds_depth_equal_ci.depthWriteEnable = VK_FALSE;
ds_depth_equal_ci.depthCompareOp = VK_COMPARE_OP_EQUAL;
CreatePipelineHelper pipe_depth_only(*this);
pipe_depth_only.InitInfo();
pipe_depth_only.gp_ci_.pColorBlendState = &cb_depth_only_ci;
pipe_depth_only.gp_ci_.pDepthStencilState = &ds_depth_only_ci;
pipe_depth_only.InitState();
pipe_depth_only.CreateGraphicsPipeline();
CreatePipelineHelper pipe_depth_equal(*this);
pipe_depth_equal.InitInfo();
pipe_depth_equal.gp_ci_.pColorBlendState = &cb_depth_equal_ci;
pipe_depth_equal.gp_ci_.pDepthStencilState = &ds_depth_equal_ci;
pipe_depth_equal.InitState();
pipe_depth_equal.CreateGraphicsPipeline();
// create a simple index buffer
std::vector<uint32_t> indices = {};
indices.resize(3);
VkConstantBufferObj ibo(m_device, sizeof(uint32_t) * indices.size(), indices.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
m_commandBuffer->begin();
m_commandBuffer->BindIndexBuffer(&ibo, 0, VK_INDEX_TYPE_UINT32);
// record a command buffer which doesn't use enough depth pre-passes or geometry to matter
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_only.pipeline_);
for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 10, 0, 0, 0);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_equal.pipeline_);
for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 10, 0, 0, 0);
m_commandBuffer->EndRenderPass();
m_errorMonitor->VerifyNotFound();
// record a command buffer which records a significant number of depth pre-passes
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit,
"UNASSIGNED-BestPractices-vkCmdEndRenderPass-depth-pre-pass-usage");
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_only.pipeline_);
for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 1000, 0, 0, 0);
vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_equal.pipeline_);
for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 1000, 0, 0, 0);
m_commandBuffer->EndRenderPass();
m_errorMonitor->VerifyFound();
m_commandBuffer->end();
}
| 43.493209 | 132 | 0.744178 | [
"geometry",
"vector",
"transform"
] |
f6946fa75df65d4efafe86d52e1c21609a50aa57 | 3,034 | hpp | C++ | src/modules/fpn/fpn_proposal_layer.m.hpp | xyt2008/frcnn | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | [
"BSD-2-Clause"
] | 198 | 2018-01-07T13:44:29.000Z | 2022-03-21T12:06:16.000Z | src/modules/fpn/fpn_proposal_layer.m.hpp | xyt2008/frcnn | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | [
"BSD-2-Clause"
] | 18 | 2018-02-01T13:24:53.000Z | 2021-04-26T10:51:47.000Z | src/modules/fpn/fpn_proposal_layer.m.hpp | xyt2008/frcnn | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | [
"BSD-2-Clause"
] | 82 | 2018-01-06T14:21:43.000Z | 2022-02-16T09:39:58.000Z | // ------------------------------------------------------------------
// Xuanyi . Refer to Dong Jian
// 2016/03/31
// ------------------------------------------------------------------
#ifndef CAFFE_FPN_PROPOSAL_LAYER_HPP_
#define CAFFE_FPN_PROPOSAL_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
namespace Frcnn {
/*************************************************
FrcnnProposalLayer
Outputs object detection proposals by applying estimated bounding-box
transformations to a set of regular boxes (called "anchors").
bottom: 'rpn_cls_prob_reshape'
bottom: 'rpn_bbox_pred'
bottom: 'im_info'
top: 'rpn_rois'
**************************************************/
template <typename Dtype>
class FPNProposalLayer : public Layer<Dtype> {
public:
explicit FPNProposalLayer(const LayerParameter& param)
#ifndef CPU_ONLY //fyk: fix problem of runtest
: Layer<Dtype>(param), anchors_(nullptr), transform_bbox_(nullptr), mask_(nullptr), selected_flags_(nullptr), gpu_keep_indices_(nullptr) {}
#else
: Layer<Dtype>(param) {}
#endif
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top){};
virtual inline const char* type() const { return "FPNProposal"; }
virtual inline int MinBottomBlobs() const { return 11; }// include level pyramid.
virtual inline int MaxBottomBlobs() const { return 11; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 6; }
#ifndef CPU_ONLY
virtual ~FPNProposalLayer() {
if (this->anchors_) {
CUDA_CHECK(cudaFree(this->anchors_));
}
if (this->transform_bbox_) {
CUDA_CHECK(cudaFree(this->transform_bbox_));
}
if (this->mask_) {
CUDA_CHECK(cudaFree(this->mask_));
}
if (this->selected_flags_) {
CUDA_CHECK(cudaFree(this->selected_flags_));
}
if (this->gpu_keep_indices_) {
CUDA_CHECK(cudaFree(this->gpu_keep_indices_));
}
}
#endif
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
#ifndef CPU_ONLY
// CUDA CU
float* anchors_;
float* transform_bbox_;
unsigned long long *mask_;
int *selected_flags_;
int *gpu_keep_indices_;
#endif
std::vector<int> _feat_strides;
std::vector<int> _anchor_scales;
std::vector<float> _anchor_ratios;
};
} // namespace frcnn
} // namespace caffe
#endif // CAFFE_FPN_PROPOSAL_LAYER_HPP_
| 31.604167 | 145 | 0.653922 | [
"object",
"vector"
] |
f6964b3ba4822b5759f5105768acffac1b939038 | 4,704 | hpp | C++ | core/algorithms/partitioning/slack_view.hpp | sjkelly/LSOracle | 21688c5d542740dfc8577349fa615ee655acd92c | [
"MIT"
] | null | null | null | core/algorithms/partitioning/slack_view.hpp | sjkelly/LSOracle | 21688c5d542740dfc8577349fa615ee655acd92c | [
"MIT"
] | 1 | 2021-07-26T22:09:49.000Z | 2021-07-26T22:09:49.000Z | core/algorithms/partitioning/slack_view.hpp | sjkelly/LSOracle | 21688c5d542740dfc8577349fa615ee655acd92c | [
"MIT"
] | 2 | 2021-07-26T14:46:51.000Z | 2021-11-09T11:32:09.000Z | /* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* 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.
*/
#pragma once
#include <algorithm>
#include <cstdint>
#include <unordered_map>
#include <vector>
#include <set>
#include <unordered_set>
#include <cassert>
#include <limits>
#include <mockturtle/traits.hpp>
#include <mockturtle/networks/detail/foreach.hpp>
#include <mockturtle/views/fanout_view.hpp>
namespace oracle
{
template<typename Ntk>
class slack_view : public Ntk {
public:
using storage = typename Ntk::storage;
using node = typename Ntk::node;
using signal = typename Ntk::signal;
public:
slack_view(){}
explicit slack_view( Ntk const& ntk )
: Ntk( ntk ), _arr( ntk ), _req_arr( ntk )
{
static_assert( mockturtle::is_network_type_v<Ntk>, "Ntk is not a network type" );
static_assert( mockturtle::has_set_visited_v<Ntk>, "Ntk does not implement the set_visited method" );
static_assert( mockturtle::has_visited_v<Ntk>, "Ntk does not implement the visited method" );
static_assert( mockturtle::has_get_node_v<Ntk>, "Ntk does not implement the get_node method" );
static_assert( mockturtle::has_get_constant_v<Ntk>, "Ntk does not implement the get_constant method" );
static_assert( mockturtle::has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" );
static_assert( mockturtle::has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" );
// set up for slack critical path calculation
mockturtle::depth_view ntk_depth{ntk};
ntk.foreach_node([&](auto node){
_arr[node] = ntk_depth.level(node);
if(ntk.is_po(node)){
if(_arr[node] > dmax){
dmax = _arr[node];
rmax = _arr[node];
}
}
});
get_required_arrival(ntk);
ntk.foreach_po([&](auto po){
_req_arr[ntk.get_node(po)] = rmax;
});
ntk.foreach_node([&](auto node){
int curr_slack = slack(node);
if(curr_slack > max_slack)
max_slack = curr_slack;
});
}
bool is_critical_path( node curr_node ) {
return slack(curr_node) == 0;
}
int slack( node curr_node ){
return _req_arr[curr_node] - _arr[curr_node];
}
int get_max_slack(){
return max_slack;
}
std::vector<node> get_critical_path( Ntk const& ntk ){
std::vector<node> crit_path;
ntk.foreach_node( [&]( auto curr_node ){
if(is_critical_path(curr_node)){
crit_path.push_back(curr_node);
}
});
return crit_path;
}
private:
void get_required_arrival( Ntk const& ntk ){
std::map<node, int> level;
ntk.foreach_node([&](auto node){
level[node] = 0;
});
mockturtle::topo_view top_view{ntk};
mockturtle::fanout_view fanout{ntk};
std::vector<node> top_nodes = top_view.get_node_vec();
std::reverse(top_nodes.begin(), top_nodes.end());
for(int i = 0; i < top_nodes.size(); i++){
node curr_node = top_nodes.at(i);
fanout.foreach_fanout(curr_node, [&](const auto& p){
if(level[curr_node] < level[p] + 1)
level[curr_node] = level[p] + 1;
});
_req_arr[curr_node] = dmax - level[curr_node];
}
}
mockturtle::node_map<uint32_t, Ntk> _req_arr;
mockturtle::node_map<uint32_t, Ntk> _arr;
int dmax = 0;
int rmax = std::numeric_limits<int>::max();
int max_slack = 0;
};
} /* namespace oracle */ | 32.441379 | 111 | 0.642219 | [
"vector"
] |
f69a84deda99df75dee19fac9dcf9ef7927e9d3e | 26,106 | cpp | C++ | apps/Analysis.cpp | MaftyNaveyuErin/Analysis | 1d1870befde835baf6efb4fcaec292ee536d13f8 | [
"MIT"
] | null | null | null | apps/Analysis.cpp | MaftyNaveyuErin/Analysis | 1d1870befde835baf6efb4fcaec292ee536d13f8 | [
"MIT"
] | 1 | 2021-08-04T08:20:00.000Z | 2021-08-04T08:20:00.000Z | apps/Analysis.cpp | MaftyNaveyuErin/Analysis | 1d1870befde835baf6efb4fcaec292ee536d13f8 | [
"MIT"
] | null | null | null | #include "CLI/CLI.hpp"
#include "Channel.hpp"
#include "Event.hpp"
#include "TCanvas.h"
#include "TFile.h"
#include "TH1F.h"
#include "TROOT.h"
#include "TSpectrum.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TPaveLabel.h"
#include "TStyle.h"
#include "TLine.h"
#include "TSystemDirectory.h"
#include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <vector>
#include <filesystem>
#include <limits>
namespace fs = std::filesystem;
#include "fmt/color.h"
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h>
#elif defined(__linux__)
#include <sys/ioctl.h>
#endif // Windows/Linux
void Clear()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
void get_terminal_size(int& width, int& height) {
#if defined(_WIN32)
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
width = (int)(csbi.dwSize.X);
height = (int)(csbi.dwSize.Y);
#elif defined(__linux__)
struct winsize w;
ioctl(fileno(stdout), TIOCGWINSZ, &w);
width = (int)(w.ws_col);
height = (int)(w.ws_row);
#endif // Windows/Linux
}
int NbrEventToProcess(int& nbrEvents, const Long64_t& nentries)
{
if(nbrEvents == 0) return nentries;
else if(nbrEvents > nentries)
{
std::cout << "WARNING : You ask to process " << nbrEvents << " but this run only have " << nentries << " !!!";
return nbrEvents = nentries;
}
else
return nbrEvents;
}
class PositiveNegative
{
public:
PositiveNegative() {}
PositiveNegative(const std::string& PN) { Parse(PN); }
bool IsPositiveSignal() { return m_positive; }
std::string asString()
{
if(m_positive) return "POSITIVE";
else
return "NEGATIVE";
}
private:
void Parse(const std::string& PN)
{
if(PN == "Positive" || PN == "POSITIVE" || PN == "P" || PN == "+") m_positive = true;
else if(PN == "Negative" || PN == "NEGATIVE" || PN == "N" || PN == "-")
m_positive = false;
else
{
std::cout << "BAD argument !!!" << std::endl;
std::exit(-5);
}
}
bool m_positive{false};
};
class channel
{
public:
channel(const int& chn, const std::string& PN): m_channelNumber(chn), m_PN(PN) {}
channel(){};
int getChannelNumber() { return m_channelNumber; }
bool isPositive() { return m_PN.IsPositiveSignal(); }
bool isNegative() { return !m_PN.IsPositiveSignal(); }
std::string PNasString() { return m_PN.asString(); }
int getPolarity()
{
if(isPositive()) return 1;
else return -1;
}
private:
int m_channelNumber{-1};
PositiveNegative m_PN;
};
class Channels
{
public:
std::size_t getNumberOfChannelActivated() { return m_Channel.size(); }
void activateChannel(const int& chn, const std::string& PN) { m_Channel.emplace(chn, channel(chn, PN)); }
void print()
{
std::cout << "Channels ENABLED for the analysis : \n";
for(std::map<int, channel>::iterator it = m_Channel.begin(); it != m_Channel.end(); ++it)
{ std::cout << "\t--> Channel " << it->first << " is declared to have " << it->second.PNasString() << " signal" << std::endl; }
}
bool DontAnalyseIt(const int& channel)
{
if(m_Channel.find(channel) == m_Channel.end()) return true;
else
return false;
}
bool ShouldBePositive(const int& ch) { return m_Channel[ch].isPositive(); }
int getPolarity(const int& ch) { return m_Channel[ch].getPolarity(); }
std::map<int, channel> getChannels()
{
return m_Channel;
}
private:
std::map<int, channel> m_Channel;
};
TH1D CreateAndFillWaveform(const int& eventNbr, const Channel& channel, const std::string& name = "", const std::string title = "")
{
std::string my_name = name + " channel " + std::to_string(int(channel.Number));
std::string my_title = title + " channel " + std::to_string(int(channel.Number));
TH1D th1(my_title.c_str(), my_name.c_str(), channel.Data.size(), 0, channel.Data.size());
for(std::size_t i = 0; i != channel.Data.size(); ++i)
{th1.Fill(i, channel.Data[i]);}
// auto result = std::minmax_element(channel.Data.begin(), channel.Data.end());
// std::pair<double, double> minmax((*result.first), (*result.second));
// th1.GetYaxis()->SetRangeUser((minmax.first - ((minmax.second - minmax.first))*0.05 / 100.0), (minmax.second + ((minmax.second - minmax.first))*0.05 / 100.0));
return std::move(th1);
}
void SupressBaseLine(Channel& channel)
{
double min{std::numeric_limits<double>::max()};
double max{std::numeric_limits<double>::min()};
double meanwindows{0};
int bin{0};
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
bin++;
meanwindows += channel.Data[j];
}
meanwindows/=bin;
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
channel.Data[j]-=meanwindows;
}
}
std::pair<std::pair<double,int>,std::pair<double,int>> getMinMax(const Channel& channel,const int& begin=-1,const int& end=-1)
{
int tick_max{0};
int tick_min{0};
double min{std::numeric_limits<double>::max()};
double max{std::numeric_limits<double>::min()};
std::size_t begin_{0};
std::size_t end_{channel.Data.size()};
if(begin>0) begin_=begin;
if(end!=-1||end<=channel.Data.size()) end_= end;
for(std::size_t j = begin_; j != end_; ++j)
{
if(channel.Data[j]>max)
{
max=channel.Data[j];
tick_max=j;
}
else if(channel.Data[j]<min)
{
min=channel.Data[j];
tick_min=j;
}
}
return std::pair<std::pair<double,int>,std::pair<double,int>>(std::pair<double,int>(min,tick_min),std::pair<double,int>(max,tick_max));
}
double getAbsMax(const Channel& channel)
{
double max{std::numeric_limits<double>::min()};
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
if(std::fabs(channel.Data[j])>max) max=std::fabs(channel.Data[j]);
}
return max;
}
void Normalise(Channel& channel,const double& max)
{
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
channel.Data[j]=channel.Data[j]/max;
}
}
std::pair<std::pair<double, double>, std::pair<double, double>> MeanSTD(const Channel& channel, const std::pair<double, double>& window_signal = std::pair<double, double>{99999999, -999999},
const std::pair<double, double>& window_noise = std::pair<double, double>{99999999, -999999})
{
double meanwindows{0};
double sigmawindows{0};
int binusedwindows{0};
double meannoise{0};
double sigmanoise{0};
int binusednoise{0};
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
////////////////////////////////
if(j >= window_noise.first && j <= window_noise.second)
{
binusednoise++;
meannoise += channel.Data[j];
}
if(j >= window_signal.first && j <= window_signal.second)
{
binusedwindows++;
meanwindows += channel.Data[j];
}
}
meannoise /= binusednoise;
meanwindows /= binusedwindows;
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
////////////////////////////////
if(j >= window_noise.first && j <= window_noise.second)
{
sigmanoise += (channel.Data[j] - meannoise) * (channel.Data[j] - meannoise);
}
if(j >= window_signal.first && j <= window_signal.second)
{
sigmawindows += (channel.Data[j] - meanwindows) * (channel.Data[j] - meanwindows);
}
}
sigmanoise = std::sqrt(sigmanoise / (binusednoise-1));
sigmawindows = std::sqrt(sigmawindows / (binusedwindows-1));
std::pair<double, double> noise(meannoise, sigmanoise);
std::pair<double, double> signal(meanwindows, sigmawindows);
return std::pair<std::pair<double, double>, std::pair<double, double>>(noise, signal);
}
class Chamber
{
public:
void activateChannel(const int& chn, const std::string& PN) { m_Channels.activateChannel(chn, PN); }
double getEfficiency() { return m_NumberFired * 1.0 / m_Total; }
double getMultiplicity() { return m_TotalHit * 1.0 / m_NumberFired; }
private:
int m_TotalHit{0};
int m_NumberFired{0};
int m_Total{0};
Channels m_Channels;
};
class Plotter
{
public:
void addType(const std::string& type)
{
m_Plots.emplace(type,std::vector<std::vector<TH1F>>());
}
void setGroupNumber(const std::string& type,const int& nbr)
{
m_Plots[type].resize(nbr);
}
TH1F& getPlot(const std::string& type,const int& group,const int& channel)
{
return m_Plots[type][group][channel];
}
private:
std::map<std::string,std::vector<std::vector<TH1F>>> m_Plots;
};
/*
* TH1D CreateSelectionPlot(const TH1D& th)
* {
* TH1D selected=th;
* selected.SetLineColor(kRed);
* std::string name="Selected_"+std::string(th.GetName());
* std::string title="Selected "+std::string(th.GetTitle());
* selected.SetTitle(title.c_str());
* selected.SetName(name.c_str());
* return std::move(selected);
* }*/
enum class Polarity
{
Positive=1,
Negative=-1,
Unknown=0,
};
int GetTickTrigger(const Channel& channel,const double& percent,const Polarity& polarity)
{
std::pair<std::pair<double,int>,std::pair<double,int>> min_max=getMinMax(channel);
int value{0};
for(std::size_t j = 0; j != channel.Data.size(); ++j)
{
if(polarity==Polarity::Positive && channel.Data[j] > percent*min_max.second.first)
{
value=j;
break;
}
else if(polarity==Polarity::Negative && channel.Data[j] < percent*min_max.first.first)
{
value=j;
break;
}
}
return value;
}
//####FIX ME PUT THIS AS PARAMETER OUT OF THE PROGRAM ######
int main(int argc, char** argv)
{
gStyle->SetOptStat(0);
gErrorIgnoreLevel = kWarning;
int width=0, height=0;
CLI::App app{"Analysis"};
std::string file{""};
app.add_option("-f,--file", file, "Name of the file to process")->required()->check(CLI::ExistingFile);
int NbrEvents{0};
app.add_option("-e,--events", NbrEvents, "Number of event to process")->check(CLI::PositiveNumber);
std::string nameTree{"Tree"};
app.add_option("-t,--tree", nameTree, "Name of the TTree");
std::pair<double, double> SignalWindow;
app.add_option("-s,--signal", SignalWindow, "Width of the signal windows, delay between signal and trigger")->required()->type_size(2);
std::pair<double, double> NoiseWindow;
app.add_option("-n,--noise", NoiseWindow, "Noise window")->required()->type_size(2);
std::pair<double, double> NoiseWindowAfter;
app.add_option("--noiseAfter", NoiseWindowAfter, "Noise window after")->required()->type_size(2);
double NbrSigmaNoise=5.0;
app.add_option("--sigmaNoise", NbrSigmaNoise, "NbrSigmaNoise");
int NumberChambers{0};
app.add_option("-c,--chambers", NumberChambers, "Number of chamber(s)")->check(CLI::PositiveNumber)->required();
std::vector<int> distribution;
app.add_option("-d,--distribution", distribution, "Channel is in wich chamber start at 0 and -1 if not connected")->required();
std::vector<std::string> polarity;
app.add_option("-p,--polarity", polarity, "Polarity of the signal Positive,+,Negative,-")->required();
std::vector<int> triggers{8,17,26,35};
app.add_option("--triggers", triggers, "Channels used as trigger 8,17,26,35 by default");
bool PlotTriggers=true;
app.add_option("--plot_triggers", PlotTriggers, "Plot the triggers");
double NbrSigma=5.0;
app.add_option("--sigma", NbrSigma, "Number of sigma above the mean noise");
try
{
app.parse(argc, argv);
}
catch(const CLI::ParseError& e)
{
return app.exit(e);
}
// Create Directory
std::string folder{"Results/"+std::string(fs::path(file).stem())};
fs::create_directories(folder+"/Events");
fs::create_directories(folder+"/Others");
if(PlotTriggers) fs::create_directories(folder+"/Triggers");
//Keep the ticks of each triggers
std::map<int,int> trigger_ticks;
std::map<int,TH1D> ticks_distribution;
for(std::size_t i=0;i!=triggers.size();++i)
{
trigger_ticks[triggers[i]]=0;
ticks_distribution[triggers[i]]=TH1D("Tick Distribution","Tick Distribution",1024,0,1024);
}
TH1D total("Tick Distribution","Tick Distribution",1024,0,1024);
TH1D delta_t("delta_T","delta_T",100,0,10);
TH1D delta_T_not_event("delta_T_not_even","delta_T_not_even",100,0,10);
TH1D delta_T_noisy("delta_T_noisy","delta_T_noisy",100,0,10);
/**************************/
/* Initialize the plotter */
/**************************/
Plotter plotter;
// We want two type channels and triggers
plotter.addType("Channels");
plotter.addType("Triggers");
//Open The file
TFile fileIn(file.c_str());
if(fileIn.IsZombie())
{
throw "File Not Opened";
}
TTree* Run = static_cast<TTree*>(fileIn.Get(nameTree.c_str()));
if(Run == nullptr || Run->IsZombie())
{
throw "Problem Opening TTree \"Tree\" !!!";
}
double scalefactor = 1.0;
Channels channels;
channels.activateChannel(0, "N");
channels.activateChannel(1, "N");
channels.activateChannel(2, "N");
channels.activateChannel(3, "N");
channels.activateChannel(4, "N");
channels.activateChannel(5, "N");
channels.activateChannel(6, "N");
channels.activateChannel(7, "N");
// channels.activateChannel(8, "N");
/* channels.activateChannel(9, "N");
channels.activateChannel(10, "N");
channels.activateChannel(11, "N");
channels.activateChannel(12, "N");
channels.activateChannel(13, "N");
channels.activateChannel(14, "N");
channels.activateChannel(15, "N");
channels.activateChannel(16, "N");*/
std::map<int,TH1D> mins;
for(auto channel : channels.getChannels())
{
mins[channel.first]=TH1D("min position distribution","min position distribution",1024,0,1024);
std::cout<<"*****"<<channel.first<<std::endl;
}
Long64_t NEntries = Run->GetEntries();
NbrEvents = NbrEventToProcess(NbrEvents, NEntries);
channels.print();
Event* event{nullptr};
int good_stack{0};
int good_stack_corrected{0};
bool good = false;
bool hasseensomething{false};
if(Run->SetBranchAddress("Events", &event))
{
throw "Error while SetBranchAddress !!!";
}
// std::vector<TH1D> Verif;
std::map<int, int> Efficiency;
TCanvas can("","",1280,720);
// Initialize multiplicity
std::vector<float> Multiplicity;
for(std::size_t i=0;i!=NumberChambers;++i)
{
Multiplicity.push_back(0.);
}
int event_skip1{-1};
int event_skip2{-1};
int total_event{0};
for(Long64_t evt = 0; evt < NbrEvents; ++evt)
{
get_terminal_size(width, height);
fmt::print(fg(fmt::color::orange) | fmt::emphasis::bold,"┌{0:─^{2}}┐\n"
"│{1: ^{2}}│\n"
"└{0:─^{2}}┘\n"
,"", fmt::format("Event {}",evt), width-2);
event->clear();
Run->GetEntry(evt);
std::vector<TH1D> Plots(event->Channels.size());
float min{std::numeric_limits<float>::max()};
float max{std::numeric_limits<float>::min()};
// First loop on triggers
for(unsigned int ch = 0; ch != event->Channels.size(); ++ch)
{
if(std::find(triggers.begin(),triggers.end(),ch)!=triggers.end())
{
SupressBaseLine(event->Channels[ch]);
double max=getAbsMax(event->Channels[ch]);
Normalise(event->Channels[ch],max);
int tick=GetTickTrigger(event->Channels[ch],0.20,Polarity::Negative);
trigger_ticks[ch]=tick;
if(PlotTriggers)
{
can.Clear();
TH1D toto=CreateAndFillWaveform(evt, event->Channels[ch], "Waveform", "Waveform");
toto.Draw("HIST");
TLine event_min;
event_min.SetLineColor(15);
event_min.SetLineWidth(1);
event_min.SetLineStyle(2);
event_min.DrawLine(tick,-1.,tick,1.);
event_min.DrawLine(0,-0.2,1024,-0.2);
ticks_distribution[ch].Fill(tick);
can.SaveAs((folder+"/Triggers"+"/Event"+std::to_string(evt)+"_Trigger"+std::to_string(ch)+".pdf").c_str(),"Q");
}
}
}
can.Clear();
TPaveLabel title(0.01, 0.965, 0.95, 0.99, ("Event "+std::to_string(evt)).c_str());
title.Draw();
TPad graphPad("Graphs","Graphs",0.01,0.01,0.995,0.96);
graphPad.Draw();
graphPad.cd();
graphPad.Divide(1,8,0.,0.);
double delta_t_last{0};
double delta_t_new{0};
for(unsigned int ch = 0; ch != event->Channels.size(); ++ch)
{
if(channels.DontAnalyseIt(ch)) continue; // Data for channel X is in file but i dont give a *** to analyse it !
if(ch==0)
{
delta_t_new = event->Channels[ch].TriggerTimeTag;
if(evt!=0)
{
delta_t.Fill((delta_t_new-delta_t_last)*8.5e-9);
}
}
get_terminal_size(width, height);
fmt::print(fg(fmt::color::white) | fmt::emphasis::bold,"┌{0:─^{2}}┐\n"
"│{1: ^{2}}│\n"
"└{0:─^{2}}┘\n"
,"", fmt::format("Channel {}",ch), width-2);
if(evt == 0) Efficiency[ch] = 0;
SupressBaseLine(event->Channels[ch]);
double max=getAbsMax(event->Channels[ch]);
Normalise(event->Channels[ch],max);
Plots[ch]=CreateAndFillWaveform(evt, event->Channels[ch], "Waveform", "Waveform");
///BAD PLEASE FIX THIS !!!
std::pair<int,int> SignalWindow2;
if(ch<=8)
{
SignalWindow2.first=trigger_ticks[8]-SignalWindow.second-SignalWindow.first/2;
SignalWindow2.second=trigger_ticks[8]-SignalWindow.second+SignalWindow.first/2;
}
std::pair<std::pair<double, double>, std::pair<double, double>> meanstd = MeanSTD(event->Channels[ch], SignalWindow2, NoiseWindow);
std::pair<std::pair<double, double>, std::pair<double, double>> meanstdAfter = MeanSTD(event->Channels[ch], SignalWindow2, NoiseWindowAfter);
if(meanstdAfter.first.second*1.0/meanstd.first.second >= NbrSigmaNoise)
{
event_skip1=evt;
event_skip2=evt+1;
}
/*
*
*
*/
std::pair<std::pair<double,int>,std::pair<double,int>> min_max=getMinMax(event->Channels[ch]);
mins[ch].Fill(trigger_ticks[8]-min_max.first.second);
total.Fill(trigger_ticks[8]-min_max.first.second);
/*
*
*
*/
min_max=getMinMax(event->Channels[ch],SignalWindow2.first,SignalWindow2.second);
// std::cout<<"Event "<<evt<<" Channel "<<ch<<"/n";
// std::cout<<" Mean : "<<meanstd.first<<" STD :
// "<<meanstd.second<<std::endl;
// selected with be updated each time we make some selection... For now
// it's the same as Waveform one but in Red !!!
// TH1D selected = CreateSelectionPlot(waveform);
if((min_max.first.first-meanstd.first.first)*channels.getPolarity(ch) > NbrSigma * meanstd.first.second) hasseensomething = true;
else hasseensomething = false;
if(hasseensomething == true)
{
good = true;
//FIXME add the chamber ability;
Multiplicity[0]++;
//hasseensomething=true;
Plots[ch].SetLineColor(4);
//waveform.Scale(1.0 / 4096);
// if(channels.ShouldBePositive(ch)) waveform.Fit(f1);
// else waveform.Fit(f1);
//can.SaveAs(("GOOD/GOOD" + std::to_string(evt) + "_Channel" + std::to_string(ch) + ".pdf").c_str(),"Q");
fmt::print(fg(fmt::color::green) | fmt::emphasis::bold,"{:^{}}\n",fmt::format("Mean signal region : {:05.4f}+-{:05.4f} min = {:05.4f}, Mean noise region : {:05.4f}+-{:05.4f}, Selection criteria {:05.4f} sigmas ({:05.4f}), Condition to fullfill {:05.4f}>{:05.4f}",meanstd.second.first,meanstd.second.second,min_max.first.first,meanstd.first.first,meanstd.first.second,NbrSigma,NbrSigma * meanstd.first.second,(min_max.first.first-meanstd.first.first)*channels.getPolarity(ch),NbrSigma * meanstd.first.second),width);
}
else
{
Plots[ch].SetLineColor(16);
// waveform.Scale(1.0 / 4096);
// if(channels.ShouldBePositive(ch)) waveform.Fit(f1);
// else waveform.Fit(f1);
//can.SaveAs(("BAD/BAD" + std::to_string(evt) + "_Channel" + std::to_string(ch) + ".pdf").c_str(),"Q");
//can.SaveAs(("GOOD/GOOD" + std::to_string(evt) + "_Channel" + std::to_string(ch) + ".pdf").c_str(),"Q");
fmt::print(fg(fmt::color::red) | fmt::emphasis::bold,"{:^{}}\n",fmt::format("Mean signal region : {:05.4f}+-{:05.4f} min = {:05.4f}, Mean noise region : {:05.4f}+-{:05.4f}, Selection criteria {:05.4f} sigmas ({:05.4f}), Condition to fullfill {:05.4f}>{:05.4f}",meanstd.second.first,meanstd.second.second,min_max.first.first,meanstd.first.first,meanstd.first.second,NbrSigma,NbrSigma * meanstd.first.second,(min_max.first.first-meanstd.first.first)*channels.getPolarity(ch),NbrSigma * meanstd.first.second),width);
}
graphPad.cd(ch+1);
gStyle->SetLineWidth(gStyle->GetLineWidth() / 4);
Plots[ch].GetXaxis()->SetRangeUser(0, 1024);
Plots[ch].GetYaxis()->SetNdivisions(10,0,0);
Plots[ch].GetXaxis()->SetNdivisions(10,10,0);
Plots[ch].GetYaxis()->SetRangeUser(-1.2,1.2);
Plots[ch].GetYaxis()->SetLabelSize(0.07);
Plots[ch].SetStats();
Plots[ch].SetTitle(";");
if(ch==7)
{
Plots[ch].GetXaxis()->SetLabelOffset(0.02);
Plots[ch].GetXaxis()->SetLabelSize(0.1);
}
else
{
Plots[ch].GetXaxis()->SetTitleOffset(0.);
Plots[ch].GetXaxis()->SetLabelSize(0.);
Plots[ch].GetXaxis()->SetTitleSize(0.);
}
Plots[ch].Draw("HIST");
TLine event_min;
event_min.SetLineColor(15);
event_min.SetLineWidth(1);
event_min.SetLineStyle(2);
event_min.DrawLine(SignalWindow2.first,-200,SignalWindow2.first,200);
event_min.DrawLine(SignalWindow2.second,-200,SignalWindow2.second,200);
event_min.SetLineColor(16);
event_min.SetLineWidth(1);
event_min.SetLineStyle(4);
event_min.DrawLine(NoiseWindow.first,-200,NoiseWindow.first,200);
event_min.DrawLine(NoiseWindow.second,-200,NoiseWindow.second,200);
event_min.SetLineStyle(5);
event_min.SetLineColor(kRed);
event_min.DrawLine(0,min_max.first.second,1024,min_max.first.second);
//Mean noise
event_min.SetLineColor(46);
event_min.DrawLine(NoiseWindow.first,meanstd.first.first,NoiseWindow.second,meanstd.first.first);
//Mean Signal
event_min.SetLineColor(40);
event_min.DrawLine(SignalWindow2.first,meanstd.second.first,SignalWindow2.second,meanstd.second.first);
//Bars
event_min.SetLineColor(kBlack);
event_min.SetLineStyle(4);
event_min.DrawLine(0,meanstd.first.first-NbrSigma * meanstd.first.second,1024,meanstd.first.first-NbrSigma * meanstd.first.second);
event_min.DrawLine(0,meanstd.first.first+NbrSigma * meanstd.first.second,1024,meanstd.first.first+NbrSigma * meanstd.first.second);
/*
event_min.SetLineColor(kRed);
event_min.DrawLine(SignalWindow.first,(meanstd.second.first-meanstd.first.first)*channels.getPolarity(ch),SignalWindow.second,(meanstd.second.first-meanstd.first.first)*channels.getPolarity(ch));
event_min.SetLineColor(kGreen);
event_min.DrawLine(0,meanstd.first.first+2 * meanstd.first.second,1024,meanstd.first.first+2 * meanstd.first.second);
event_min.DrawLine(0,meanstd.first.first-2 * meanstd.first.second,1024,meanstd.first.first-2 * meanstd.first.second);
event_min.Draw();*/
}
can.SetTitle(("Event " + std::to_string(evt)).c_str());
can.SetName(("Event " + std::to_string(evt)).c_str());
can.SaveAs((folder+"/Events"+"/Event"+std::to_string(evt)+".pdf").c_str(),"Q");
if(good == true)
{
if(event_skip2!=evt)
{
good_stack_corrected++;
}
good_stack++;
good = false;
//hasseensomething=true;
}
else
{
delta_T_not_event.Fill((delta_t_new-delta_t_last)*8.5e-9);
}
if(event_skip2!=evt)
{
total_event++;
}
delta_t_new=delta_t_last;
Clear();
}
for(std::map<int,TH1D>::iterator it= ticks_distribution.begin();it!= ticks_distribution.end();++it)
{
can.Clear();
it->second.Draw();
can.SaveAs((folder+"/Others"+"/Tick_Distribution_"+std::to_string(it->first)+".pdf").c_str(),"Q");
}
for(auto min : mins)
{
can.Clear();
min.second.GetXaxis()->SetNdivisions(510);
min.second.Draw();
can.SaveAs((folder+"/Others"+"/minimum_position_distribution"+std::to_string(min.first)+".pdf").c_str(),"Q");
}
can.Clear();
total.GetXaxis()->SetNdivisions(510);
total.Draw();
can.SaveAs((folder+"/Others"+"/minimum_position_distribution_total.pdf").c_str(),"Q");
can.Clear();
delta_t.GetXaxis()->SetNdivisions(510);
delta_t.Draw();
can.SaveAs((folder+"/DeltaT.pdf").c_str(),"Q");
can.Clear();
delta_T_not_event.GetXaxis()->SetNdivisions(510);
delta_T_not_event.Draw();
can.SaveAs((folder+"/delta_T_not_event.pdf").c_str(),"Q");
can.Clear();
delta_T_noisy.GetXaxis()->SetNdivisions(510);
delta_T_noisy.Draw();
can.SaveAs((folder+"/delta_T_noisy.pdf").c_str(),"Q");
float efficiency=good_stack * 1.00 / (NbrEvents * scalefactor);
float efficiency_corrected=good_stack_corrected * 1.00 / (total_event * scalefactor);
std::cout << "Chamber efficiency " << efficiency << " +-" <<std::sqrt(efficiency*(1-efficiency)/NbrEvents)<<" with signal "<<good_stack<<" total event "<< NbrEvents<<" Multiplicity"<< Multiplicity[0]/good_stack<< std::endl;
std::cout << "Chamber efficiency corrected " << efficiency_corrected << " +-" <<std::sqrt(efficiency_corrected*(1-efficiency_corrected)/total_event)<<" with signal "<<good_stack_corrected<<" total event "<< total_event <<std::endl;
std::cout<< "Number event analysed " << total_event*100.0/NbrEvents <<std::endl;
if(event != nullptr) delete event;
if(Run != nullptr) delete Run;
if(fileIn.IsOpen()) fileIn.Close();
}
| 33.129442 | 523 | 0.635984 | [
"vector"
] |
f69c22d2a95e2ffc08ea4e3ae0430c7957b5868a | 23,328 | cc | C++ | tensorflow/contrib/persona/kernels/snap-align/SnapAlignerWrapper.cc | epfl-dcsl/ptf-system | 16d634bf2572eb316112ea34630feaa90a560e5a | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/persona/kernels/snap-align/SnapAlignerWrapper.cc | epfl-dcsl/ptf-system | 16d634bf2572eb316112ea34630feaa90a560e5a | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/persona/kernels/snap-align/SnapAlignerWrapper.cc | epfl-dcsl/ptf-system | 16d634bf2572eb316112ea34630feaa90a560e5a | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 École Polytechnique Fédérale de Lausanne. 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 <vector>
#include <exception>
#include "tensorflow/core/platform/logging.h"
#include "AlignerOptions.h"
#include "AlignmentResult.h"
#include "BaseAligner.h"
#include "Genome.h"
#include "GenomeIndex.h"
#include "Read.h"
#include "SingleAligner.h"
#include "SeedSequencer.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/errors.h"
#include "SAM.h"
#include "SnapAlignerWrapper.h"
namespace snap_wrapper {
using namespace tensorflow;
using namespace std;
namespace {
const int maxReadSize = MAX_READ_LENGTH;
}
Status init() {
InitializeSeedSequencers();
return Status::OK();
}
PairedAligner::PairedAligner(const PairedAlignerOptions *options_, GenomeIndex *index) :
options(options_), format(options_->useM), genome(index->getGenome()) {
size_t memoryPoolSize = IntersectingPairedEndAligner::getBigAllocatorReservation(
index,
options->intersectingAlignerMaxHits,
maxReadSize,
index->getSeedLength(),
options->numSeedsFromCommandLine,
options->seedCoverage,
options->maxDist,
options->extraSearchDepth,
options->maxCandidatePoolSize,
options->maxSecondaryAlignmentsPerContig);
memoryPoolSize += ChimericPairedEndAligner::getBigAllocatorReservation(
index,
maxReadSize,
options->maxHits,
index->getSeedLength(),
options->numSeedsFromCommandLine,
options->seedCoverage,
options->maxDist,
options->extraSearchDepth,
options->maxCandidatePoolSize,
options->maxSecondaryAlignmentsPerContig);
if (options->maxSecondaryAlignmentAdditionalEditDistance < 0) {
maxPairedSecondaryHits_ = 0;
maxSingleSecondaryHits_ = 0;
} else {
maxPairedSecondaryHits_ = IntersectingPairedEndAligner::getMaxSecondaryResults(
options->numSeedsFromCommandLine,
options->seedCoverage,
maxReadSize,
options->maxHits,
index->getSeedLength(),
options->minSpacing,
options->maxSpacing);
maxSingleSecondaryHits_ = ChimericPairedEndAligner::getMaxSingleEndSecondaryResults(
options->numSeedsFromCommandLine,
options->seedCoverage,
maxReadSize,
options->maxHits,
index->getSeedLength());
}
memoryPoolSize += (1 + maxPairedSecondaryHits_) * sizeof(PairedAlignmentResult) + maxSingleSecondaryHits_ * sizeof(SingleAlignmentResult);
allocator.reset(new BigAllocator(memoryPoolSize));
if (!allocator) {
LOG(ERROR) << "Unable to create new big allocator for pool size " << memoryPoolSize;
throw logic_error("Allocation of big allocator failed");
}
auto *alloc = allocator.get();
intersectingAligner = new (alloc) IntersectingPairedEndAligner(
index,
maxReadSize,
options->maxHits,
options->maxDist,
options->numSeedsFromCommandLine,
options->seedCoverage,
options->minSpacing,
options->maxSpacing,
options->intersectingAlignerMaxHits,
options->extraSearchDepth,
options->maxCandidatePoolSize,
options->maxSecondaryAlignmentsPerContig,
alloc,
options->noUkkonen,
options->noOrderedEvaluation,
options->noTruncation);
if (!intersectingAligner) {
auto err = "Unable to create intersecting aligner";
LOG(ERROR) << err;
throw logic_error(err);
}
aligner = new (alloc) ChimericPairedEndAligner(
index,
maxReadSize,
options->maxHits,
options->maxDist,
options->numSeedsFromCommandLine,
options->seedCoverage,
options->minWeightToCheck,
options->forceSpacing,
options->extraSearchDepth,
options->noUkkonen,
options->noOrderedEvaluation,
options->noTruncation,
intersectingAligner,
options->minReadLength,
options->maxSecondaryAlignmentsPerContig,
alloc);
if (!aligner) {
intersectingAligner->~IntersectingPairedEndAligner();
auto err = "Unable to create chimeric aligner";
LOG(ERROR) << err;
throw logic_error(err);
}
allocator->checkCanaries();
secondary_results_.reset(new PairedAlignmentResult[maxPairedSecondaryHits_]);
secondary_single_results_.reset(new SingleAlignmentResult[maxSingleSecondaryHits_]);
}
PairedAligner::~PairedAligner() {
// This calls the destructor without calling operator delete, allocator owns the memory.
allocator->checkCanaries();
aligner->~ChimericPairedEndAligner();
intersectingAligner->~IntersectingPairedEndAligner();
// No need to call delete on allocator. unique_ptr takes care of it
}
// FIXME need to pass in max_secondary to this method
void
PairedAligner::align(array<Read, 2> &snap_reads, PairedAlignmentResult &result, int max_secondary,
PairedAlignmentResult** secondary_results, int* num_secondary_results,
SingleAlignmentResult** secondary_single_results, int* num_secondary_single_results_first,
int* num_secondary_single_results_second) {
aligner->align(&snap_reads[0], &snap_reads[1],
&result,
options->maxSecondaryAlignmentAdditionalEditDistance,
maxPairedSecondaryHits_, // secondary results buffer size
num_secondary_results,
secondary_results_.get(), // secondary results buffer
maxSingleSecondaryHits_, // single secondary buffer size
max_secondary, //max_secondary_, // maxSecondaryAlignmentsToReturn
num_secondary_single_results_first,
num_secondary_single_results_second,
secondary_single_results_.get()); // more stuff related to secondary results
*secondary_results = secondary_results_.get();
*secondary_single_results = secondary_single_results_.get();
}
Status
PairedAligner::writeResult(array<Read, 2> &snap_reads, PairedAlignmentResult &result, AlignmentResultBuilder &result_column, bool is_secondary) {
array<Alignment, 2> results;
array<string, 2> cigars;
// always write pair 1 before pair 2
// make sure 'first in pair'/'second in pair' matches original data
snap_reads[0].setAdditionalFrontClipping(0);
snap_reads[1].setAdditionalFrontClipping(0);
// we don't write out the results yet in case one of them fails
int addFrontClipping;
int cumulativePositiveAddFrontClipping[2] = { 0, 0 };
GenomeLocation finalLocations[2];
finalLocations[0] = result.status[0] != NotFound ? result.location[0] : InvalidGenomeLocation;
finalLocations[1] = result.status[1] != NotFound ? result.location[1] : InvalidGenomeLocation;
for (int i = 0; i < 2; ++i) {
auto &read = snap_reads[i];
TF_RETURN_IF_ERROR(PostProcess(genome,
&lvc,
&read,
result.status[i],
result.mapq[i],
finalLocations[i],
result.direction[i],
is_secondary,
results[i],
cigars[i],
&addFrontClipping,
true, // useM
true,
i == 0,
&snap_reads[1 - i],
result.status[1 - i],
finalLocations[1 - i],
result.direction[1 - i],
result.alignedAsPair));
if (addFrontClipping != 0) {
const Genome::Contig *originalContig = genome->getContigAtLocation(finalLocations[i]);
const Genome::Contig *newContig = genome->getContigAtLocation(finalLocations[i] + addFrontClipping);
if (newContig != originalContig || NULL == newContig || finalLocations[i] + addFrontClipping > originalContig->beginningLocation + originalContig->length - genome->getChromosomePadding()) {
//
// Altering this would push us over a contig boundary. Just give up on the read.
//
result.status[i] = NotFound;
result.location[i] = InvalidGenomeLocation;
finalLocations[i] = InvalidGenomeLocation;
//results[i].set_location(finalLocations[i]);
results[i].mutable_position()->set_position(-1);
results[i].mutable_position()->set_ref_index(-1);
} else {
if (addFrontClipping > 0) {
cumulativePositiveAddFrontClipping[i] += addFrontClipping;
read.setAdditionalFrontClipping(cumulativePositiveAddFrontClipping[i]);
}
finalLocations[i] += addFrontClipping;
//results[i].set_location(finalLocations[i]); //update in the result itself
}
if (i == 1) // if i is 1 we need to redo the first one because the second has a location change
i -= 2;
else
i -= 1; // just redo the first now
}
}
// Loop again now that all the adjustments worked correctly
// TODO put an assert check here to make sure the read pair is properly formed
for (size_t i = 0; i < 2; ++i) {
result_column.AppendAlignmentResult(results[i]);
}
return Status::OK();
}
Status WriteSingleResult(Read &snap_read, SingleAlignmentResult &result, AlignmentResultBuilder &result_column,
const Genome* genome, LandauVishkinWithCigar* lvc, bool is_secondary, bool use_m) {
string cigar;
Alignment format_result;
snap_read.setAdditionalFrontClipping(0);
int addFrontClipping = -1;
GenomeLocation finalLocation = result.status != NotFound ? result.location : InvalidGenomeLocation;
unsigned nAdjustments = 0;
int cumulativeAddFrontClipping = 0;
while (addFrontClipping != 0) {
addFrontClipping = 0;
TF_RETURN_IF_ERROR(PostProcess(genome,
lvc,
&snap_read,
result.status,
result.mapq,
finalLocation,
result.direction,
is_secondary,
format_result,
cigar,
&addFrontClipping,
use_m));
// redo if read modified (e.g. to add soft clipping, or move alignment for a leading I.
if (addFrontClipping != 0) {
nAdjustments++;
const Genome::Contig *originalContig = result.status == NotFound ? NULL
: genome->getContigAtLocation(result.location);
const Genome::Contig *newContig = result.status == NotFound ? NULL
: genome->getContigAtLocation(result.location + addFrontClipping);
if (newContig == NULL || newContig != originalContig || finalLocation + addFrontClipping > originalContig->beginningLocation + originalContig->length - genome->getChromosomePadding() ||
nAdjustments > snap_read.getDataLength()) {
//
// Altering this would push us over a contig boundary, or we're stuck in a loop. Just give up on the read.
//
result.status = NotFound;
result.location = InvalidGenomeLocation;
finalLocation = InvalidGenomeLocation;
} else {
cumulativeAddFrontClipping += addFrontClipping;
if (addFrontClipping > 0) {
snap_read.setAdditionalFrontClipping(cumulativeAddFrontClipping);
}
finalLocation = result.location + cumulativeAddFrontClipping;
}
}
}
//format_result.set_cigar(cigar);
result_column.AppendAlignmentResult(format_result);
return Status::OK();
}
Status PostProcess(
const Genome* genome,
LandauVishkinWithCigar * lv,
Read * read,
AlignmentResult result,
int mapQuality,
GenomeLocation genomeLocation,
Direction direction,
bool secondaryAlignment,
Alignment &finalResult,
string &cigar,
int * addFrontClipping,
bool useM,
bool hasMate,
bool firstInPair,
Read * mate,
AlignmentResult mateResult,
GenomeLocation mateLocation,
Direction mateDirection,
bool alignedAsPair
)
{
cigar = "*";
const int MAX_READ = MAX_READ_LENGTH;
char data[MAX_READ];
char quality[MAX_READ];
/*const int cigarBufSize = MAX_READ * 2;
char cigarBuf[cigarBufSize];
const int cigarBufWithClippingSize = MAX_READ * 2 + 32;
char cigarBufWithClipping[cigarBufWithClippingSize];
int flags = 0;
const char *cigar = "*";
const char *matecontigName = "*";
int mateContigIndex = -1;
GenomeDistance matePositionInContig = 0;
_int64 templateLength = 0;
char data[MAX_READ];
char quality[MAX_READ];
const char* clippedData;
unsigned fullLength;
unsigned clippedLength;
unsigned basesClippedBefore;
GenomeDistance extraBasesClippedBefore; // Clipping added if we align before the beginning of a chromosome
unsigned basesClippedAfter;
int editDistance = -1;*/
*addFrontClipping = 0;
const char *contigName = "*";
const char *matecontigName = "*";
int contigIndex = -1;
GenomeDistance positionInContig = 0;
int mateContigIndex = -1;
GenomeDistance matePositionInContig = 0;
GenomeDistance extraBasesClippedBefore; // Clipping added if we align before the beginning of a chromosome
_int64 templateLength = 0;
const char* clippedData;
unsigned fullLength;
unsigned clippedLength;
unsigned basesClippedBefore;
unsigned basesClippedAfter;
int editDistance = -1;
uint16_t flags = 0;
GenomeLocation orig_location = genomeLocation;
if (secondaryAlignment) {
flags |= SAM_SECONDARY;
}
//
// If the aligner said it didn't find anything, treat it as such. Sometimes it will emit the
// best match that it found, even if it's not within the maximum edit distance limit (but will
// then say NotFound). Here, we force that to be SAM_UNMAPPED.
//
if (NotFound == result) {
genomeLocation = InvalidGenomeLocation;
}
if (InvalidGenomeLocation == genomeLocation) {
//
// If it's unmapped, then always emit it in the forward direction. This is necessary because we don't even include
// the SAM_REVERSE_COMPLEMENT flag for unmapped reads, so there's no way to tell that we reversed it.
//
direction = FORWARD;
}
clippedLength = read->getDataLength();
fullLength = read->getUnclippedLength();
if (direction == RC) {
for (unsigned i = 0; i < fullLength; i++) {
data[fullLength - 1 - i] = COMPLEMENT[read->getUnclippedData()[i]];
quality[fullLength - 1 - i] = read->getUnclippedQuality()[i];
}
clippedData = &data[fullLength - clippedLength - read->getFrontClippedLength()];
basesClippedBefore = fullLength - clippedLength - read->getFrontClippedLength();
basesClippedAfter = read->getFrontClippedLength();
} else {
clippedData = read->getData();
basesClippedBefore = read->getFrontClippedLength();
basesClippedAfter = fullLength - clippedLength - basesClippedBefore;
}
if (genomeLocation != InvalidGenomeLocation) {
if (direction == RC) {
flags |= SAM_REVERSE_COMPLEMENT;
}
const Genome::Contig *contig = genome->getContigForRead(genomeLocation, read->getDataLength(), &extraBasesClippedBefore);
_ASSERT(NULL != contig && contig->length > genome->getChromosomePadding());
genomeLocation += extraBasesClippedBefore;
contigName = contig->name;
contigIndex = (int)(contig - genome->getContigs());
positionInContig = genomeLocation - contig->beginningLocation; // SAM is 1-based
mapQuality = max(0, min(70, mapQuality)); // FIXME: manifest constant.
} else {
flags |= SAM_UNMAPPED;
mapQuality = 0;
extraBasesClippedBefore = 0;
}
finalResult.mutable_next_position()->set_position(-1);
finalResult.mutable_next_position()->set_ref_index(-1);
if (hasMate) {
flags |= SAM_MULTI_SEGMENT;
flags |= (firstInPair ? SAM_FIRST_SEGMENT : SAM_LAST_SEGMENT);
if (mateLocation != InvalidGenomeLocation) {
GenomeDistance mateExtraBasesClippedBefore;
const Genome::Contig *mateContig = genome->getContigForRead(mateLocation, mate->getDataLength(), &mateExtraBasesClippedBefore);
mateLocation += mateExtraBasesClippedBefore;
matecontigName = mateContig->name;
mateContigIndex = (int)(mateContig - genome->getContigs());
matePositionInContig = mateLocation - mateContig->beginningLocation;
if (mateDirection == RC) {
flags |= SAM_NEXT_REVERSED;
}
if (genomeLocation == InvalidGenomeLocation) {
//
// The SAM spec says that for paired reads where exactly one end is unmapped that the unmapped
// half should just have RNAME and POS copied from the mate.
//
contigName = matecontigName;
contigIndex = mateContigIndex;
matecontigName = "=";
positionInContig = matePositionInContig;
}
} else {
flags |= SAM_NEXT_UNMAPPED;
//
// The mate's unmapped, so point it at us.
// in AGD this doesnt matter
matecontigName = "=";
mateContigIndex = contigIndex;
matePositionInContig = positionInContig;
}
if (genomeLocation != InvalidGenomeLocation && mateLocation != InvalidGenomeLocation) {
if (alignedAsPair) {
flags |= SAM_ALL_ALIGNED;
}
// Also compute the length of the whole paired-end string whose ends we saw. This is slightly
// tricky because (a) we may have clipped some bases before/after each end and (b) we need to
// give a signed result based on whether our read is first or second in the pair.
GenomeLocation myStart = genomeLocation - basesClippedBefore;
GenomeLocation myEnd = genomeLocation + clippedLength + basesClippedAfter;
_int64 mateBasesClippedBefore = mate->getFrontClippedLength();
_int64 mateBasesClippedAfter = mate->getUnclippedLength() - mate->getDataLength() - mateBasesClippedBefore;
GenomeLocation mateStart = mateLocation - (mateDirection == RC ? mateBasesClippedAfter : mateBasesClippedBefore);
GenomeLocation mateEnd = mateLocation + mate->getDataLength() + (mateDirection == FORWARD ? mateBasesClippedAfter : mateBasesClippedBefore);
if (contigName == matecontigName) { // pointer (not value) comparison, but that's OK.
if (myStart < mateStart) {
templateLength = mateEnd - myStart;
} else {
templateLength = -(myEnd - mateStart);
}
} // otherwise leave TLEN as zero.
}
if (contigName == matecontigName) {
matecontigName = "="; // SAM Spec says to do this when they're equal (and not *, which won't happen because this is a pointer, not string, compare)
}
finalResult.mutable_next_position()->set_position(matePositionInContig);
finalResult.mutable_next_position()->set_ref_index(mateContigIndex);
}
finalResult.set_mapping_quality(mapQuality);
finalResult.set_flag(flags);
finalResult.set_template_length(templateLength);
finalResult.mutable_position()->set_position(positionInContig);
finalResult.mutable_position()->set_ref_index(contigIndex);
const int cigarBufSize = MAX_READ * 2;
char cigarBuf[cigarBufSize];
const int cigarBufWithClippingSize = MAX_READ * 2 + 32;
char cigarBufWithClipping[cigarBufWithClippingSize];
if (orig_location != InvalidGenomeLocation) {
const char * thecigar = SAMFormat::computeCigarString(genome, lv, cigarBuf, cigarBufSize, cigarBufWithClipping, cigarBufWithClippingSize,
clippedData, clippedLength, basesClippedBefore, extraBasesClippedBefore, basesClippedAfter,
read->getOriginalFrontHardClipping(), read->getOriginalBackHardClipping(), orig_location, direction, useM,
&editDistance, addFrontClipping);
//VLOG(INFO) << "cigar output was : " << thecigar << " and frontclipping was " << *addFrontClipping;
if (*addFrontClipping != 0) {
// higher up the call stack deals with this
//return errors::Internal("something went horribly wrong creating a cigar string");
} else {
cigar = thecigar;
finalResult.set_cigar(thecigar);
}
}
return Status::OK();
}
}
| 42.725275 | 197 | 0.60018 | [
"vector"
] |
f69ccd7c3cf069e8dc9aa44d2354accf9eb2aa1d | 10,454 | cpp | C++ | deps/src/boost_1_65_1/libs/spirit/classic/test/bug_fixes.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2018-12-15T20:03:51.000Z | 2018-12-15T20:03:51.000Z | deps/src/boost_1_65_1/libs/spirit/classic/test/bug_fixes.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 3 | 2021-09-08T02:18:00.000Z | 2022-03-12T00:39:44.000Z | deps/src/boost_1_65_1/libs/spirit/classic/test/bug_fixes.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2020-10-21T17:46:28.000Z | 2020-10-21T17:46:28.000Z | /*=============================================================================
Copyright (c) 2003 Giovanni Bajo
Copyright (c) 2003 Joel de Guzman
Copyright (c) 2003 Vaclav Vesely
http://spirit.sourceforge.net/
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_assign_actor.hpp>
using namespace boost;
using namespace BOOST_SPIRIT_CLASSIC_NS;
using namespace std;
///////////////////////////////////////////////////////////////////////////////
//
// bug_001
//
// access_node_d[] and access_match_d[] iterator bug
// http://sf.net/mailarchive/forum.php?thread_id=1963157&forum_id=1595
// http://sf.net/mailarchive/forum.php?thread_id=1966224&forum_id=1595
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_ast.hpp>
struct my_action
{
template <typename TreeT, typename IterT>
void operator()(TreeT& /*t*/, IterT begin, IterT end) const
{
BOOST_TEST(*begin == '1');
BOOST_TEST(*end == '2');
}
};
void bug_001()
{
const char* text = "123";
ast_parse(text, text+3, access_node_d[chlit<>('1')][my_action()]);
ast_parse(text, text+3, access_match_d[chlit<>('1')][my_action()]);
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_001
//
// mismatch closure return type bug
// http://article.gmane.org/gmane.comp.parsers.spirit.general/3678
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_attribute.hpp>
#include <string>
typedef std::string member_type;
struct my_closure: closure<my_closure, member_type>
{
member1 val;
};
void bug_002()
{
rule<scanner<char const*>, my_closure::context_t> my_rule = real_p;
BOOST_TEST(parse("1", my_rule).full);
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_003
//
// impl::detach_clear bug
// http://sourceforge.net/mailarchive/forum.php?thread_id=2008510&forum_id=25901
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_chset.hpp>
void bug_003()
{
chset<> set;
set = 'a';
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_004
//
// chset<>::operator~(range<>) bug
// operator&(chset<>, range<>) bug
// operator&(range<>, chset<>) bug
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/limits.hpp>
#include <boost/spirit/include/classic_chset.hpp>
void bug_004()
{
const char min = (numeric_limits<char>::min)();
const char max = (numeric_limits<char>::max)();
{
chset<> set(~range<>(min, max));
BOOST_TEST(set.test(min) == false);
BOOST_TEST(set.test(min) == false);
}
{
chset<> set(chset<>(anychar_p) & range<>(min, max));
BOOST_TEST(set.test(min) == true);
BOOST_TEST(set.test(min) == true);
}
{
chset<> set(range<>(min, max) & chset<>(anychar_p));
BOOST_TEST(set.test(min) == true);
BOOST_TEST(set.test(min) == true);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_005
//
// Most trailing space bug
// http://article.gmane.org/gmane.comp.parsers.spirit.general/4029
// JDG: Oct 18, 2005. We shall revert to the previous behavior where
// Post skips are not allowed. The reason is that
// there is a valid use case where input is obtained
// from cin and multi_pass which results in an infinite
// loop while the post skipper waits for a whitespace.
// For examples like below, the grammar must explicitly
// include the post whitespace. One possible way is to
// place an end_p at the end of the grammar. The end_p
// will trigger the post-skip.
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_core.hpp>
using namespace std;
using namespace boost;
using namespace spirit;
void bug_005()
{
BOOST_TEST(
parse(" aaaaaaaaa ", *ch_p('a') >> end_p, space_p).full
);
BOOST_TEST(
parse(" aaaaaaaaa ", lexeme_d[*ch_p('a')] >> end_p, space_p).full
);
#if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
// not sure why Code Warrior 9.5 does not recognize ch_p(' ') as the
// same as space_p (see above) when the inputs are spaces. The
// tests below are redundant anyway.
#else
BOOST_TEST(
parse(" aaaaaaaaa ", *ch_p('a') >> end_p, ch_p(' ')).full
);
BOOST_TEST(
parse(" aaaaaaaaa ", lexeme_d[*ch_p('a')] >> end_p, ch_p(' ')).full
);
#endif
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_006
//
// confix bug
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/limits.hpp>
#include <boost/spirit/include/classic_confix.hpp>
void bug_006()
{
BOOST_TEST(parse("#some comment", comment_p('#')).full);
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_007
//
// handling of trailing whitespace bug (ast_parse/pt_parse related)
// JDG: Oct 18, 2005. We shall revert to the previous behavior where
// Post skips are not allowed. The reason is that
// there is a valid use case where input is obtained
// from cin and multi_pass which results in an infinite
// loop while the post skipper waits for a whitespace.
// For examples like below, the grammar must explicitly
// include the post whitespace. One possible way is to
// place an end_p at the end of the grammar. The end_p
// will trigger the post-skip.
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_ast.hpp>
#include <boost/spirit/include/classic_parse_tree.hpp>
void bug_007()
{
BOOST_TEST(parse("test ", str_p("test") >> end_p, space_p).full);
BOOST_TEST(pt_parse("test ", str_p("test") >> end_p, space_p).full);
BOOST_TEST(ast_parse("test ", str_p("test") >> end_p, space_p).full);
}
///////////////////////////////////////////////////////////////////////////////
//
// sf_bug_718903
//
// see https://sourceforge.net/tracker/index.php
// ?func=detail&aid=718903&group_id=28447&atid=393386
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/cstdlib.hpp>
#include <boost/spirit/include/classic_chset.hpp>
void sf_bug_718903()
{
empty_match_parser<chset<char> >
e(epsilon_p(chset_p("abc")));
}
///////////////////////////////////////////////////////////////////////////////
//
// sf_bug_719322
// range_run bug
//
// see http://sourceforge.net/tracker/index.php
// ?func=detail&aid=719322&group_id=28447&atid=393386
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_basic_chset.hpp>
void sf_bug_719322()
{
basic_chset<int> s;
s.set(3, 3);
s.set(1, 5);
BOOST_TEST(s.test(5));
}
///////////////////////////////////////////////////////////////////////////////
//
// sf_bug_742038
//
// see http://sf.net/tracker/
// ?func=detail&atid=393386&aid=742038&group_id=28447
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/classic_file_iterator.hpp>
#include <string>
#include <fstream>
#include <iostream>
#include <boost/detail/lightweight_test.hpp>
#include <stdio.h>
template <typename IterT>
void test_assign(IterT b, IterT e)
{
typedef scanner<IterT> scanner_t;
#if (defined(__GNUC__) && defined(__MINGW32__)) \
|| (defined(__GNUC__) && (__GNUC_MINOR__ < 20))
// There's a bug in g++3.x on MinGW that makes basic_string assert
// when assigning from IterT [f, l) where IterT is a position_iterator.
// This issue is discussed here:
//
// http://gcc.gnu.org/ml/libstdc++/2002-03/msg00196.html
//
// Aparently, this bug is only present on MinGW. I'm clueless as
// to why this is so. Regressions on linux seem to be OK! :(
//
// With, g++3.1, assigning to basic_string from IterT [f, l) is a
// compile error (a g++3.1 bug).
//
// In both cases above, we use a vector instead of a string.
typedef std::vector<char> store;
#else
typedef std::string store;
#endif
store dst;
rule<scanner_t> r = (*alpha_p)[assign_a(dst)];
parse(b, e, r);
store::iterator d = dst.begin();
while (b != e)
{
if (*d != *b)
BOOST_TEST(*d == *b);
++b;
++d;
}
}
void sf_bug_742038()
{
std::string src = "abcdef";
const char* tmpfilename = "sf_bug_742038.tmp";
test_assign(src.begin(), src.end());
position_iterator<std::string::iterator> b(src.begin(), src.end(), "");
position_iterator<std::string::iterator> e;
test_assign(b, e);
std::fstream f(tmpfilename, std::ios::out);
f << src;
f.close();
file_iterator<> b1(tmpfilename);
file_iterator<> e1(b1.make_end());
test_assign(b1, e1);
::remove(tmpfilename);
}
///////////////////////////////////////////////////////////////////////////////
//
// bug_009
//
// limit_d bug
// http://article.gmane.org/gmane.comp.parsers.spirit.devel/1891/
//
///////////////////////////////////////////////////////////////////////////////
void
bug_009()
{
parse(
"test"
, limit_d(1U, 10U)[uint_p] | str_p("test"));
}
int
main()
{
bug_001();
bug_002();
bug_003();
bug_004();
bug_005();
bug_006();
bug_007();
bug_009();
sf_bug_718903();
sf_bug_719322();
sf_bug_742038();
return boost::report_errors();
}
| 28.562842 | 81 | 0.51741 | [
"vector"
] |
f69ddeaa1fa0b3c6e5838b113df051e617d7a52d | 2,032 | cxx | C++ | pi_14_parvec_omp_for_avx2.cxx | cmbrandt/using-openmp | 6260592d06856722ae315338b844cff86e4bfc21 | [
"MIT"
] | null | null | null | pi_14_parvec_omp_for_avx2.cxx | cmbrandt/using-openmp | 6260592d06856722ae315338b844cff86e4bfc21 | [
"MIT"
] | null | null | null | pi_14_parvec_omp_for_avx2.cxx | cmbrandt/using-openmp | 6260592d06856722ae315338b844cff86e4bfc21 | [
"MIT"
] | null | null | null | // pi_14_parvec_omp_for_avx2.cxx
// Compile:
// g++ -Wall -pedantic -std=c++17 -fopenmp -mavx2 -mfma -O3 pi_14_parvec_omp_for_avx2.cxx -o pi_14.exe
// Usage:
// ./pi_14.exe
#include <iostream>
#include <vector>
#include <immintrin.h>
#include <omp.h>
double pi_14_parvec_omp_for_avx2(int num_steps)
{
int num_thrds = omp_get_max_threads();
std::vector<double> sum(num_thrds, 0.0);
#pragma omp parallel \
default (none) \
shared (sum) \
firstprivate (num_steps, num_thrds)
{
int id = omp_get_thread_num();
double step_size = 1.0 / num_steps;
double one = 1.0;
double four = 4.0;
__m256d vcoef = _mm256_set_pd(0.5, 1.5, 2.5, 3.5);
__m256d vone = _mm256_broadcast_sd(&one);
__m256d vfour = _mm256_broadcast_sd(&four);
__m256d vstep = _mm256_broadcast_sd(&step_size);
__m256d vsum = _mm256_setzero_pd();
#pragma omp for
for (int i = 0; i < num_steps; i += 4) {
double idx = static_cast<double>(i);
__m256d vidx = _mm256_broadcast_sd(&idx);
__m256d vx = _mm256_mul_pd(_mm256_add_pd(vidx, vcoef), vstep);
__m256d vden = _mm256_fmadd_pd(vx, vx, vone);
vsum = _mm256_add_pd(_mm256_div_pd(vfour, vden), vsum);
}
__m128d vl = _mm256_castpd256_pd128(vsum);
__m128d vh = _mm256_extractf128_pd(vsum, 1);
vl = _mm_add_pd(vl, vh);
__m128d h64 = _mm_unpackhi_pd(vl, vl);
sum[id] = _mm_cvtsd_f64(_mm_add_sd(vl, h64)) * step_size;
}
double pi = 0.0;
for (int i = 0; i < num_thrds; ++i)
pi = pi + sum[i];
return pi;
}
int main()
{
int num_steps = 1024*1024*1024;
int max_thrds = omp_get_max_threads();
double start_time = omp_get_wtime();
double pi = pi_14_parvec_omp_for_avx2(num_steps);
double stop_time = omp_get_wtime();
std::cout << "\nthreads: " << max_thrds
<< "\nsteps: " << num_steps
<< "\npi: " << pi
<< "\ntime: " << stop_time - start_time << std::endl;
}
| 25.4 | 105 | 0.612697 | [
"vector"
] |
f69ee32990d944caacd126ca31c5334833b7d8c8 | 8,888 | cpp | C++ | src/tests/functional/plugin/gna/pass_tests/convert_dwsc_to_scaleshifts.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/tests/functional/plugin/gna/pass_tests/convert_dwsc_to_scaleshifts.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/tests/functional/plugin/gna/pass_tests/convert_dwsc_to_scaleshifts.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include "common_test_utils/test_common.hpp"
#include <string>
#include <sstream>
#include <fstream>
#include <memory>
#include <queue>
#include <map>
#include "transformations/init_node_info.hpp"
#include "ngraph_functions/builders.hpp"
#include "shared_test_classes/base/layer_test_utils.hpp"
using namespace ngraph;
using namespace ngraph::opset7;
namespace LayerTestsDefinitions {
enum class modelType {
TranspDWSCTransp = 0, /* Transpose(NHWC->NCHW) => DWSC (Group Convolution) => Transpose(NCHW->NHWC) */
TranspDWSCBiasTransp, /* Transpose(NHWC->NCHW) => DWSC => Broadcasted Add (Bias) => Transpose(NCHW->NHWC) */
};
typedef std::tuple<
InferenceEngine::SizeVector, // Kernel size
InferenceEngine::SizeVector, // Strides
std::vector<ptrdiff_t>, // Pad begin
std::vector<ptrdiff_t>, // Pad end
InferenceEngine::SizeVector, // Dilation
op::PadType, // Padding type
size_t, // Num out channels
size_t, // Num groups
InferenceEngine::SizeVector // Bias
> DWSCParams;
typedef std::tuple<
DWSCParams, // DWSC and bias parameters
InferenceEngine::Precision, // Network Precision
std::string, // Target Device
std::map<std::string, std::string>, // Configuration
InferenceEngine::SizeVector, // Input shapes
modelType // Test model
> DWSCToScaleShiftsParams;
class DWSCToScaleShiftsTest : public testing::WithParamInterface<DWSCToScaleShiftsParams>,
virtual public LayerTestsUtils::LayerTestsCommon {
public:
static std::string getTestCaseName(testing::TestParamInfo<DWSCToScaleShiftsParams> obj) {
DWSCParams params;
InferenceEngine::Precision netPrecision;
std::string targetDevice;
std::map<std::string, std::string> configuration;
InferenceEngine::SizeVector inputShape;
modelType model;
std::tie(params, netPrecision, targetDevice, configuration, inputShape, model) = obj.param;
op::PadType padType;
InferenceEngine::SizeVector filter, stride, dilation, bias;
std::vector<ptrdiff_t> padBegin, padEnd;
size_t numOutChannels, numGroups;
std::tie(filter, stride, padBegin, padEnd, dilation, padType, numOutChannels, numGroups, bias) = params;
std::ostringstream result;
result << "M=" << static_cast<uint32_t>(model) << "_";
result << "IS=" << CommonTestUtils::vec2str(inputShape) << "_";
result << "K" << CommonTestUtils::vec2str(filter) << "_";
result << "S" << CommonTestUtils::vec2str(stride) << "_";
result << "PB" << CommonTestUtils::vec2str(padBegin) << "_";
result << "PE" << CommonTestUtils::vec2str(padEnd) << "_";
result << "D=" << CommonTestUtils::vec2str(dilation) << "_";
result << "O=" << numOutChannels << "_";
result << "AP=" << padType << "_";
result << "B=" << CommonTestUtils::vec2str(bias) << "_";
result << "netPRC=" << netPrecision.name() << "_";
result << "targetDevice=" << targetDevice << "_";
for (auto const& configItem : configuration) {
result << "_configItem=" << configItem.first << "_" << configItem.second;
}
return result.str();
}
protected:
void SetUp() override {
threshold = 0.05f;
DWSCParams params;
InferenceEngine::Precision netPrecision;
std::vector<size_t> inputShape;
modelType model;
std::tie(params, netPrecision, targetDevice, configuration, inputShape, model) = this->GetParam();
op::PadType padType;
InferenceEngine::SizeVector filter, stride, dilation, bias;
std::vector<ptrdiff_t> padBegin, padEnd;
size_t numOutChannels, numGroups;
std::tie(filter, stride, padBegin, padEnd, dilation, padType, numOutChannels, numGroups, bias) = params;
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision);
auto input = builder::makeParams(ngPrc, {inputShape});
auto transposeInOrder = op::Constant::create(element::i64, Shape{4}, {0, 3, 1, 2});
auto transposeIn = std::make_shared<Transpose>(input[0], transposeInOrder);
auto filterSize = std::accumulate(std::begin(filter), std::end(filter), 1ull, std::multiplies<size_t>());
auto filterWeights = CommonTestUtils::generate_float_numbers(numOutChannels * (inputShape[3] / numGroups) * filterSize, -0.5f, 0.5f);
auto dwsc = builder::makeGroupConvolution(transposeIn, ngPrc, filter, stride, padBegin,
padEnd, dilation, padType, numOutChannels, numGroups, false, filterWeights);
auto transposeOutOrder = op::Constant::create(element::i64, Shape{4}, {0, 2, 3, 1});
auto lastOp = std::make_shared<Transpose>(dwsc, transposeOutOrder);
if (model == modelType::TranspDWSCBiasTransp) {
Shape biasShape{bias};
auto biasWeights = CommonTestUtils::generate_float_numbers(shape_size(biasShape), -1.0f, 1.0f);
auto biasConst = std::make_shared<Constant>(ngPrc, biasShape, biasWeights);
auto bias = std::make_shared<Add>(dwsc, biasConst);
lastOp = std::make_shared<Transpose>(bias, transposeOutOrder);
}
auto result = std::make_shared<Result>(lastOp);
function = std::make_shared<Function>(ResultVector{result}, ParameterVector{input});
}
};
TEST_P(DWSCToScaleShiftsTest, CompareWithRefs) {
Run();
}
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16
};
const std::vector<std::map<std::string, std::string>> configs = {
{
{"GNA_DEVICE_MODE", "GNA_SW_EXACT"},
{"GNA_SCALE_FACTOR_0", "1"},
{"GNA_PWL_UNIFORM_DESIGN", "NO"}
},
{
{"GNA_DEVICE_MODE", "GNA_SW_EXACT"},
{"GNA_SCALE_FACTOR_0", "1"},
{"GNA_PWL_UNIFORM_DESIGN", "YES"}
}
};
const std::vector<op::PadType> padTypes = {
op::PadType::VALID,
op::PadType::EXPLICIT,
op::PadType::SAME_LOWER,
op::PadType::SAME_UPPER
};
const std::vector<modelType> models = {
modelType::TranspDWSCTransp,
modelType::TranspDWSCBiasTransp
};
const std::vector<std::vector<size_t>> inputNHWC = {{1, 1, 5, 32}};
const std::vector<std::vector<size_t >> filters = {{1, 3}};
const std::vector<std::vector<size_t >> strides = {{1, 1}, {1, 2}};
const std::vector<std::vector<ptrdiff_t>> padBegins = {{0, 1}, {0, 2}};
const std::vector<std::vector<ptrdiff_t>> padEnds = {{0, 1}};
const std::vector<std::vector<size_t >> dilations = {{1, 1}};
const std::vector<size_t> numOutChannels = {32};
const std::vector<size_t> numGroups = {32};
const std::vector<std::vector<size_t >> biases = {{1, 32, 1, 1}};
const auto convParams = ::testing::Combine(
::testing::ValuesIn(filters),
::testing::ValuesIn(strides),
::testing::ValuesIn(padBegins),
::testing::ValuesIn(padEnds),
::testing::ValuesIn(dilations),
::testing::ValuesIn(padTypes),
::testing::ValuesIn(numOutChannels),
::testing::ValuesIn(numGroups),
::testing::ValuesIn(biases)
);
INSTANTIATE_TEST_SUITE_P(smoke_DWSCToScaleShifts, DWSCToScaleShiftsTest,
::testing::Combine(
convParams,
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_GNA),
::testing::ValuesIn(configs),
::testing::ValuesIn(inputNHWC),
::testing::ValuesIn(models)),
DWSCToScaleShiftsTest::getTestCaseName);
/* ============= Strides & Dilations Combination ============= */
const std::vector<op::PadType> padTypesSD = {
op::PadType::VALID,
};
const std::vector<std::vector<size_t>> inputNHWCSD = {{1, 1, 8, 32}};
const std::vector<std::vector<size_t >> dilationsSD = {{1, 1}, {1, 2}};
const auto convParamsSD = ::testing::Combine(
::testing::ValuesIn(filters),
::testing::ValuesIn(strides),
::testing::ValuesIn(padBegins),
::testing::ValuesIn(padEnds),
::testing::ValuesIn(dilationsSD),
::testing::ValuesIn(padTypesSD),
::testing::ValuesIn(numOutChannels),
::testing::ValuesIn(numGroups),
::testing::ValuesIn(biases)
);
INSTANTIATE_TEST_SUITE_P(smoke_DWSCToScaleShiftsStridesDilations, DWSCToScaleShiftsTest,
::testing::Combine(
convParamsSD,
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_GNA),
::testing::ValuesIn(configs),
::testing::ValuesIn(inputNHWCSD),
::testing::ValuesIn(models)),
DWSCToScaleShiftsTest::getTestCaseName);
} // namespace LayerTestsDefinitions
| 40.036036 | 141 | 0.645815 | [
"shape",
"vector",
"model"
] |
f69f47073683d479d5321ed0bb152a6ab67821b7 | 2,696 | cpp | C++ | examples/src/example_access.cpp | cmas1/HolorLib | bb62dc738298b7e229a1965a5bfc206395f68b88 | [
"MIT"
] | 1 | 2022-01-20T12:48:36.000Z | 2022-01-20T12:48:36.000Z | examples/src/example_access.cpp | cmas1/HolorLib | bb62dc738298b7e229a1965a5bfc206395f68b88 | [
"MIT"
] | null | null | null | examples/src/example_access.cpp | cmas1/HolorLib | bb62dc738298b7e229a1965a5bfc206395f68b88 | [
"MIT"
] | null | null | null | // This file is part of Holor, a C++ header-only template library for multi-dimensional containers
// Copyright 2020-2022 Carlo Masone
// 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 <holor/holor_full.h>
#include <iostream>
#include <vector>
#include <array>
using namespace holor;
int main(){
Holor<int, 3> A{{{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}, {{12, 13, 14, 15}, {16, 17, 18, 19}, {20, 21, 22, 23}}};
std::cout << " Holor<int, 3> A{{{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}, {{12, 13, 14, 15}, {16, 17, 18, 19}, {20, 21, 22, 23}}}; \n";
std::cout << "A = " << A << "\n\n";
//an Holor can be accessed element by element
std::cout << "A(0,1,2) = " << A(0,1,2) << "\n";
std::cout << "A(std::vector<size_t>{0,1,2}) = " << A(std::vector<size_t>{0,1,2}) << "\n";
std::cout << "A(std::array<size_t,3>{0,1,2}) = " << A(std::array<size_t,3>{0,1,2}) << "\n\n";
//an Holor can be sliced ...
std::cout << "A(range(0,1), range(1,2), range(2,3)) = "<< A(range(0,1), range(1,2), range(2,3)) << "\n";
std::cout << "A(0, range(0,1), range(2,3)) = "<< A(0, range(0,1), range(2,3)) << "\n\n";
//... and the slice can be accessed by element or further sliced
auto B = A(0, range(0,1), range(2,3));
std::cout << "B = A(0, range(0,1), range(2,3)) => "<< B << "\n";
std::cout << "B(std::vector<size_t>{1,1} = "<< B(std::vector<size_t>{1,1}) << "\n\n";
//there are other functions that allow to slice an Holor
std::cout << "A.row(0) = "<< A.row(0) << "\n";
std::cout << "A.col(1) = "<< A.col(1) << "\n";
std::cout << "A.slice<2>(3) = "<< A.slice<2>(3) << "\n\n";
return 0;
} | 42.125 | 142 | 0.609792 | [
"vector"
] |
f6a09625a8554c1fc7af57552ce3634969addc66 | 592 | hxx | C++ | other/cpp/problems/algorithm/1twosum/cpp/twosum.hxx | sguzman/LeetCode | 83cd945949cdbcafec91045d87e30549feb181f1 | [
"MIT"
] | null | null | null | other/cpp/problems/algorithm/1twosum/cpp/twosum.hxx | sguzman/LeetCode | 83cd945949cdbcafec91045d87e30549feb181f1 | [
"MIT"
] | null | null | null | other/cpp/problems/algorithm/1twosum/cpp/twosum.hxx | sguzman/LeetCode | 83cd945949cdbcafec91045d87e30549feb181f1 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <unordered_map>
using std::vector;
using std::unordered_map;
class Solution {
public:
vector<int> twoSum(const vector<int>& nums, const int target) {
unordered_map<int,int> sums;
vector<int> result{2, 1};
for (unsigned int idx{}; idx < nums.size(); ++idx) {
if (sums.find(nums[idx]) == sums.cend()) {
sums.insert({target - nums[idx], static_cast<int>(idx)});
} else {
result[0] = sums[nums[idx]] + 1;
result[1] = static_cast<int>(idx) + 1;
break;
}
}
return result;
}
};
| 19.733333 | 65 | 0.58277 | [
"vector"
] |
f6a10dc06033c505553cdd08fbbaae2ceacfc0de | 6,491 | cpp | C++ | src/model_Skeleton.cpp | dimtziwnas/HandObjectInteractionIJCV16_HandMotionViewer | 9d8bb450d32c17eecf09ea4ab6ab98e26698f119 | [
"MIT"
] | 11 | 2017-01-26T01:46:57.000Z | 2020-11-09T00:06:08.000Z | src/model_Skeleton.cpp | cvlabbonn/hands_3d_motion_viewer | f7d45f123e5ed4b60e68515268e27d00504d8f87 | [
"MIT"
] | null | null | null | src/model_Skeleton.cpp | cvlabbonn/hands_3d_motion_viewer | f7d45f123e5ed4b60e68515268e27d00504d8f87 | [
"MIT"
] | 3 | 2015-10-05T22:48:34.000Z | 2018-06-28T11:50:14.000Z | #include "model.h"
void Model::readSkeleton( QString myFileString_Skeleton )
{
QFile myFile (myFileString_Skeleton );
myFile.open(QIODevice::ReadOnly);
if( !myFile.isOpen() )
{
ErrorManager::error(3, myFileString_Skeleton);
return;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
QTextStream myInputFileToString(&myFile);
QStringList myStringListFromFile;
QString myStringFromFile;
myStringFromFile = myInputFileToString.readAll();
QRegExp koftis("\r\n");
myStringListFromFile = myStringFromFile.split(koftis, QString::SkipEmptyParts);
int length = myStringListFromFile.length();
totalSkeletonFrames = myStringListFromFile.at(0).toInt();
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
totalBones = (length-1) / 3;
//////////////////////////////////
skeleton.bones.clear();
skeleton.bones.resize(totalBones);
//////////////////////////////////
int counter = 0;
skeleton.bones[0].fatherAddress = -888;
for (int i=1; i<length; i+=3)
{
skeleton.bones[counter].fatherName = myStringListFromFile.at(i+0);
skeleton.bones[counter].name = myStringListFromFile.at(i+1);
skeleton.bones[counter].length = myStringListFromFile.at(i+2).toDouble();
skeleton.bones[counter].addressSeListaBones = counter;
skeleton.bones[counter].addressSeListaSKINNING = -1;
skeleton.bones[counter].isUsedForSkinning = false;
for (int k=0; k<totalBones; k++)
{
if (skeleton.bones[k].name != "NULL")
{
if (skeleton.bones[k].name == skeleton.bones[counter].fatherName)
skeleton.bones[counter].fatherAddress = k;
}
}
\
int fatherAdd = skeleton.bones[counter].fatherAddress;
if (fatherAdd > -1)
{
skeleton.bones[ fatherAdd ].childrenVector.append(i/3);
}
counter++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Model::print_SkeletonBones()
{
std::cout << "totalSkeletonFrames -\t" << totalSkeletonFrames << std::endl << std::endl;
for (int i=0; i<totalBones; i++)
{
std::cout << i << "\t\t" << skeleton.bones[i].name.toStdString() << "\t\t" << skeleton.bones[i].fatherName.toStdString() << "\t\t" << skeleton.bones[i].length << std::endl;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 58.477477 | 289 | 0.20644 | [
"model"
] |
f6a4adfa848da19c7d87fda2ec243b38a8d951f5 | 18,633 | cpp | C++ | src/main/cpp/driver/ps_navi_controller.cpp | morrky89/PSMoveSteamVRBridge | 03d29b14d1738597523bd059d30736cb0d075d37 | [
"Apache-2.0"
] | 147 | 2017-03-28T21:32:25.000Z | 2022-01-03T14:43:58.000Z | src/main/cpp/driver/ps_navi_controller.cpp | morrky89/PSMoveSteamVRBridge | 03d29b14d1738597523bd059d30736cb0d075d37 | [
"Apache-2.0"
] | 129 | 2017-04-01T20:34:52.000Z | 2021-04-06T07:34:49.000Z | src/main/cpp/driver/ps_navi_controller.cpp | morrky89/PSMoveSteamVRBridge | 03d29b14d1738597523bd059d30736cb0d075d37 | [
"Apache-2.0"
] | 53 | 2017-03-29T19:31:40.000Z | 2022-03-13T11:38:23.000Z | #define _USE_MATH_DEFINES
#include "constants.h"
#include "server_driver.h"
#include "utils.h"
#include "settings_util.h"
#include "driver.h"
#include "facing_handsolver.h"
#include "ps_navi_controller.h"
#include "trackable_device.h"
#include <assert.h>
#if _MSC_VER
#define strcasecmp(a, b) stricmp(a,b)
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': snprintf
#define snprintf _snprintf
#endif
namespace steamvrbridge {
// -- PSNaviControllerConfig -----
configuru::Config PSNaviControllerConfig::WriteToJSON() {
configuru::Config &pt= ControllerConfig::WriteToJSON();
// General Settings
pt["thumbstick_deadzone"] = thumbstick_deadzone;
//PSMove controller button -> fake touchpad mappings
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_PS);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Left);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Up);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Right);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Down);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Circle);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Cross);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Joystick);
WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Shoulder);
return pt;
}
bool PSNaviControllerConfig::ReadFromJSON(const configuru::Config &pt) {
if (!ControllerConfig::ReadFromJSON(pt))
return false;
// General Settings
thumbstick_deadzone = pt.get_or<float>("thumbstick_deadzone", thumbstick_deadzone);
// DS4 controller button -> fake touchpad mappings
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_PS);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Left);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Up);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Right);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Down);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Circle);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Cross);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Joystick);
ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Shoulder);
return true;
}
// -- PSNaviController -----
PSNaviController::PSNaviController(
PSMControllerID psmControllerId,
vr::ETrackedControllerRole trackedControllerRole,
const char *psmSerialNo)
: Controller()
, m_parentController(nullptr)
, m_nPSMControllerId(psmControllerId)
, m_PSMServiceController(nullptr)
, m_nPoseSequenceNumber(0)
, m_resetPoseButtonPressTime()
, m_bResetPoseRequestSent(false)
, m_resetAlignButtonPressTime()
, m_bResetAlignRequestSent(false)
, m_touchpadDirectionsUsed(false)
, m_lastSanitizedThumbstick_X(0.f)
, m_lastSanitizedThumbstick_Y(0.f) {
char svrIdentifier[256];
Utils::GenerateControllerSteamVRIdentifier(svrIdentifier, sizeof(svrIdentifier), psmControllerId);
m_strSteamVRSerialNo = svrIdentifier;
m_lastTouchpadPressTime = std::chrono::high_resolution_clock::now();
if (psmSerialNo != NULL) {
m_strPSMControllerSerialNo = psmSerialNo;
}
// Tell PSM Client API that we are listening to this controller id
PSM_AllocateControllerListener(psmControllerId);
m_PSMServiceController = PSM_GetController(psmControllerId);
m_TrackedControllerRole = trackedControllerRole;
m_trackingStatus = vr::TrackingResult_Running_OK;
}
PSNaviController::~PSNaviController() {
PSM_FreeControllerListener(m_PSMServiceController->ControllerID);
m_PSMServiceController = nullptr;
}
void PSNaviController::AttachToController(Controller *parent_controller)
{
if (m_unSteamVRTrackedDeviceId == vr::k_unTrackedDeviceIndexInvalid)
{
// Use our parent's property container for registering buttons and axes
m_parentController= parent_controller;
m_ulPropertyContainer = parent_controller->getPropertyContainerHandle();
PSMRequestID requestId;
if (PSM_StartControllerDataStreamAsync(
m_PSMServiceController->ControllerID,
PSMStreamFlags_includePositionData | PSMStreamFlags_includePhysicsData,
&requestId) != PSMResult_Error) {
PSM_RegisterCallback(requestId, PSNaviController::start_controller_response_callback, this);
}
}
else
{
Logger::Error("PSNaviController::AttachToController() - Can't attach PSNavi(%s) since it's already been Activated!",
m_strPSMControllerSerialNo.c_str());
}
}
vr::EVRInitError PSNaviController::Activate(vr::TrackedDeviceIndex_t unObjectId) {
vr::EVRInitError result = Controller::Activate(unObjectId);
if (m_parentController != nullptr) {
Logger::Error("PSNaviController::AttachToController() - Can't Activate PSNavi(%s) since it's already been attached to %s!",
m_strPSMControllerSerialNo.c_str(), m_parentController->GetPSMControllerSerialNo().c_str());
return vr::VRInitError_Driver_Failed;
}
if (result == vr::VRInitError_None) {
Logger::Info("PSNaviController::Activate - Controller %d Activated\n", unObjectId);
PSMRequestID requestId;
if (PSM_StartControllerDataStreamAsync(
m_PSMServiceController->ControllerID,
PSMStreamFlags_includePositionData | PSMStreamFlags_includePhysicsData,
&requestId) != PSMResult_Error) {
PSM_RegisterCallback(requestId, PSNaviController::start_controller_response_callback, this);
}
// Setup controller properties
{
vr::CVRPropertyHelpers *properties = vr::VRProperties();
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceOff_String, "{psmove}psnavi_status_off.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceSearching_String, "{psmove}psnavi_status_ready.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{psmove}psnavi_status_ready_alert.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceReady_String, "{psmove}psnavi_status_ready.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{psmove}psnavi_status_ready_alert.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceNotReady_String, "{psmove}psnavi_status_error.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceStandby_String, "{psmove}psnavi_status_ready.png");
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceAlertLow_String, "{psmove}psnavi_status_ready_low.png");
properties->SetBoolProperty(m_ulPropertyContainer, vr::Prop_WillDriftInYaw_Bool, false);
properties->SetBoolProperty(m_ulPropertyContainer, vr::Prop_DeviceIsWireless_Bool, true);
properties->SetBoolProperty(m_ulPropertyContainer, vr::Prop_DeviceProvidesBatteryStatus_Bool, false);
properties->SetInt32Property(m_ulPropertyContainer, vr::Prop_DeviceClass_Int32, vr::TrackedDeviceClass_Controller);
// The {psmove} syntax lets us refer to rendermodels that are installed
// in the driver's own resources/rendermodels directory. The driver can
// still refer to SteamVR models like "generic_hmd".
if (getConfig()->override_model.length() > 0)
{
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_RenderModelName_String, getConfig()->override_model.c_str());
}
else
{
properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_RenderModelName_String, "{psmove}navi_controller");
}
// Set device properties
vr::VRProperties()->SetInt32Property(m_ulPropertyContainer, vr::Prop_ControllerRoleHint_Int32, m_TrackedControllerRole);
vr::VRProperties()->SetStringProperty(m_ulPropertyContainer, vr::Prop_ManufacturerName_String, "Sony");
vr::VRProperties()->SetUint64Property(m_ulPropertyContainer, vr::Prop_HardwareRevision_Uint64, 1313);
vr::VRProperties()->SetUint64Property(m_ulPropertyContainer, vr::Prop_FirmwareVersion_Uint64, 1315);
vr::VRProperties()->SetStringProperty(m_ulPropertyContainer, vr::Prop_ModelNumber_String, "PS Navi");
vr::VRProperties()->SetStringProperty(m_ulPropertyContainer, vr::Prop_SerialNumber_String, m_strPSMControllerSerialNo.c_str());
}
}
return result;
}
void PSNaviController::start_controller_response_callback(
const PSMResponseMessage *response, void *userdata) {
PSNaviController *controller = reinterpret_cast<PSNaviController *>(userdata);
if (response->result_code == PSMResult::PSMResult_Success) {
Logger::Info("PSNaviController::start_controller_response_callback - Controller stream started\n");
// Create the special case system button (bound to PS button)
controller->CreateButtonComponent(k_PSMButtonID_System);
// Create buttons components
controller->CreateButtonComponent(k_PSMButtonID_PS);
controller->CreateButtonComponent(k_PSMButtonID_Circle);
controller->CreateButtonComponent(k_PSMButtonID_Cross);
controller->CreateButtonComponent(k_PSMButtonID_DPad_Up);
controller->CreateButtonComponent(k_PSMButtonID_DPad_Down);
controller->CreateButtonComponent(k_PSMButtonID_DPad_Left);
controller->CreateButtonComponent(k_PSMButtonID_DPad_Right);
controller->CreateButtonComponent(k_PSMButtonID_Shoulder);
controller->CreateButtonComponent(k_PSMButtonID_Joystick);
// Create axis components
controller->CreateAxisComponent(k_PSMAxisID_Trigger);
controller->CreateAxisComponent(k_PSMAxisID_Joystick_X);
controller->CreateAxisComponent(k_PSMAxisID_Joystick_Y);
// [optional] Create components for emulated trackpad
controller->CreateButtonComponent(k_PSMButtonID_EmulatedTrackpadTouched);
controller->CreateButtonComponent(k_PSMButtonID_EmulatedTrackpadPressed);
controller->CreateAxisComponent(k_PSMAxisID_EmulatedTrackpad_X);
controller->CreateAxisComponent(k_PSMAxisID_EmulatedTrackpad_Y);
}
}
void PSNaviController::Deactivate() {
Logger::Info("PSNaviController::Deactivate - Controller stream stopped\n");
PSM_StopControllerDataStreamAsync(m_PSMServiceController->ControllerID, nullptr);
Controller::Deactivate();
}
void PSNaviController::UpdateControllerState() {
static const uint64_t s_kTouchpadButtonMask = vr::ButtonMaskFromId(vr::k_EButton_SteamVR_Touchpad);
assert(m_PSMServiceController != nullptr);
assert(m_PSMServiceController->IsConnected);
const PSMPSNavi &clientView = m_PSMServiceController->ControllerState.PSNaviState;
// System Button hard-coded to PS button
Controller::UpdateButton(k_PSMButtonID_System, clientView.PSButton);
// Process all the native buttons
Controller::UpdateButton(k_PSMButtonID_PS, clientView.PSButton);
Controller::UpdateButton(k_PSMButtonID_Circle, clientView.CircleButton);
Controller::UpdateButton(k_PSMButtonID_Cross, clientView.CrossButton);
Controller::UpdateButton(k_PSMButtonID_DPad_Up, clientView.DPadUpButton);
Controller::UpdateButton(k_PSMButtonID_DPad_Down, clientView.DPadDownButton);
Controller::UpdateButton(k_PSMButtonID_DPad_Left, clientView.DPadLeftButton);
Controller::UpdateButton(k_PSMButtonID_DPad_Right, clientView.DPadRightButton);
Controller::UpdateButton(k_PSMButtonID_Shoulder, clientView.L2Button);
Controller::UpdateButton(k_PSMButtonID_Joystick, clientView.L3Button);
// Thumbstick handling
UpdateThumbstick();
// Touchpad handling
UpdateEmulatedTrackpad();
// Trigger handling
Controller::UpdateAxis(k_PSMAxisID_Trigger, clientView.TriggerValue / 255.f);
}
void PSNaviController::UpdateThumbstick()
{
const PSMPSNavi &clientView = m_PSMServiceController->ControllerState.PSNaviState;
const unsigned char rawThumbStickX = clientView.Stick_XAxis;
const unsigned char rawThumbStickY = clientView.Stick_YAxis;
const float thumb_stick_x = ((float)rawThumbStickX - 127.f) / 127.f;
const float thumb_stick_y = ((float)rawThumbStickY - 127.f) / 127.f;
const float thumb_stick_radius = sqrtf(thumb_stick_x*thumb_stick_x + thumb_stick_y * thumb_stick_y);
// Moving a thumb-stick outside of the deadzone is consider a touchpad touch
if (thumb_stick_radius >= getConfig()->thumbstick_deadzone)
{
// Rescale the thumb-stick position to hide the dead zone
const float rescaledRadius = (thumb_stick_radius - getConfig()->thumbstick_deadzone) / (1.f - getConfig()->thumbstick_deadzone);
// Set the thumb-stick axis
m_lastSanitizedThumbstick_X = (rescaledRadius / thumb_stick_radius) * thumb_stick_x;
m_lastSanitizedThumbstick_Y = (rescaledRadius / thumb_stick_radius) * thumb_stick_y;
}
else
{
m_lastSanitizedThumbstick_X= 0.f;
m_lastSanitizedThumbstick_Y= 0.f;
}
Controller::UpdateAxis(k_PSMAxisID_Joystick_X, m_lastSanitizedThumbstick_X);
Controller::UpdateAxis(k_PSMAxisID_Joystick_Y, m_lastSanitizedThumbstick_Y);
}
// Updates the state of the controllers touchpad axis relative to its position over time and active state.
void PSNaviController::UpdateEmulatedTrackpad() {
// Bail if the config hasn't enabled the emulated trackpad
if (!HasButton(k_PSMButtonID_EmulatedTrackpadPressed) && !HasButton(k_PSMButtonID_EmulatedTrackpadPressed))
return;
// Find the highest priority emulated touch pad action (if any)
eEmulatedTrackpadAction highestPriorityAction= k_EmulatedTrackpadAction_None;
for (int buttonIndex = 0; buttonIndex < static_cast<int>(k_PSMButtonID_Count); ++buttonIndex) {
eEmulatedTrackpadAction action= getConfig()->ps_button_id_to_emulated_touchpad_action[buttonIndex];
if (action != k_EmulatedTrackpadAction_None) {
PSMButtonState button_state= PSMButtonState_UP;
if (Controller::GetButtonState((ePSMButtonID)buttonIndex, button_state)) {
if (button_state == PSMButtonState_DOWN || button_state == PSMButtonState_PRESSED) {
if (action >= highestPriorityAction) {
highestPriorityAction= action;
}
if (action >= k_EmulatedTrackpadAction_Press) {
break;
}
}
}
}
}
float touchpad_x = 0.f;
float touchpad_y = 0.f;
PSMButtonState emulatedTouchPadTouchedState= PSMButtonState_UP;
PSMButtonState emulatedTouchPadPressedState= PSMButtonState_UP;
if (highestPriorityAction == k_EmulatedTrackpadAction_Touch)
{
emulatedTouchPadTouchedState= PSMButtonState_DOWN;
}
else if (highestPriorityAction == k_EmulatedTrackpadAction_Press)
{
emulatedTouchPadTouchedState= PSMButtonState_DOWN;
emulatedTouchPadPressedState= PSMButtonState_DOWN;
}
if (highestPriorityAction != k_EmulatedTrackpadAction_None)
{
emulatedTouchPadTouchedState= PSMButtonState_DOWN;
emulatedTouchPadPressedState= PSMButtonState_DOWN;
// If the action specifies a specific trackpad direction,
// then use the given trackpad axis
switch (highestPriorityAction)
{
case k_EmulatedTrackpadAction_Touch:
case k_EmulatedTrackpadAction_Press:
touchpad_x= 0.f;
touchpad_y= 0.f;
break;
case k_EmulatedTrackpadAction_Left:
touchpad_x= -1.f;
touchpad_y= 0.f;
break;
case k_EmulatedTrackpadAction_Up:
touchpad_x= 0.f;
touchpad_y= 1.f;
break;
case k_EmulatedTrackpadAction_Right:
touchpad_x= 1.f;
touchpad_y= 0.f;
break;
case k_EmulatedTrackpadAction_Down:
touchpad_x= 0.f;
touchpad_y= -1.f;
break;
case k_EmulatedTrackpadAction_UpLeft:
touchpad_x = -0.707f;
touchpad_y = 0.707f;
break;
case k_EmulatedTrackpadAction_UpRight:
touchpad_x = 0.707f;
touchpad_y = 0.707f;
break;
case k_EmulatedTrackpadAction_DownLeft:
touchpad_x = -0.707f;
touchpad_y = -0.707f;
break;
case k_EmulatedTrackpadAction_DownRight:
touchpad_x = 0.707f;
touchpad_y = -0.707f;
break;
}
} else {
// Fallback to using the thumbstick as the touchpad.
// Consider the touchpad pressed if the thumbstick is deflected at all.
const bool bIsTouched= fabsf(m_lastSanitizedThumbstick_X) + fabsf(m_lastSanitizedThumbstick_Y) > 0.f;
if (bIsTouched)
{
emulatedTouchPadTouchedState= PSMButtonState_DOWN;
emulatedTouchPadPressedState= PSMButtonState_DOWN;
touchpad_x= m_lastSanitizedThumbstick_X;
touchpad_y= m_lastSanitizedThumbstick_Y;
}
}
Controller::UpdateButton(k_PSMButtonID_EmulatedTrackpadTouched, emulatedTouchPadTouchedState);
Controller::UpdateButton(k_PSMButtonID_EmulatedTrackpadPressed, emulatedTouchPadPressedState);
Controller::UpdateAxis(k_PSMAxisID_EmulatedTrackpad_X, touchpad_x);
Controller::UpdateAxis(k_PSMAxisID_EmulatedTrackpad_Y, touchpad_y);
}
void PSNaviController::UpdateTrackingState() {
assert(m_PSMServiceController != nullptr);
assert(m_PSMServiceController->IsConnected);
// The tracking status will be one of the following states:
m_Pose.result = m_trackingStatus;
m_Pose.deviceIsConnected = m_PSMServiceController->IsConnected;
// These should always be false from any modern driver. These are for Oculus DK1-like
// rotation-only tracking. Support for that has likely rotted in vrserver.
m_Pose.willDriftInYaw = false;
m_Pose.shouldApplyHeadModel = false;
// No prediction since that's already handled in the psmove service
m_Pose.poseTimeOffset = 0.f;
// No transform due to the current HMD orientation
m_Pose.qDriverFromHeadRotation.w = 1.f;
m_Pose.qDriverFromHeadRotation.x = 0.0f;
m_Pose.qDriverFromHeadRotation.y = 0.0f;
m_Pose.qDriverFromHeadRotation.z = 0.0f;
m_Pose.vecDriverFromHeadTranslation[0] = 0.f;
m_Pose.vecDriverFromHeadTranslation[1] = 0.f;
m_Pose.vecDriverFromHeadTranslation[2] = 0.f;
// Set position
m_Pose.vecPosition[0] = 0.f;
m_Pose.vecPosition[1] = 0.f;
m_Pose.vecPosition[2] = 0.f;
// Set rotational coordinates
m_Pose.qRotation.w = 1.f;
m_Pose.qRotation.x = 0.f;
m_Pose.qRotation.y = 0.f;
m_Pose.qRotation.z = 0.f;
m_Pose.poseIsValid = false;
// This call posts this pose to shared memory, where all clients will have access to it the next
// moment they want to predict a pose.
vr::VRServerDriverHost()->TrackedDevicePoseUpdated(m_unSteamVRTrackedDeviceId, m_Pose, sizeof(vr::DriverPose_t));
}
void PSNaviController::Update() {
Controller::Update();
if (IsActivated() && m_PSMServiceController->IsConnected) {
int seq_num = m_PSMServiceController->OutputSequenceNum;
// Only other updating incoming state if it actually changed and is due for one
if (m_nPoseSequenceNumber < seq_num) {
m_nPoseSequenceNumber = seq_num;
UpdateTrackingState();
UpdateControllerState();
}
}
}
void PSNaviController::RefreshWorldFromDriverPose() {
TrackableDevice::RefreshWorldFromDriverPose();
// Mark the calibration process as done once we have setup the world from driver pose
m_trackingStatus = vr::TrackingResult_Running_OK;
}
} | 39.644681 | 149 | 0.78522 | [
"transform"
] |
f6ab03421060536bb97f49bc17e9ce2e4708af37 | 1,067 | hpp | C++ | src/org/apache/poi/hssf/eventmodel/EventRecordFactory.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/eventmodel/EventRecordFactory.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/eventmodel/EventRecordFactory.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/hssf/eventmodel/EventRecordFactory.java
#pragma once
#include <fwd-POI.hpp>
#include <java/io/fwd-POI.hpp>
#include <org/apache/poi/hssf/eventmodel/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::hssf::eventmodel::EventRecordFactory final
: public ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
ERFListener* _listener { };
::int16_tArray* _sids { };
protected:
void ctor(ERFListener* listener, ::int16_tArray* sids);
private:
bool isSidIncluded(int16_t sid);
bool processRecord(::poi::hssf::record::Record* record);
public:
void processRecords(::java::io::InputStream* in) /* throws(RecordFormatException) */;
// Generated
EventRecordFactory(ERFListener* listener, ::int16_tArray* sids);
protected:
EventRecordFactory(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 23.711111 | 89 | 0.710403 | [
"object"
] |
f6ac5be0297745a1032935843f69fff0a8a57a7b | 473 | cpp | C++ | 0101-0200/0128-Longest Consecutive Sequence/0128-Longest Consecutive Sequence.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 0101-0200/0128-Longest Consecutive Sequence/0128-Longest Consecutive Sequence.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 0101-0200/0128-Longest Consecutive Sequence/0128-Longest Consecutive Sequence.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> table(nums.begin(), nums.end());
int maxLen = 0;
for (int num : nums) {
if (!table.count(num - 1)) {
int nextNum = num + 1;
while (table.count(nextNum)) {
++nextNum;
}
maxLen = max(maxLen, nextNum - num);
}
}
return maxLen;
}
};
| 26.277778 | 59 | 0.44186 | [
"vector"
] |
f6b12c3d74a1d7b084a1c75928536153c4c6b9eb | 14,696 | cpp | C++ | util/system/filemap.cpp | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | null | null | null | util/system/filemap.cpp | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | null | null | null | util/system/filemap.cpp | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 1 | 2022-02-23T13:35:26.000Z | 2022-02-23T13:35:26.000Z | #include "info.h"
#include "madvise.h"
#include "defaults.h"
#include "hi_lo.h"
#include <util/generic/yexception.h>
#include <util/generic/singleton.h>
#if defined(_win_)
#include "winint.h"
#elif defined(_unix_)
#include <sys/types.h>
#include <sys/mman.h>
#if !defined(_linux_)
#ifdef MAP_POPULATE
#error unlisted platform supporting MAP_POPULATE
#endif
#define MAP_POPULATE 0
#endif
#if !defined(_freebsd_)
#ifdef MAP_NOCORE
#error unlisted platform supporting MAP_NOCORE
#endif
#define MAP_NOCORE 0
#endif
#else
#error todo
#endif
#include <util/generic/utility.h>
#include <util/system/sanitizers.h>
#include "filemap.h"
#undef PAGE_SIZE
#undef GRANULARITY
#ifdef _win_
#define MAP_FAILED ((void*)(LONG_PTR)-1)
#endif
namespace {
struct TSysInfo {
inline TSysInfo()
: GRANULARITY_(CalcGranularity())
, PAGE_SIZE_(NSystemInfo::GetPageSize())
{
}
static inline const TSysInfo& Instance() {
return *Singleton<TSysInfo>();
}
static inline size_t CalcGranularity() noexcept {
#if defined(_win_)
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
return sysInfo.dwAllocationGranularity;
#else
return NSystemInfo::GetPageSize();
#endif
}
const size_t GRANULARITY_;
const size_t PAGE_SIZE_;
};
}
#define GRANULARITY (TSysInfo::Instance().GRANULARITY_)
#define PAGE_SIZE (TSysInfo::Instance().PAGE_SIZE_)
TString TMemoryMapCommon::UnknownFileName() {
return "Unknown_file_name";
}
static inline i64 DownToGranularity(i64 offset) noexcept {
return offset & ~((i64)(GRANULARITY - 1));
}
#if defined(_unix_)
static int ModeToMmapFlags(TMemoryMapCommon::EOpenMode mode) {
int flags = MAP_NOCORE;
if ((mode & TMemoryMapCommon::oAccessMask) == TMemoryMapCommon::oCopyOnWr) {
flags |= MAP_PRIVATE;
} else {
flags |= MAP_SHARED;
}
if (mode & TMemoryMapCommon::oPopulate) {
flags |= MAP_POPULATE;
}
return flags;
}
static int ModeToMmapProt(TMemoryMapCommon::EOpenMode mode) {
int prot = PROT_READ;
if ((mode & TMemoryMapCommon::oAccessMask) != TMemoryMapCommon::oRdOnly) {
prot |= PROT_WRITE;
}
return prot;
}
#endif
// maybe we should move this function to another .cpp file to avoid unwanted optimization?
void NPrivate::Precharge(const void* data, size_t dataSize, size_t off, size_t size) {
if (off > dataSize) {
assert(false);
return;
}
size_t endOff = (size == (size_t)-1 ? dataSize : off + size);
if (endOff > dataSize) {
assert(false);
endOff = dataSize;
}
size = endOff - off;
if (dataSize == 0 || size == 0) {
return;
}
volatile const char *c = (const char*)data + off, *e = c + size;
for (; c < e; c += 512) {
*c;
}
}
class TMemoryMap::TImpl: public TAtomicRefCount<TImpl> {
public:
inline void CreateMapping() {
#if defined(_win_)
Mapping_ = nullptr;
if (Length_) {
Mapping_ = CreateFileMapping(File_.GetHandle(), nullptr,
(Mode_ & oAccessMask) == TFileMap::oRdWr ? PAGE_READWRITE : PAGE_READONLY,
(DWORD)(Length_ >> 32), (DWORD)(Length_ & 0xFFFFFFFF), nullptr);
if (Mapping_ == nullptr) {
ythrow yexception() << "Can't create file mapping of '" << DbgName_ << "': " << LastSystemErrorText();
}
} else {
Mapping_ = MAP_FAILED;
}
#elif defined(_unix_)
if (!(Mode_ & oNotGreedy)) {
PtrStart_ = mmap((caddr_t) nullptr, Length_, ModeToMmapProt(Mode_), ModeToMmapFlags(Mode_), File_.GetHandle(), 0);
if ((MAP_FAILED == PtrStart_) && Length_) {
ythrow yexception() << "Can't map " << (unsigned long)Length_ << " bytes of file '" << DbgName_ << "' at offset 0: " << LastSystemErrorText();
}
} else {
PtrStart_ = nullptr;
}
#endif
}
void CheckFile() const {
if (!File_.IsOpen()) {
ythrow yexception() << "TMemoryMap: FILE '" << DbgName_ << "' is not open, " << LastSystemErrorText();
}
if (Length_ < 0) {
ythrow yexception() << "'" << DbgName_ << "' is not a regular file";
}
}
inline TImpl(FILE* f, EOpenMode om, TString dbgName)
: File_(Duplicate(f))
, DbgName_(std::move(dbgName))
, Length_(File_.GetLength())
, Mode_(om)
{
CheckFile();
CreateMapping();
}
inline TImpl(const TString& name, EOpenMode om)
: File_(name, (om & oRdWr) ? OpenExisting | RdWr : OpenExisting | RdOnly)
, DbgName_(name)
, Length_(File_.GetLength())
, Mode_(om)
{
CheckFile();
CreateMapping();
}
inline TImpl(const TString& name, i64 length, EOpenMode om)
: File_(name, (om & oRdWr) ? OpenExisting | RdWr : OpenExisting | RdOnly)
, DbgName_(name)
, Length_(length)
, Mode_(om)
{
CheckFile();
if (File_.GetLength() < Length_) {
File_.Resize(Length_);
}
CreateMapping();
}
inline TImpl(const TFile& file, EOpenMode om, TString dbgName)
: File_(file)
, DbgName_(File_.GetName() ? File_.GetName() : std::move(dbgName))
, Length_(File_.GetLength())
, Mode_(om)
{
CheckFile();
CreateMapping();
}
inline bool IsOpen() const noexcept {
return File_.IsOpen()
#if defined(_win_)
&& Mapping_ != nullptr
#endif
;
}
inline bool IsWritable() const noexcept {
return (Mode_ & oRdWr || Mode_ & oCopyOnWr);
}
inline TMapResult Map(i64 offset, size_t size) {
assert(File_.IsOpen());
if (offset > Length_) {
ythrow yexception() << "Can't map something at offset " << offset << " of '" << DbgName_ << "' with length " << Length_;
}
if (offset + (i64)size > Length_) {
ythrow yexception() << "Can't map " << (unsigned long)size << " bytes at offset " << offset << " of '" << DbgName_ << "' with length " << Length_;
}
TMapResult result;
i64 base = DownToGranularity(offset);
result.Head = (i32)(offset - base);
size += result.Head;
#if defined(_win_)
result.Ptr = MapViewOfFile(Mapping_,
(Mode_ & oAccessMask) == oRdOnly ? FILE_MAP_READ : (Mode_ & oAccessMask) == oCopyOnWr ? FILE_MAP_COPY
: FILE_MAP_WRITE,
Hi32(base), Lo32(base), size);
#else
#if defined(_unix_)
if (Mode_ & oNotGreedy) {
#endif
result.Ptr = mmap((caddr_t) nullptr, size, ModeToMmapProt(Mode_), ModeToMmapFlags(Mode_), File_.GetHandle(), base);
if (result.Ptr == (char*)(-1)) {
result.Ptr = nullptr;
}
#if defined(_unix_)
} else {
result.Ptr = PtrStart_ ? static_cast<caddr_t>(PtrStart_) + base : nullptr;
}
#endif
#endif
if (result.Ptr != nullptr || size == 0) { // allow map of size 0
result.Size = size;
} else {
ythrow yexception() << "Can't map " << (unsigned long)size << " bytes at offset " << offset << " of '" << DbgName_ << "': " << LastSystemErrorText();
}
NSan::Unpoison(result.Ptr, result.Size);
if (Mode_ & oPrecharge) {
NPrivate::Precharge(result.Ptr, result.Size, 0, result.Size);
}
return result;
}
#if defined(_win_)
inline bool Unmap(void* ptr, size_t) {
return ::UnmapViewOfFile(ptr) != FALSE;
}
#else
inline bool Unmap(void* ptr, size_t size) {
#if defined(_unix_)
if (Mode_ & oNotGreedy) {
#endif
return size == 0 || ::munmap(static_cast<caddr_t>(ptr), size) == 0;
#if defined(_unix_)
} else {
return true;
}
#endif
}
#endif
void SetSequential() {
#if defined(_unix_)
if (!(Mode_ & oNotGreedy) && Length_) {
MadviseSequentialAccess(PtrStart_, Length_);
}
#endif
}
void Evict(void* ptr, size_t len) {
MadviseEvict(ptr, len);
}
void Evict() {
#if defined(_unix_)
// Evict(PtrStart_, Length_);
#endif
}
inline ~TImpl() {
#if defined(_win_)
if (Mapping_) {
::CloseHandle(Mapping_); // != FALSE
Mapping_ = nullptr;
}
#elif defined(_unix_)
if (PtrStart_) {
munmap((caddr_t)PtrStart_, Length_);
}
#endif
}
inline i64 Length() const noexcept {
return Length_;
}
inline TFile GetFile() const noexcept {
return File_;
}
inline TString GetDbgName() const {
return DbgName_;
}
inline EOpenMode GetMode() const noexcept {
return Mode_;
}
private:
TFile File_;
TString DbgName_; // This string is never used to actually open a file, only in exceptions
i64 Length_;
EOpenMode Mode_;
#if defined(_win_)
void* Mapping_;
#elif defined(_unix_)
void* PtrStart_;
#endif
};
TMemoryMap::TMemoryMap(const TString& name)
: Impl_(new TImpl(name, EOpenModeFlag::oRdOnly))
{
}
TMemoryMap::TMemoryMap(const TString& name, EOpenMode om)
: Impl_(new TImpl(name, om))
{
}
TMemoryMap::TMemoryMap(const TString& name, i64 length, EOpenMode om)
: Impl_(new TImpl(name, length, om))
{
}
TMemoryMap::TMemoryMap(FILE* f, TString dbgName)
: Impl_(new TImpl(f, EOpenModeFlag::oRdOnly, std::move(dbgName)))
{
}
TMemoryMap::TMemoryMap(FILE* f, EOpenMode om, TString dbgName)
: Impl_(new TImpl(f, om, std::move(dbgName)))
{
}
TMemoryMap::TMemoryMap(const TFile& file, TString dbgName)
: Impl_(new TImpl(file, EOpenModeFlag::oRdOnly, std::move(dbgName)))
{
}
TMemoryMap::TMemoryMap(const TFile& file, EOpenMode om, TString dbgName)
: Impl_(new TImpl(file, om, std::move(dbgName)))
{
}
TMemoryMap::~TMemoryMap() = default;
TMemoryMap::TMapResult TMemoryMap::Map(i64 offset, size_t size) {
return Impl_->Map(offset, size);
}
bool TMemoryMap::Unmap(void* ptr, size_t size) {
return Impl_->Unmap(ptr, size);
}
bool TMemoryMap::Unmap(TMapResult region) {
return Unmap(region.Ptr, region.Size);
}
void TMemoryMap::ResizeAndReset(i64 size) {
EOpenMode om = Impl_->GetMode();
TFile file = GetFile();
file.Resize(size);
Impl_.Reset(new TImpl(file, om, Impl_->GetDbgName()));
}
TMemoryMap::TMapResult TMemoryMap::ResizeAndRemap(i64 offset, size_t size) {
ResizeAndReset(offset + (i64)size);
return Map(offset, size);
}
void TMemoryMap::SetSequential() {
Impl_->SetSequential();
}
void TMemoryMap::Evict(void* ptr, size_t len) {
Impl_->Evict(ptr, len);
}
void TMemoryMap::Evict() {
Impl_->Evict();
}
i64 TMemoryMap::Length() const noexcept {
return Impl_->Length();
}
bool TMemoryMap::IsOpen() const noexcept {
return Impl_->IsOpen();
}
bool TMemoryMap::IsWritable() const noexcept {
return Impl_->IsWritable();
}
TMemoryMap::EOpenMode TMemoryMap::GetMode() const noexcept {
return Impl_->GetMode();
}
TFile TMemoryMap::GetFile() const noexcept {
return Impl_->GetFile();
}
TFileMap::TFileMap(const TMemoryMap& map) noexcept
: Map_(map)
{
}
TFileMap::TFileMap(const TString& name)
: Map_(name)
{
}
TFileMap::TFileMap(const TString& name, EOpenMode om)
: Map_(name, om)
{
}
TFileMap::TFileMap(const TString& name, i64 length, EOpenMode om)
: Map_(name, length, om)
{
}
TFileMap::TFileMap(FILE* f, EOpenMode om, TString dbgName)
: Map_(f, om, dbgName)
{
}
TFileMap::TFileMap(const TFile& file, EOpenMode om, TString dbgName)
: Map_(file, om, dbgName)
{
}
TFileMap::TFileMap(const TFileMap& fm) noexcept
: Map_(fm.Map_)
{
}
void TFileMap::Flush(void* ptr, size_t size, bool sync) {
Y_ASSERT(ptr >= Ptr());
Y_ASSERT(static_cast<char*>(ptr) + size <= static_cast<char*>(Ptr()) + MappedSize());
if (!Region_.IsMapped()) {
return;
}
#if defined(_win_)
if (sync) {
FlushViewOfFile(ptr, size);
}
#else
msync(ptr, size, sync ? MS_SYNC : MS_ASYNC);
#endif
}
TFileMap::TMapResult TFileMap::Map(i64 offset, size_t size) {
Unmap();
Region_ = Map_.Map(offset, size);
return Region_;
}
TFileMap::TMapResult TFileMap::ResizeAndRemap(i64 offset, size_t size) {
// explicit Unmap() is required because in oNotGreedy mode the Map_ object doesn't own the mapped area
Unmap();
Region_ = Map_.ResizeAndRemap(offset, size);
return Region_;
}
void TFileMap::Unmap() {
if (!Region_.IsMapped()) {
return;
}
if (Map_.Unmap(Region_)) {
Region_.Reset();
} else {
ythrow yexception() << "can't unmap file";
}
}
TFileMap::~TFileMap() {
try {
// explicit Unmap() is required because in oNotGreedy mode the Map_ object doesn't own the mapped area
Unmap();
} catch (...) {
// ¯\_(ツ)_/¯
}
}
void TFileMap::Precharge(size_t pos, size_t size) const {
NPrivate::Precharge(Ptr(), MappedSize(), pos, size);
}
TMappedAllocation::TMappedAllocation(size_t size, bool shared, void* addr)
: Ptr_(nullptr)
, Size_(0)
, Shared_(shared)
#if defined(_win_)
, Mapping_(nullptr)
#endif
{
if (size != 0) {
Alloc(size, addr);
}
}
void* TMappedAllocation::Alloc(size_t size, void* addr) {
assert(Ptr_ == nullptr);
#if defined(_win_)
(void)addr;
Mapping_ = CreateFileMapping((HANDLE)-1, nullptr, PAGE_READWRITE, 0, size ? size : 1, nullptr);
Ptr_ = MapViewOfFile(Mapping_, FILE_MAP_WRITE, 0, 0, size ? size : 1);
#else
Ptr_ = mmap(addr, size, PROT_READ | PROT_WRITE, (Shared_ ? MAP_SHARED : MAP_PRIVATE) | MAP_ANON, -1, 0);
if (Ptr_ == (void*)MAP_FAILED) {
Ptr_ = nullptr;
}
#endif
if (Ptr_ != nullptr) {
Size_ = size;
}
return Ptr_;
}
void TMappedAllocation::Dealloc() {
if (Ptr_ == nullptr) {
return;
}
#if defined(_win_)
UnmapViewOfFile(Ptr_);
CloseHandle(Mapping_);
Mapping_ = nullptr;
#else
munmap((caddr_t)Ptr_, Size_);
#endif
Ptr_ = nullptr;
Size_ = 0;
}
void TMappedAllocation::swap(TMappedAllocation& with) {
DoSwap(Ptr_, with.Ptr_);
DoSwap(Size_, with.Size_);
#if defined(_win_)
DoSwap(Mapping_, with.Mapping_);
#endif
}
| 25.121368 | 161 | 0.592474 | [
"object"
] |
f6b18ecb7f2c7d6eecff499a1762b035171edcb0 | 7,032 | cpp | C++ | test/beast/core/flat_stream.cpp | Pandinosaurus/beast | bd5e702c9004f2fff828735676c260972f1cd37d | [
"BSL-1.0"
] | 2,906 | 2017-07-25T18:28:53.000Z | 2022-03-31T16:07:53.000Z | test/beast/core/flat_stream.cpp | Pandinosaurus/beast | bd5e702c9004f2fff828735676c260972f1cd37d | [
"BSL-1.0"
] | 1,712 | 2017-07-25T23:22:10.000Z | 2022-03-31T06:39:46.000Z | Libs/boost_1_76_0/libs/beast/test/beast/core/flat_stream.cpp | Antd23rus/S2DE | 47cc7151c2934cd8f0399a9856c1e54894571553 | [
"MIT"
] | 555 | 2017-07-25T17:53:39.000Z | 2022-03-21T07:27:16.000Z | //
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
// Test that header file is self-contained.
#include <boost/beast/core/flat_stream.hpp>
#include "stream_tests.hpp"
#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <boost/beast/_experimental/test/stream.hpp>
#include <boost/beast/core/role.hpp>
#include <initializer_list>
#include <vector>
#if BOOST_ASIO_HAS_CO_AWAIT
#include <boost/asio/use_awaitable.hpp>
#endif
namespace boost {
namespace beast {
class flat_stream_test : public unit_test::suite
{
public:
void
testMembers()
{
net::io_context ioc;
test_sync_stream<flat_stream<test::stream>>();
test_async_stream<flat_stream<test::stream>>();
// read/write
{
error_code ec;
flat_stream<test::stream> s(ioc);
{
// VFALCO Hack to make test stream code = eof
test::stream ts(ioc);
s.next_layer().connect(ts);
}
char buf[1];
net::mutable_buffer m1 = net::buffer(buf);
BEAST_EXPECT(s.read_some(net::mutable_buffer{}) == 0);
BEAST_EXPECT(s.read_some(net::mutable_buffer{}, ec) == 0);
BEAST_EXPECTS(! ec, ec.message());
try
{
s.read_some(m1);
BEAST_FAIL();
}
catch(std::exception const&)
{
BEAST_PASS();
}
catch(...)
{
BEAST_FAIL();
}
BEAST_EXPECT(s.write_some(net::const_buffer{}) == 0);
BEAST_EXPECT(s.write_some(net::const_buffer{}, ec) == 0);
BEAST_EXPECTS(! ec, ec.message());
try
{
s.write_some(m1);
BEAST_FAIL();
}
catch(std::exception const&)
{
BEAST_PASS();
}
catch(...)
{
BEAST_FAIL();
}
bool invoked;
invoked = false;
s.async_read_some(net::mutable_buffer{},
[&](error_code ec, std::size_t)
{
invoked = true;
BEAST_EXPECTS(! ec, ec.message());
});
ioc.run();
ioc.restart();
BEAST_EXPECT(invoked);
invoked = false;
s.async_write_some(net::const_buffer{},
[&](error_code ec, std::size_t)
{
invoked = true;
BEAST_EXPECTS(! ec, ec.message());
});
ioc.run();
ioc.restart();
BEAST_EXPECT(invoked);
}
// stack_write_some
{
char b[detail::flat_stream_base::max_size];
std::array<net::const_buffer, 3> bs;
bs[0] = net::const_buffer(b, 100);
bs[1] = net::const_buffer(b + 100, 200);
bs[2] = net::const_buffer(b + 100 + 200, 300);
BEAST_EXPECT(buffer_bytes(bs) <=
detail::flat_stream_base::max_stack);
flat_stream<test::stream> s(ioc);
error_code ec;
s.write_some(bs, ec);
}
// write_some
{
char b[detail::flat_stream_base::max_size];
std::array<net::const_buffer, 2> bs;
bs[0] = net::const_buffer(b,
detail::flat_stream_base::max_stack);
bs[1] = net::const_buffer(b + bs[0].size(), 1024);
BEAST_EXPECT(buffer_bytes(bs) <=
detail::flat_stream_base::max_size);
flat_stream<test::stream> s(ioc);
error_code ec;
s.write_some(bs, ec);
}
// async_write_some
{
char b[detail::flat_stream_base::max_size];
std::array<net::const_buffer, 2> bs;
bs[0] = net::const_buffer(b,
detail::flat_stream_base::max_stack);
bs[1] = net::const_buffer(b + bs[0].size(), 1024);
BEAST_EXPECT(buffer_bytes(bs) <=
detail::flat_stream_base::max_size);
flat_stream<test::stream> s(ioc);
s.async_write_some(bs,
[](error_code, std::size_t)
{
});
}
// teardown
{
test::stream ts(ioc);
flat_stream<test::stream> s(ioc);
ts.connect(s.next_layer());
error_code ec;
teardown(role_type::client, s, ec);
}
{
test::stream ts(ioc);
flat_stream<test::stream> s(ioc);
ts.connect(s.next_layer());
async_teardown(role_type::client, s,
[](error_code)
{
});
}
}
void
testSplit()
{
auto const check =
[&](
std::initializer_list<int> v0,
std::size_t limit,
unsigned long count,
bool copy)
{
std::vector<net::const_buffer> v;
v.reserve(v0.size());
for(auto const n : v0)
v.emplace_back("", n);
auto const result =
boost::beast::detail::flat_stream_base::flatten(v, limit);
BEAST_EXPECT(result.size == count);
BEAST_EXPECT(result.flatten == copy);
return result;
};
check({}, 1, 0, false);
check({1,2}, 1, 1, false);
check({1,2}, 2, 1, false);
check({1,2}, 3, 3, true);
check({1,2}, 4, 3, true);
check({1,2,3}, 1, 1, false);
check({1,2,3}, 2, 1, false);
check({1,2,3}, 3, 3, true);
check({1,2,3}, 4, 3, true);
check({1,2,3}, 7, 6, true);
check({1,2,3,4}, 3, 3, true);
}
#if BOOST_ASIO_HAS_CO_AWAIT
void testAwaitableCompiles(
flat_stream<test::stream>& stream,
net::mutable_buffer rxbuf,
net::const_buffer txbuf)
{
static_assert(std::is_same_v<
net::awaitable<std::size_t>, decltype(
stream.async_read_some(rxbuf, net::use_awaitable))>);
static_assert(std::is_same_v<
net::awaitable<std::size_t>, decltype(
stream.async_write_some(txbuf, net::use_awaitable))>);
}
#endif
void
run() override
{
testMembers();
testSplit();
#if BOOST_ASIO_HAS_CO_AWAIT
boost::ignore_unused(&flat_stream_test::testAwaitableCompiles);
#endif
}
};
BEAST_DEFINE_TESTSUITE(beast,core,flat_stream);
} // beast
} // boost
| 28.702041 | 79 | 0.487201 | [
"vector"
] |
f6b376c24e8307a61c32fd7fdb12d09f63cf48fd | 47,945 | cpp | C++ | windows/FaceRecognitionTest/FaceImage.cpp | HSE-asavchenko/HSE_FaceRec | 7ba0d9aa10629061866fc237c04f15b00cd25659 | [
"Apache-2.0"
] | 3 | 2016-12-16T20:03:35.000Z | 2018-05-17T17:55:36.000Z | windows/FaceRecognitionTest/FaceImage.cpp | HSE-asavchenko/HSE_FaceRec | 7ba0d9aa10629061866fc237c04f15b00cd25659 | [
"Apache-2.0"
] | 1 | 2018-07-06T13:41:45.000Z | 2020-01-29T09:38:13.000Z | windows/FaceRecognitionTest/FaceImage.cpp | HSE-asavchenko/HSE_FaceRec | 7ba0d9aa10629061866fc237c04f15b00cd25659 | [
"Apache-2.0"
] | 3 | 2016-12-16T19:03:41.000Z | 2019-05-20T01:58:33.000Z | #include "stdafx.h"
#include "FaceImage.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace cv;
//#define ORTHO_SERIES_HISTOS
#ifdef ORTHO_SERIES_HISTOS
#define ORTHO_SERIES_CORRECT
#endif
static void median(int* pixels, int width,int height, int colorCount){
int *prev_pixels=new int[width*height*colorCount];
int i,j,ind;
for(j=0;j<width;++j){
for(i=0;i<height;++i){
ind=(i*width+j)*colorCount+0;
prev_pixels[ind]=pixels[ind];
}
}
const int MEDIAN_DIFF=1;
std::vector<int> neighbors;
for(int k=0;k<1;++k)
for(i=1;i<height-1;++i){
for(j=1;j<width-1;++j){
ind=(i*width+j)*colorCount;
neighbors.clear();
for(int i1=(i-MEDIAN_DIFF);i1<=(i+MEDIAN_DIFF);++i1)
if(i1>=0 && i1<height)
for(int j1=(j-MEDIAN_DIFF);j1<=(j+MEDIAN_DIFF);++j1)
if(j1>=0 && j1<width)
neighbors.push_back(prev_pixels[i1*width+j1]);
neighbors.push_back(pixels[ind+k]);
std::sort(neighbors.begin(),neighbors.end());
pixels[ind+k]=neighbors[neighbors.size()/2];
}
}
delete[] prev_pixels;
}
static void equalizeAllPixels(int* pixels, int width,int height, int colorCount){
const int max=255;
const int min=0;
int i,j,k,l,ind;
int histo[max+1];
int sqrSize=height*width;
memset(histo,0,sizeof(histo));
for(i=0;i<height;++i)
for(j=0;j<width;++j){
ind=(i*width+j)*colorCount;
++histo[pixels[ind]];
}
for(l=1;l<=max;++l){
histo[l]+=histo[l-1];
}
for(i=0;i<height;++i)
for(j=0;j<width;++j){
ind=(i*width+j)*colorCount;
pixels[ind]=min+(max-min)*histo[pixels[ind]]/sqrSize;
}
}
static void varSmoothing(int* pixels, int width,int height, int colorCount){
float *vars=new float[width*height*colorCount];
int i,j,ind;
const int VAR_DIFF=2;
float minVar=100000,maxVar=0;
for(int k=0;k<1;++k)
for(i=1;i<height-1;++i){
for(j=1;j<width-1;++j){
ind=(i*width+j)*colorCount;
float mean=pixels[ind+k],var=pixels[ind+k]*pixels[ind+k];
int count=1;
for(int i1=(i-VAR_DIFF);i1<=(i+VAR_DIFF);++i1)
if(i1>=0 && i1<height)
for(int j1=(j-VAR_DIFF);j1<=(j+VAR_DIFF);++j1)
if(j1>=0 && j1<width){
mean+=pixels[i1*width+j1];
var+=pixels[i1*width+j1]*pixels[i1*width+j1];
++count;
}
mean/=count;
var = fast_sqrt((var - mean * mean * count) / count);
if(var<minVar)
minVar=var;
if(var>maxVar)
maxVar=var;
vars[ind+k]=var;
}
}
for(int k=0;k<1;++k)
for(j=0;j<width;++j){
for(i=0;i<height;++i){
ind=(i*width+j)*colorCount+0;
pixels[ind+k]=maxVar==minVar?0:(int)(255*(vars[ind+k]-minVar)/(maxVar-minVar));
}
}
delete[] vars;
}
static void randomizeImage(int* pixels, int width,int height, int colorCount, int rndImageRange){
int i,j,ind;
for(j=0;j<width;++j){
for(i=0;i<height;++i){
ind=(i*width+j)*colorCount+0;
int rnd = rand();
if (rndImageRange>0){
pixels[ind] += rnd % (2 * rndImageRange) - rndImageRange;
if (pixels[ind]<0)
pixels[ind] = 0;
if (pixels[ind]>255)
pixels[ind] = 255;
}
}
}
}
#if DISTANCE==LOCAL_DESCRIPTORS
cv::DescriptorExtractor* FaceImage::extractor=new cv::SiftDescriptorExtractor();
cv::FeatureDetector * FaceImage::detector=new cv::SiftFeatureDetector();
#endif
const float PI=4.*atan(1.0);
FaceImage::FaceImage(const char* imageFileName, const std::string& pName, int pW, int pH, int rndImageRange, ImageTransform img_transform) :
personName(pName),
fileName(imageFileName),
pointsInW(pW), pointsInH(pH)
{
//std::cout << imageFileName << '\n';
const int scale = 1;
Mat img = imread( imageFileName, CV_LOAD_IMAGE_COLOR );
int width=img.cols/scale;
int height = img.rows / scale;
#ifndef USE_DNN_FEATURES
width = height = 96;
if ((width%pointsInW) != 0) {
if ((width%pointsInW)<pointsInW / 2)
width = (width / pointsInW)*pointsInW;
else
width = ((width / pointsInW) + 1)*pointsInW;
}
if ((height%pointsInH) != 0) {
if ((height%pointsInH)<pointsInH / 2)
height = (height / pointsInH)*pointsInH;
else
height = ((height / pointsInH) + 1)*pointsInH;
}
#elif defined(USE_RGB_DNN)
width = height = 224;
//width = 96; height = 112;
#else
width = height = 128;
#endif
resize(img, img, Size(width,height));
init(img, width, height, rndImageRange, img_transform);
}
FaceImage::FaceImage(cv::Mat& img, const std::string& pName, int pW, int pH) :
personName(pName),
fileName(""),
pointsInW(pW), pointsInH(pH)
{
init(img,img.cols,img.rows);
}
FaceImage::FaceImage():
personName(""),
fileName(""),
pointsInW(POINTS_IN_W), pointsInH(POINTS_IN_H)
{
int i,j,k,ind;
histos = new float[COLORS_COUNT*pointsInH*pointsInW*HISTO_SIZE];
kernel_histos = kernel_histos_function = histosSum = 0;
for(k=0;k<COLORS_COUNT;++k)
for (i = 0; i<pointsInH; ++i)
for (j = 0; j<pointsInW; ++j){
for(ind=0;ind<HISTO_SIZE;++ind){
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = 1.0 / HISTO_SIZE;//[k][i][j][ind]
}
}
}
FaceImage::FaceImage(int* p, int w, int h, const std::string& pName, int pW, int pH) :
pixels(p),
personName(pName),
fileName(""),
pointsInW(pW), pointsInH(pH),
width(w), height(h)
{
initHistos(p);
}
#ifdef USE_DNN_FEATURES
FaceImage::FaceImage(std::string fn, std::string pn, std::vector<float>& features, bool normalize) :
fileName(fn),personName(pn),featureVector(FEATURES_COUNT)
{
float sum = 1;
if (normalize) {
sum = 0;
#if DISTANCE!=EUC
for (int i = 0; i < FEATURES_COUNT; ++i)
sum += features[i];
#else
for (int i = 0; i < FEATURES_COUNT; ++i)
sum += features[i] * features[i];
sum = sqrt(sum);
#endif
}
//std::cout << "sum=" << sum << std::endl;
for (int i = 0; i < FEATURES_COUNT; ++i)
featureVector[i] = features[i] / sum;
}
static std::string readString(std::istream& file)
{
unsigned char len;
file.read((char*)&len, 1);
char* buffer = new char[len];
file.read(buffer, len);
std::string str(buffer, len);
delete[] buffer;
return str;
}
static void writeString(std::ostream& file, std::string str)
{
unsigned char len = (char)str.length();
file.write((char*)&len, 1);
file.write(str.c_str(), len);
}
FaceImage* FaceImage::readFaceImage(std::ifstream& file)
{
std::string fileName = readString(file);
std::string personName = readString(file);
//cout << fileName << ' ' << personName << '\n';
std::vector<float> features(FEATURES_COUNT);
file.read((char*)&features[0], sizeof(float)*FEATURES_COUNT);
return new FaceImage(fileName, personName, features);
}
void FaceImage::writeFaceImage(std::ofstream& file)
{
writeString(file, fileName);
writeString(file, personName);
file.write((char*)&featureVector[0], sizeof(float)*FEATURES_COUNT);
}
#endif
FaceImage::~FaceImage(){
delete[] histos;
delete[] histosSum;
delete[] pixels;
}
FaceImage* FaceImage::nextInPyramid(double scale){
//return new FaceImage(fileName.c_str(), personName, (int)(pointsInW / scale), (int)(pointsInH / scale));
int newWidth = width;// (int)(width / scale);
int newHeight = height;// (int)(height / scale);
int *new_pixels = new int[width*height*COLORS_COUNT];
memmove(new_pixels, pixels, width*height*COLORS_COUNT*sizeof(int));
FaceImage* res = new FaceImage(new_pixels, width, height, personName, (int)(pointsInW / scale), (int)(pointsInH / scale));
return res;
}
static int* get_gamma_vals(double gamma){
static int lut[256];
double inverse_gamma = 1.0 / gamma;
for (int i = 0; i < 256; i++)
lut[i] = (int)(pow((double)i / 255.0, gamma) * 255.0);
return lut;
}
static int* lut = get_gamma_vals(0.2);
static Mat norm_0_255(const Mat& src) {
// Create and return normalized image:
Mat dst;
switch (src.channels()) {
case 1:
cv::normalize(src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
static Mat tan_triggs_preprocessing(Mat X,
float alpha = 0.1, float tau = 10.0, float gamma = 0.2, int sigma0 = 1,
int sigma1 = 2) {
// Convert to floating point:
X.convertTo(X, CV_32FC1);
// Start preprocessing:
Mat I;
pow(X, gamma, I);
// Calculate the DOG Image:
if(false){
Mat gaussian0, gaussian1;
// Kernel Size:
int kernel_sz0 = (3 * sigma0);
int kernel_sz1 = (3 * sigma1);
// Make them odd for OpenCV:
kernel_sz0 += ((kernel_sz0 % 2) == 0) ? 1 : 0;
kernel_sz1 += ((kernel_sz1 % 2) == 0) ? 1 : 0;
GaussianBlur(I, gaussian0, Size(kernel_sz0, kernel_sz0), sigma0, sigma0, BORDER_CONSTANT);
GaussianBlur(I, gaussian1, Size(kernel_sz1, kernel_sz1), sigma1, sigma1, BORDER_CONSTANT);
subtract(gaussian0, gaussian1, I);
}
{
double meanI = 0.0;
{
Mat tmp;
pow(abs(I), alpha, tmp);
meanI = mean(tmp).val[0];
}
I = I / pow(meanI, 1.0 / alpha);
}
{
double meanI = 0.0;
{
Mat tmp;
pow(min(abs(I), tau), alpha, tmp);
meanI = mean(tmp).val[0];
}
I = I / pow(meanI, 1.0 / alpha);
}
// Squash into the tanh:
{
for (int r = 0; r < I.rows; r++) {
for (int c = 0; c < I.cols; c++) {
I.at<float>(r, c) = tanh(I.at<float>(r, c) / tau);
}
}
I = tau * I;
}
return norm_0_255(I);
}
/*
copied from https://github.com/MasteringOpenCV/code/blob/master/Chapter8_FaceRecognition/preprocessFace.cpp
Author Shervin Emami
*/
static void equalizeLeftAndRightHalves(Mat &faceImg)
{
// It is common that there is stronger light from one half of the face than the other. In that case,
// if you simply did histogram equalization on the whole face then it would make one half dark and
// one half bright. So we will do histogram equalization separately on each face half, so they will
// both look similar on average. But this would cause a sharp edge in the middle of the face, because
// the left half and right half would be suddenly different. So we also histogram equalize the whole
// image, and in the middle part we blend the 3 images together for a smooth brightness transition.
int w = faceImg.cols;
int h = faceImg.rows;
// 1) First, equalize the whole face.
Mat wholeFace;
equalizeHist(faceImg, wholeFace);
// 2) Equalize the left half and the right half of the face separately.
int midX = w / 2;
Mat leftSide = faceImg(Rect(0, 0, midX, h));
Mat rightSide = faceImg(Rect(midX, 0, w - midX, h));
equalizeHist(leftSide, leftSide);
equalizeHist(rightSide, rightSide);
// 3) Combine the left half and right half and whole face together, so that it has a smooth transition.
for (int y = 0; y<h; y++) {
for (int x = 0; x<w; x++) {
int v;
if (x < w / 4) { // Left 25%: just use the left face.
v = leftSide.at<uchar>(y, x);
}
else if (x < w * 2 / 4) { // Mid-left 25%: blend the left face & whole face.
int lv = leftSide.at<uchar>(y, x);
int wv = wholeFace.at<uchar>(y, x);
// Blend more of the whole face as it moves further right along the face.
float f = (x - w * 1 / 4) / (float)(w*0.25f);
v = cvRound((1.0f - f) * lv + (f)* wv);
}
else if (x < w * 3 / 4) { // Mid-right 25%: blend the right face & whole face.
int rv = rightSide.at<uchar>(y, x - midX);
int wv = wholeFace.at<uchar>(y, x);
// Blend more of the right-side face as it moves further right along the face.
float f = (x - w * 2 / 4) / (float)(w*0.25f);
v = cvRound((1.0f - f) * wv + (f)* rv);
}
else { // Right 25%: just use the right face.
v = rightSide.at<uchar>(y, x - midX);
}
faceImg.at<uchar>(y, x) = v;
}// end x loop
}//end y loop
}
static Mat normalizeMat(const Mat& srcMat) {
Mat result;
if (srcMat.channels() >= 3)
{
Mat ycrcb;
cvtColor(srcMat, ycrcb, CV_BGR2YCrCb);
std::vector<Mat> channels;
split(ycrcb, channels);
equalizeLeftAndRightHalves(channels[0]);
merge(channels, ycrcb);
cvtColor(ycrcb, result, CV_YCrCb2BGR);
}
else {
result = srcMat.clone();
equalizeLeftAndRightHalves(result);
}
return result;
}
void FaceImage::init(cv::Mat& img, int w, int h, int rndImageRange, ImageTransform img_transform){
//std::cout << fileName << '\n';
width = w;
height = h;
#if DISTANCE==LOCAL_DESCRIPTORS
detector->detect(img,keypoints);
extractor->compute(img,keypoints,descriptors);
#else
int i,j,k;
Mat dst;
#if 1
//cv::GaussianBlur(img, dst, Size(1, 1),1);
/*
for (i = 0; i < width; ++i){
for (j = 0; j < height; ++j){
Vec3b& val = img.at<Vec3b>(Point(i, j));
int greyColor = (int)(0.11*val[0] + .56*val[1] + .33*val[2]);
int rnd = rand();
if (rndImageRange>0){
greyColor += rnd % (2 * rndImageRange) - rndImageRange;
if (greyColor<0)
greyColor = 0;
if (greyColor>255)
greyColor = 255;
}
val[0] = val[1] = val[2] =
greyColor;
//lut[greyColor];
}
}
*/
#if 1 || !defined(USE_DNN_FEATURES)
cv::medianBlur(img, dst, 3);
#else
dst = img;
#endif
cv::Mat colorMat = dst.clone();
cvtColor(dst, dst, CV_RGB2GRAY);
//dst = tan_triggs_preprocessing(dst);
#if defined(USE_DNN_FEATURES) && defined(USE_RGB_DNN)
cv::Mat srcMat=colorMat;
#else
cv::Mat srcMat = dst;
#endif
cv::Mat transformedMat;
std::string dst_path = "D:\\img";
switch (img_transform) {
case ImageTransform::NONE:
transformedMat = srcMat;
break;
case ImageTransform::FLIP:
transformedMat = cv::Mat(srcMat.rows, srcMat.cols, srcMat.type());
cv::flip(srcMat, transformedMat, 1);
dst_path += "_flipped";
break;
case ImageTransform::NORMALIZE:
transformedMat=normalizeMat(srcMat);
dst_path += "_normalized";
break;
}
//imwrite( dst_path+".jpg", transformedMat);
/*char c;
std::cin>>c;*/
#endif
pixelMat = dst;
#ifndef USE_DNN_FEATURES
pixels = new int[width*height*COLORS_COUNT];
for (i = 0; i < width; ++i) {
for (j = 0; j < height; ++j) {
//Vec3b val = dst.at<Vec3b>(Point(i, j));
uchar val = transformedMat.at<uchar>(Point(i, j));
for (k = 0; k < COLORS_COUNT; ++k)
pixels[(j*width + i)*COLORS_COUNT + k] = val;
}
}
//equalizeAllPixels(pixels, width, height, COLORS_COUNT);
float mean = 0, std_var = 0;
for (i = 0; i < width; ++i) {
for (j = 0; j < height; ++j) {
//dst.at<uchar>(Point(i, j)) = pixels[(j*width + i)*COLORS_COUNT + 0];
mean += pixels[(j*width + i)*COLORS_COUNT + 0];
std_var += pixels[(j*width + i)*COLORS_COUNT + 0] * pixels[(j*width + i)*COLORS_COUNT + 0];
}
}
mean /= width*height;
std_var = std_var / (width*height) - mean*mean;
std_var = (std_var>0) ? sqrt(std_var) : 0;
for (i = 0; i < width; ++i) {
for (j = 0; j < height; ++j) {
for (k = 0; k < COLORS_COUNT; ++k) {
float val = 128;
if (std_var>0) {
val = 128 + ((pixels[(j*width + i)*COLORS_COUNT + k] - mean) * 127 / (6 * std_var));
if (val < 0)
val = 0;
else if (val >= 255)
val = 255;
}
pixels[(j*width + i)*COLORS_COUNT + k] = (int)val;
}
}
}
initHistos(pixels);
delete[] pixels; pixels = 0;
#else
featureVector.resize(FEATURES_COUNT);
DnnFeatureExtractor::GetInstance()->extractFeatures(transformedMat, &featureVector[0]);
/*float sum = 0;
for (int i = 0; i < FEATURES_COUNT; ++i)
sum += featureVector[i] * featureVector[i];
sum = sqrt(sum);
for (int i = 0; i < FEATURES_COUNT; ++i)
featureVector[i] /= sum;
*/
#endif
#endif
}
#define eps 0.0001
// unit vectors used to compute gradient orientation
float uu[9] = { 1.0000,
0.9397,
0.7660,
0.500,
0.1736,
-0.1736,
-0.5000,
-0.7660,
-0.9397 };
float vv[9] = { 0.0000,
0.3420,
0.6428,
0.8660,
0.9848,
0.9848,
0.8660,
0.6428,
0.3420 };
static inline double min(double x, double y) { return (x <= y ? x : y); }
static inline double max(double x, double y) { return (x <= y ? y : x); }
static inline int min(int x, int y) { return (x <= y ? x : y); }
static inline int max(int x, int y) { return (x <= y ? y : x); }
// takes a double color image and a bin size
// returns HOG features
float* FaceImage::extractHOG(int& feat_size) {
int *im = pixels;
// memory for caching orientation histograms & their norms
int blocks[2] = { pointsInH, pointsInW };
int histoGranularityH = height / pointsInH;
int histoGranularityW = width / pointsInW;
/*blocks[0] = (int)round((float)width / (float)sbin);
blocks[1] = (int)round((float)height / (float)sbin);*/
float *hist = new float[blocks[0] * blocks[1] * 18];
float *norm = new float[blocks[0] * blocks[1]];
for (int i = 0; i < blocks[0] * blocks[1] * 18; ++i)
hist[i] = 0;
for (int i = 0; i < blocks[0] * blocks[1]; ++i)
norm[i] = 0;
// memory for HOG features
int out[3];
out[0] = max(blocks[0] - 2, 0);
out[1] = max(blocks[1] - 2, 0);
out[2] = 18;// 27 + 4 + 1;
feat_size = out[0] * out[1] * out[2];
float *feat = new float[feat_size];
for (int i = 0; i < feat_size; ++i)
feat[i] = 0;
int visible[2];
visible[0] = height;// blocks[0] * sbin;
visible[1] = width;// blocks[1] * sbin;
for (int x = 1; x < visible[1] - 1; x++) {
for (int y = 1; y < visible[0] - 1; y++) {
int *s = im + min(x, height - 2)*width + min(y, width - 2);
int dy = *(s + 1) - *(s - 1);
int dx = *(s + width) - *(s - width);
int v = dx*dx + dy*dy;
// snap to one of 18 orientations
float best_dot = 0;
int best_o = 0;
for (int o = 0; o < 9; o++) {
float dot = uu[o] * dx + vv[o] * dy;
if (dot > best_dot) {
best_dot = dot;
best_o = o;
}
else if (-dot > best_dot) {
best_dot = -dot;
best_o = o + 9;
}
}
// add to 4 histograms around pixel using linear interpolation
float xp = ((float)x + 0.5) / histoGranularityW - 0.5;
float yp = ((float)y + 0.5) / histoGranularityH - 0.5;
int ixp = (int)floor(xp);
int iyp = (int)floor(yp);
float vx0 = xp - ixp;
float vy0 = yp - iyp;
float vx1 = 1.0 - vx0;
float vy1 = 1.0 - vy0;
v = sqrt(v);
if (ixp >= 0 && iyp >= 0) {
*(hist + ixp*blocks[0] + iyp + best_o*blocks[0] * blocks[1]) +=
vx1*vy1*v;
}
if (ixp + 1 < blocks[1] && iyp >= 0) {
*(hist + (ixp + 1)*blocks[0] + iyp + best_o*blocks[0] * blocks[1]) +=
vx0*vy1*v;
}
if (ixp >= 0 && iyp + 1 < blocks[0]) {
*(hist + ixp*blocks[0] + (iyp + 1) + best_o*blocks[0] * blocks[1]) +=
vx1*vy0*v;
}
if (ixp + 1 < blocks[1] && iyp + 1 < blocks[0]) {
*(hist + (ixp + 1)*blocks[0] + (iyp + 1) + best_o*blocks[0] * blocks[1]) +=
vx0*vy0*v;
}
}
}
// compute energy in each block by summing over orientations
for (int o = 0; o < 9; o++) {
float *src1 = hist + o*blocks[0] * blocks[1];
float *src2 = hist + (o + 9)*blocks[0] * blocks[1];
float *dst = norm;
float *end = norm + blocks[1] * blocks[0];
while (dst < end) {
*(dst++) += (*src1 + *src2);// *(*src1 + *src2);
src1++;
src2++;
}
}
// compute features
for (int x = 0; x < out[1]; x++) {
for (int y = 0; y < out[0]; y++) {
float *dst = feat + x*out[0] + y;
float *src, *p, n1, n2, n3, n4;
p = norm + (x + 1)*blocks[0] + y + 1;
n1 = 1.0 / /*sqrt*/(*p + *(p + 1) + *(p + blocks[0]) + *(p + blocks[0] + 1) + eps);
p = norm + (x + 1)*blocks[0] + y;
n2 = 1.0 / /*sqrt*/(*p + *(p + 1) + *(p + blocks[0]) + *(p + blocks[0] + 1) + eps);
p = norm + x*blocks[0] + y + 1;
n3 = 1.0 / /*sqrt*/(*p + *(p + 1) + *(p + blocks[0]) + *(p + blocks[0] + 1) + eps);
p = norm + x*blocks[0] + y;
n4 = 1.0 / /*sqrt*/(*p + *(p + 1) + *(p + blocks[0]) + *(p + blocks[0] + 1) + eps);
float t1 = 0;
float t2 = 0;
float t3 = 0;
float t4 = 0;
// contrast-sensitive features
src = hist + (x + 1)*blocks[0] + (y + 1);
for (int o = 0; o < 18; o++) {
float h1 = min(*src * n1, 0.2);
float h2 = min(*src * n2, 0.2);
float h3 = min(*src * n3, 0.2);
float h4 = min(*src * n4, 0.2);
*dst = 0.5 * (h1 + h2 + h3 + h4);
t1 += h1;
t2 += h2;
t3 += h3;
t4 += h4;
dst += out[0] * out[1];
src += blocks[0] * blocks[1];
}
}
}
delete[] hist;
delete[] norm;
float sum = eps;
for (int i = 0; i < feat_size; ++i)
sum += feat[i];
for (int i = 0; i < feat_size; ++i){
feat[i] /= sum;
}
return feat;
}
static int LBPH_size = 0;
static int* get_uniform_map(){
static int uniform_map[256];
int bits[8];
for (int i = 0; i < 256; ++i){
int prev_bit, cur_bit, count = 0;
prev_bit = (i&(1 << 7)) ? 1 : 0;
for (int j = 1; j<8; ++j){
cur_bit = (i&(1 << (7 - j))) ? 1 : 0;
if (prev_bit != cur_bit)
++count;
prev_bit = cur_bit;
}
if (count <= 2)
uniform_map[i] = LBPH_size++;
else
uniform_map[i] = -1;
}
for (int i = 0; i < 256; ++i){
if (uniform_map[i] == -1)
uniform_map[i] = LBPH_size;
}
++LBPH_size;
return uniform_map;
}
static int* uniform_map = get_uniform_map();
template<typename T> float* FaceImage::extractLBP(int& feat_size, T* image){
int k = 0;
int w1 = width , h1 = height ;
int* lbp_image = new int[width*height*COLORS_COUNT];
for (int j = 0; j < height; ++j){
for (int i = 0; i < width; ++i){
lbp_image[(j*width + i)*COLORS_COUNT + k] = 0;
}
}
for (int i = 2; i < width - 2; ++i){
for (int j = 2; j < height - 2; ++j){
int res = 0;
if (image[(j*w1 + i - 2)*COLORS_COUNT + k] >= image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 7;
if (image[((j + 2)*w1 + i)*COLORS_COUNT + k] >= image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 5;
if (image[(j*w1 + i + 2)*COLORS_COUNT + k] >= image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 3;
if (image[((j - 2)*w1 + i)*COLORS_COUNT + k] >= image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 1;
if ((image[((j + 1)*w1 + i - 1)*COLORS_COUNT + k] + image[((j + 2)*w1 + i - 2)*COLORS_COUNT + k])
>= 2 * image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 6;
if ((image[((j + 1)*w1 + i + 1)*COLORS_COUNT + k] + image[((j + 2)*w1 + i + 2)*COLORS_COUNT + k])
>= 2 * image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 4;
if ((image[((j - 1)*w1 + i + 1)*COLORS_COUNT + k] + image[((j - 2)*w1 + i + 2)*COLORS_COUNT + k])
>= 2 * image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 2;
if ((image[((j - 1)*w1 + i - 1)*COLORS_COUNT + k] + image[((j - 2)*w1 + i - 2)*COLORS_COUNT + k])
>= 2 * image[(j*w1 + i)*COLORS_COUNT + k])
res += 1 << 0;
lbp_image[((j - 0)*width + i - 0)*COLORS_COUNT + k] = uniform_map[res];
}
}
//WARNING!!! POINTS_IN_W, POINTS_IN_H are not used
int pointsInW = 8;
int pointsInH = 8;
feat_size = pointsInW*pointsInH*LBPH_size;
float* lbp_histo = new float[feat_size];
memset(lbp_histo, 0, feat_size*sizeof(float));
int histoGranularityW = width / pointsInW;
int histoGranularityH = height / pointsInH;
for (int k = 0; k < COLORS_COUNT; ++k){
for (int i = 0; i < pointsInH; ++i){
for (int j = 0; j < pointsInW; ++j){
int superInd = LBPH_size*(i*pointsInW + j);
for (int di = 0; di < histoGranularityH; ++di){
int x = i*histoGranularityH + di;
if (x >= height){
break;
}
for (int dj = 0; dj < histoGranularityW; ++dj){
int y = j*histoGranularityW + dj;
if (y >= width){
break;
}
int ind = lbp_image[x*width + y];
if (ind != -1)
++lbp_histo[superInd + ind];
}
}
float sum = 0;
for (int ind = 0; ind < LBPH_size; ++ind)
sum += lbp_histo[superInd + ind];
if (sum>0){
float norm = sum;
sum = 0;
for (int ind = 0; ind < LBPH_size; ++ind){
lbp_histo[superInd + ind] /= norm;
if (lbp_histo[superInd + ind] > 0.2)
lbp_histo[superInd + ind] = 0.2;
sum += lbp_histo[superInd + ind];
}
norm = sum;
for (int ind = 0; ind < LBPH_size; ++ind){
lbp_histo[superInd + ind] /= norm;
}
}
}
}
}
delete[] lbp_image;
return lbp_histo;
}
static Mat gabor_kernel[8];
static Ptr<Mat>* createFilterBank(){
static Ptr<Mat> gabor_filter[8];
float lambda = 4;
float sigma = .5622*lambda;
float thetas[] = { 0, 45, 90, 135 };
float gamma = 1;
for (int i = 0; i < 4; ++i){
float theta = thetas[i] * CV_PI / 180;
//Mat kernel;
gabor_kernel[2*i]=getGaborKernel(cv::Size(13, 13), sigma, theta, lambda, gamma, 0, CV_32F);
/*gabor_filter[2 * i] = createLinearFilter(CV_32F, CV_32F, gabor_kernel[2 * i], cv::Point(-1, -1),
0, BORDER_REFLECT, BORDER_REFLECT, Scalar(0));*/
gabor_kernel[2 * i+1] = getGaborKernel(cv::Size(13, 13), sigma, theta, lambda, gamma, -CV_PI / 2, CV_32F);
/*gabor_filter[2 * i + 1] = createLinearFilter(CV_32F, CV_32F, gabor_kernel[2 * i + 1], cv::Point(-1, -1),
0, BORDER_REFLECT, BORDER_REFLECT, Scalar(0));*/
}
return gabor_filter;
}
static Ptr<Mat>* gabor_filter = createFilterBank();
float* FaceImage::extractGabor(int& feat_size){
Mat img;
pixelMat.convertTo(img, CV_32F);
#if 1
int w = 48, h=48;
#else
int w = width, h = height;
#endif
resize(img, img, Size(w, h));
feat_size = w*h * 4;
float* gabor_features = new float[feat_size];
std::vector<float> res;
Mat dest0(img.rows, img.cols, CV_32F), dest1(img.rows, img.cols, CV_32F);
for (int i = 0; i < 4; ++i){
filter2D(img, dest0, CV_32F, gabor_kernel[2*i]);
//gabor_filter[2 * i]->apply(img, dest0);
cv::pow(dest0, 2, dest0);
//filter2D(img, dests[1], CV_32F, gabor_kernel[2*i+1]);
//gabor_filter[2 * i+1]->apply(img, dest1);
filter2D(img, dest1, CV_32F, gabor_kernel[2 * i + 1]);
cv::pow(dest1, 2, dest1);
cv::add(dest0, dest1, dest0);
cv::pow(dest0, 0.5, dest0);
/*double maxVal;
cv::minMaxLoc(dest0, 0, &maxVal);
dest0 /= (float)maxVal;*/
float sum = 0.;
for (int r = 0; r < h; ++r){
for (int c = 0; c < w; ++c){
gabor_features[i*w*h + r*w + c] = dest0.at<float>(r, c);
sum += gabor_features[i*w*h + r*w + c];
}
}
if (sum>0){
//sum = sqrt(sum);
for (int j = 0; j < w*h; ++j)
gabor_features[i*w*h + j] /= sum;
}
}
return gabor_features;
}
void FaceImage::initHistos(int* pixels)
{
int i, j, k, di, dj, x, y, superInd, ind;
const float min_weight = 0.1f;
weights.resize(pointsInH*pointsInW);
for (int row = 0; row<pointsInH; ++row){
for (int j = 0; j < pointsInW; ++j){
if ((row >= pointsInH / 2 && row <= 3 * pointsInH / 4)){
if (j<pointsInW / 2)
weights[row*pointsInW+j] = min_weight + (1 - min_weight) * 2 * j / (pointsInW - 1);
else
weights[row*pointsInW+j] = min_weight + (1 - min_weight) * 2 * (pointsInW - j - 1) / (pointsInW - 1);
}
else
weights[row*pointsInW+j] = 1.f;
}
}
//equalizeAllPixels(pixels,width,height,COLORS_COUNT);
//median(pixels,width,height,COLORS_COUNT);
//varSmoothing(pixels,width,height,COLORS_COUNT);
int histo_length = COLORS_COUNT*pointsInH*pointsInW*HISTO_SIZE;
histos = new float[3 * histo_length];
kernel_histos = &histos[histo_length];
kernel_histos_function = &histos[2*histo_length];
histosSum = new float[COLORS_COUNT*pointsInH*pointsInW];
int histoGranularityW = width / pointsInW;
int histoGranularityH = height / pointsInH;
blockSize = histoGranularityH*histoGranularityW;
//const float PI=4*atan(1.);
std::vector<float> mags;
mags.reserve(blockSize);
const int rate = 1;
#ifdef ORTHO_SERIES_HISTOS
int PROJECT_SIZE = (int)pow(histoGranularityH*histoGranularityW, 1.0 / 3);
if (PROJECT_SIZE<10)
PROJECT_SIZE = 10;
vector<double> a(PROJECT_SIZE), b(PROJECT_SIZE);
#endif
for (k = 0; k<COLORS_COUNT; ++k)
for (i = 0; i<pointsInH; ++i)
for (j = 0; j<pointsInW; ++j){
superInd = i*pointsInW + j;
#ifdef USE_GRADIENTS
#ifdef ORTHO_SERIES_HISTOS
for (int projInd = 0; projInd<PROJECT_SIZE; ++projInd)
a[projInd] = b[projInd] = 0;
#endif
mags.clear();
for (di = 0; di<histoGranularityH; ++di){
x = i*histoGranularityH + di;
if (x >= height - 1){
break;
}
for (dj = 0; dj<histoGranularityW; ++dj){
if ((di + dj) % rate != 0)
continue;
y = j*histoGranularityW + dj;
if (y >= width - 1){
break;
}
ind = x*width + y;
int dfdx = (pixels[(x + 1)*width + y] - pixels[x*width + y + 1]);
int dfdy = (pixels[x*width + y] - pixels[(x + 1)*width + y + 1]);
//float magSqr=dfdx*dfdx+dfdy*dfdy;
//float mag=labs(dfdx)>labs(dfdy)?labs(dfdx):labs(dfdy);
float mag = labs(dfdx) + labs(dfdy);
mags.push_back(mag);
}
}
std::sort(mags.begin(), mags.end());
float maxMag = mags[(mags.size() - 1) * 9 / 10] + 0.1;
for (ind = 0; ind<HISTO_SIZE; ++ind){
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = 0;
}
float sum = 0;
for (di = 0; di<histoGranularityH; ++di){
x = i*histoGranularityH + di;
if (x >= height - 1){
break;
}
for (dj = 0; dj<histoGranularityW; ++dj){
if ((di + dj) % rate != 0)
continue;
y = j*histoGranularityW + dj;
if (y >= width - 1){
break;
}
ind = x*width + y;
int dfdx = (pixels[(x + 1)*width + y] - pixels[x*width + y + 1]);
int dfdy = (pixels[x*width + y] - pixels[(x + 1)*width + y + 1]);
//float magSqr=dfdx*dfdx+dfdy*dfdy;
//float mag=labs(dfdx)>labs(dfdy)?labs(dfdx):labs(dfdy);
float mag = labs(dfdx) + labs(dfdy);
int angleInd = 0;
#if 1
float angle = atan2((float)dfdy, (float)dfdx) / (2 * PI);//+1./(2*HISTO_SIZE);
if (angle<0)
angle += 1;
else if (angle >= 1)
angle -= 1;
angleInd = (int)(HISTO_SIZE*angle);
#else
int bit0 = (abs(dfdy)<abs(dfdx)) ? 1 : 0;
int bit1 = (dfdx<0) ? 2 : 0;
int bit2 = (dfdy<0) ? 4 : 0;
angleInd = bit0 + bit1 + bit2;
#endif
//mag+=0.1;
float curIncrement = (mag >= maxMag) ? 1 : (mag / maxMag);
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + angleInd] += curIncrement;
#ifdef ORTHO_SERIES_CORRECT
float angle = atan2((float)dfdy, (float)dfdx);
//curIncrement=1;
for (int projInd = 0; projInd<PROJECT_SIZE; ++projInd){
a[projInd] += curIncrement*cos(angle*(projInd + 1))*(PROJECT_SIZE - projInd) / (mags.size()*(PROJECT_SIZE + 1));
b[projInd] += curIncrement*sin(angle*(projInd + 1))*(PROJECT_SIZE - projInd) / (mags.size()*(PROJECT_SIZE + 1));
}
#endif
}
}
#else
for (di = 0; di<histoGranularityH; ++di){
x = i*histoGranularityH + di;
//x=i*histoGranularityH/2+di;
if (x >= height){
break;
}
for (dj = 0; dj<histoGranularityW; ++dj){
y = j*histoGranularityW + dj;
//y=j*histoGranularityW/2+dj;
if (y >= width){
break;
}
ind = x*width + y;
int ind = HISTO_SIZE*pixels[x*width + y] / 256;
++histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
}
}
#endif
sum = 0;
for (ind = 0; ind<HISTO_SIZE; ++ind){
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] += 0.1;
sum += histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
}
histosSum[(k*pointsInH + i)*pointsInW + j] = sum;
if (sum>0){
float sum1 = 0;
for (ind = 0; ind<HISTO_SIZE; ++ind){
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] /= sum;
}
}
#if defined(ORTHO_SERIES_HISTOS) && !defined(ORTHO_SERIES_CORRECT)
for (int projInd = 0; projInd<PROJECT_SIZE; ++projInd){
for (int ind1 = 0; ind1<HISTO_SIZE; ++ind1){
double angle = 2 * PI*(ind1 + 1) / HISTO_SIZE;
if (angle>PI)
angle -= 2 * PI;
a[projInd] += histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind1] * cos(angle*(projInd + 1));
b[projInd] += histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind1] * sin(angle*(projInd + 1));
//std::cout<<projInd<<' '<<angle<<' '<<a[projInd]<<' '<<b[projInd]<<'\n';
}
a[projInd] = a[projInd] * (PROJECT_SIZE - projInd) / ((PROJECT_SIZE + 1));
b[projInd] = b[projInd] * (PROJECT_SIZE - projInd) / ((PROJECT_SIZE + 1));
//std::cout<<"ab "<<a[projInd]<<' '<<b[projInd]<<'\n';
}
#endif
//exit(0);
sum = 0;
for (ind = 0; ind<HISTO_SIZE; ++ind){
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = 0;
#ifdef ORTHO_SERIES_HISTOS
double angle = 2 * PI*(ind + 1) / HISTO_SIZE;
if (angle>PI)
angle -= 2 * PI;
for (int projInd = 0; projInd<PROJECT_SIZE; ++projInd){
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] += a[projInd] * cos(angle*(projInd + 1));
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] += b[projInd] * sin(angle*(projInd + 1));
}
//kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]/=PROJECT_SIZE+1;
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] += 0.5;
if (kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]<0){
cout << kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] << " error\n";
for (int projInd = 0; projInd<PROJECT_SIZE; ++projInd){
cout << a[projInd] << ' ' << b[projInd] << endl;
}
exit(0);
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = 0.001;
}
//std::cout<<histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]<<' '<<kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]<<'\n';
#ifdef ORTHO_SERIES_CORRECT
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
#endif
#else
for (int ind1 = 0; ind1<HISTO_SIZE; ++ind1)
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] +=
kernel.kernel[ind][ind1] * histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind1];
#endif
sum += kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
}
#ifdef ORTHO_SERIES_CORRECT
sum = 0;
for (ind = 0; ind<HISTO_SIZE; ++ind){
sum += histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
}
for (ind = 0; ind<HISTO_SIZE; ++ind){
histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] /= sum;
}
sum = 0;
for (ind = 0; ind<HISTO_SIZE; ++ind){
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = 0;
for (int ind1 = 0; ind1<HISTO_SIZE; ++ind1)
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] +=
kernel.kernel[ind][ind1] * histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind1];
sum += kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
}
#endif
if (sum>0){
for (ind = 0; ind<HISTO_SIZE; ++ind){
kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] /= sum;
kernel_histos_function[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] = 0;
if (kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]>0)
kernel_histos_function[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] =
#if DISTANCE==HOMOGENEITY || DISTANCE==PNN
log(kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]);
#elif DISTANCE == SIMPLIFIED_HOMOGENEITY
1 / kernel_histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind];
#else
0;
#endif
#if DISTANCE == KL
kernel_histos_function[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind] =
log(histos[((k*pointsInH + i)*pointsInW + j)*HISTO_SIZE + ind]);
#endif
}
}
}
#ifdef USE_EXTRA_FEATURES
int lbp_feat_size = 0;
float* lbp_features = 0;// extractLBP(lbp_feat_size, pixels);
//std::cout << lbp_feat_size << '\n';
//lbp_feat_size = 0;
#if 1
int hog_feat_size = 0;
float* hog_features = extractHOG(hog_feat_size);
//std::cout << hog_feat_size << '\n';
#else
int hog_feat_size = COLORS_COUNT*POINTS_IN_W*POINTS_IN_H*HISTO_SIZE;
float* hog_features = histos;
#endif
//hog_feat_size = 0;
int gabor_feat_size = 0;
float* gabor_features = 0;// extractGabor(gabor_feat_size);
featureVector.resize(lbp_feat_size + hog_feat_size+gabor_feat_size);
for (int i = 0; i < lbp_feat_size; ++i)
featureVector[i] = lbp_features[i];
for (int i = 0; i < hog_feat_size; ++i)
featureVector[i + lbp_feat_size] = hog_features[i];
for (int i = 0; i < gabor_feat_size; ++i)
featureVector[i + lbp_feat_size + hog_feat_size] = gabor_features[i];
delete[] gabor_features;
delete[] hog_features;
delete[] lbp_features;
#endif
}
FaceImage::Kernel::Kernel()
{
float expCoeffs[HISTO_SIZE];
#ifdef USE_GRADIENTS
float alpha=-3;
#else
float alpha=-0.5;
#endif
for(int i=0;i<HISTO_SIZE;++i){
expCoeffs[i]=exp(alpha*i);
}
for(int i=0;i<HISTO_SIZE;++i){
float sum=0;
for(int j=0;j<HISTO_SIZE;++j){
int diff = abs(i - j);
#ifdef USE_GRADIENTS
if (diff>HISTO_SIZE / 2)
diff = (HISTO_SIZE - diff);
#endif
kernel[i][j]=expCoeffs[diff];
sum+=kernel[i][j];
}
for(int j=0;j<HISTO_SIZE;++j){
kernel[i][j]/=sum;
}
}
}
//#define PARALLEL_DISTANCE
const int NUM_OF_ROWS=1;
const int thread_count=8;
inline float FaceImage::getRowDistance(const FaceImage* rhs,int k, int row) const
{
float res=0;
int jMin, jMax;
int maxI=row+NUM_OF_ROWS;
if(maxI>pointsInH)
maxI=pointsInH;
int delta = /*(pointsInW <= 5) ? 0 : */DELTA;
for(int i=row;i<maxI;++i){
int iMin = i >= delta ? i - delta : 0;
int iMax = i + delta;
if(iMax>=pointsInH)
iMax=pointsInH-1;
for (int j = 0; j<pointsInW; ++j){
jMin = j >= delta ? j - delta : 0;
jMax = j + delta;
if (jMax >= pointsInW)
jMax = pointsInW - 1;
float minSum=1000000;
int i1=i,j1=j;
//for(i1=iMin;i1<=iMax;++i1)
// for(j1=jMin;j1<=jMax;++j1)
for(int i2=iMin;i2<=iMax;++i2){
for(int j2=jMin;j2<=jMax;++j2){
float curSum=0;
#if DISTANCE==KOLMOGOROFF
curSum=100000;
#endif
float cdf1=0,cdf2=0;
for(int ind=0;ind<HISTO_SIZE;++ind){
float d1 = histos[((k*pointsInH + i1)*pointsInW + j1)*HISTO_SIZE + ind];
float d2 = rhs->histos[((k*pointsInH + i2)*pointsInW + j2)*HISTO_SIZE + ind];
float kd1 = kernel_histos[((k*pointsInH + i1)*pointsInW + j1)*HISTO_SIZE + ind];
float kd2 = rhs->kernel_histos[((k*pointsInH + i2)*pointsInW + j2)*HISTO_SIZE + ind];
float kd1_f=kernel_histos_function[((k*pointsInH + i1)*pointsInW + j1)*HISTO_SIZE + ind];
float kd2_f=rhs->kernel_histos_function[((k*pointsInH + i2)*pointsInW + j2)*HISTO_SIZE + ind];
#if DISTANCE==MANHATTEN
curSum+=(fabs(d1-d2));
//curSum+=fast_sqrt(fabs(d1-d2));
#elif DISTANCE==EUC
curSum+=(d1-d2)*(d1-d2);
#elif DISTANCE==INTERSECT
curSum+=1-((d1<d2)?d1:d2);
#elif DISTANCE==SMIRNOFF
cdf1+=d1;
cdf2+=d2;
curSum+=fabs(cdf1-cdf2);
/*if(ind==HISTO_SIZE-1){
if(cdf1<0.999 || cdf2<0.999)
std::cerr<<cdf1<<' '<<cdf2<<'\n';
}*/
#elif DISTANCE==KOLMOGOROFF
cdf1+=d1;
cdf2+=d2;
float tmpDist=fabs(cdf1-cdf2);
if(curSum>tmpDist)
curSum=tmpDist;
#elif DISTANCE==LEMAN_ROSENBLATT
cdf1+=d1;
cdf2+=d2;
#if 0
float summary=(d1*histosSum[(k*pointsInH + i1)*pointsInW + j1]+
d2*rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2])/
(histosSum[(k*pointsInH + i1)*pointsInW + j1]+rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2]);
#else
float summary=(d1+d2)/2;
//float summary=(kd1+kd2)/2;
#endif
curSum+=summary*
fabs(cdf1-cdf2);
//(cdf1-cdf2)*(cdf1-cdf2);
#elif DISTANCE==CHI_SQUARE
if(d1+d2>0)
curSum+=(d1-d2)*(d1-d2)/(d1+d2);
#elif DISTANCE==KL
#if 0
curSum+=d1*std::log(d1/d2);
#else
curSum+=d1*(kd1_f-kd2_f);
#endif
#elif DISTANCE==SYM_KL
curSum+=(d1-d2)*std::log(d1/d2);
#elif DISTANCE==JENSEN_SHANNON
if(d1>0)
curSum+=d1*log(2*d1/(d1+d2));
//curSum+=(4*d1*d1-(d1+d2)*(d1+d2))/(d1+d2);
if(d2>0)
curSum+=d2*log(2*d2/(d1+d2));
//curSum+=(4*d2*d2-(d1+d2)*(d1+d2))/(d1+d2);
//curSum+=d1*log(2*kd1/(kd1+kd2))+d2*log(2*kd2/(kd1+kd2));
#elif DISTANCE==HOMOGENEITY || DISTANCE==SIMPLIFIED_HOMOGENEITY
#if 1
#else
float kd1=d1;
float kd2=d2;
#endif
#if 0
float curProd=kd1*histosSum[(k*pointsInH + i1)*pointsInW + j1];
float rhsCurProd = kd2*rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2];
float summary = (curProd + rhsCurProd) /
(histosSum[(k*pointsInH + i1)*pointsInW + j1] + rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2]);
#else
float summary=(d1+d2)/2.f;
//float summary=(kd1+kd2)/2;
#endif
if(summary>0){
float inv_sum =
#if DISTANCE==HOMOGENEITY
log(summary);
#else
2.f / summary;
#endif
float tempSum=0;
/*if (kd1>0){
tempSum += kd1*(kd1*kd1 - summary*summary) / (2 * kd1*summary);
}
if (kd2>0){
tempSum += kd2*(kd2*kd2 - summary*summary) / (2 * kd2*summary);
}*/
#if DISTANCE==HOMOGENEITY
if (kd1>0)
{
tempSum += d1*(kd1_f - inv_sum);//*histosSum[(k*pointsInH + i1)*pointsInW + j1];
}
#else
tempSum += kd1_f*inv_sum*d1*(kd1*kd1 - summary*summary);
//tempSum+=d1/2*(kd1/summary-summary/kd1);
#endif
#if DISTANCE==HOMOGENEITY
if (kd2>0)
{
tempSum += d2*(kd2_f - inv_sum);//*rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2];
}
#else
tempSum += kd2_f*inv_sum*d2*(kd2*kd2 - summary*summary);
//tempSum+=d2/2*(kd2/summary-summary/kd2);
#endif
//tempSum/=(histosSum[(k*pointsInH + i1)*pointsInW + j1]+rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2]);
curSum+=tempSum;
}
#elif DISTANCE==PNN
#if 1
float det=kd2;
#else
float det=d2;
//kd1=d1;
#endif
if (d1 > 0 && det > 0){
//curSum += d1*log(kd1 / det);
curSum += d1*(kd1_f - kd2_f);
//curSum+=d1*(kd1*kd1-det*det)/(2*kd1*det);
}
#elif DISTANCE==MY_PNN
float num1=0,num2=0,den=0;
for(int ind1=0;ind1<HISTO_SIZE;++ind1){
float curProd=histos[((k*pointsInH + i1)*pointsInW + j1)*HISTO_SIZE + ind1]*histosSum[(k*pointsInH + i1)*pointsInW + j1];
float rhsCurProd=rhs->histos[((k*pointsInH + i2)*pointsInW + j2)*HISTO_SIZE + ind1]*rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2];
float summary=(curProd+rhsCurProd)/
(histosSum[(k*pointsInH + i1)*pointsInW + j1]+rhs->histosSum[(k*pointsInH + i2)*pointsInW + j2]);
num1+=kernel.kernel[ind][ind1]*histos[((k*pointsInH + i1)*pointsInW + j1)*HISTO_SIZE + ind1];
num2+=kernel.kernel[ind][ind1]*rhs->histos[((k*pointsInH + i2)*pointsInW + j2)*HISTO_SIZE + ind1];
den+=kernel.kernel[ind][ind1]*summary;
}
if(den>0){
if(num1>0)
curSum+=d1*log(num1/den);
if(num2>0)
curSum+=d2*log(num2/den);
}
#elif DISTANCE==BHATTACHARYYA
curSum+=fast_sqrt(d1*d2);
#endif
}
#if DISTANCE==BHATTACHARYYA
if(curSum>0)
curSum=-log(curSum);
#endif
if(curSum<0)
curSum=0;
if(minSum>curSum){
minSum=curSum;
}
}
}
minSum=fast_sqrt(minSum);
res += weights[i*pointsInW + j] * (minSum);
}
}
return res;
}
#ifndef PARALLEL_DISTANCE
/*
* Euclidean distance functor
*/
template<class T>
struct CV_EXPORTS SqrtL2
{
typedef T ValueType;
typedef typename cv::Accumulator<T>::Type ResultType;
ResultType operator()( const T* a, const T* b, int size ) const
{
ResultType result = ResultType();
#if 1
for(int i=0;i<16;++i){
ResultType cellResult = ResultType();
for(int j=0;j<8;++j){
ResultType diff = (ResultType)(a[i*8+j] - b[i*8+j]);
cellResult += diff*diff;//abs(diff);
}
result+=(ResultType)fast_sqrt((float)cellResult);
}
#else
for(int i1=0;i1<4;++i1){
int iMin=i1>=DELTA?i1-DELTA:0;
int iMax=i1+DELTA;
if(iMax>=4)
iMax=3;
for(int j1=0;j1<4;++j1){
int jMin=j1>=DELTA?j1-DELTA:0;
int jMax=j1+DELTA;
if(jMax>=4)
jMax=3;
float cellResult = FLT_MAX;
for(int i2=iMin;i2<=iMax;++i2){
for(int j2=jMin;j2<=jMax;++j2){
float curSum=0.f;
for(int k=0;k<8;++k){
T cur_a=a[(i1*4+j1)*8+k];
T cur_b=b[(i2*4+j2)*8+k];
T diff = (cur_a - cur_b);
//if(cur_a + cur_b>0)
curSum += diff*diff;///(cur_a + cur_b);
}
if(curSum<0)
curSum=0;
if(cellResult>curSum){
cellResult=curSum;
}
}
}
result+=
(ResultType)cellResult;
//(ResultType)fast_sqrt(cellResult);
}
}
#endif
return result;
}
};
float FaceImage::distance(const FaceImage* rhs, float* var){
double res=0;
double var_dist = 0;
#if 1 || defined(USE_DNN_FEATURES)
const float* search_features = rhs->getFeatures();
const float* features=getFeatures();
double tmp;
for (int k = 0; k<FEATURES_COUNT; ++k){
#if DISTANCE==MANHATTEN
tmp=fabs(features[k] - search_features[k]);
#elif DISTANCE==CHI_SQUARE
if ((features[k] + search_features[k])>0)
tmp = (features[k] - search_features[k])*(features[k] - search_features[k])/(features[k] + search_features[k]);
else
tmp = 0;
#else // DISTANCE==EUC by default
tmp = (features[k] - search_features[k])*(features[k] - search_features[k]);
#endif
res += tmp;
}
res /= FEATURES_COUNT;
#if DISTANCE==EUC
res=sqrt(res);
#endif
return (float)res;
#else
#if DISTANCE==LOCAL_DESCRIPTORS
std::vector<vector<cv::DMatch > > matches;
std::vector<cv::DMatch > good_matches;
//cv::FlannBasedMatcher matcher;
cv::BruteForceMatcher<
//SqrtL2
cv::L2
<float> > matcher;
matcher.knnMatch(descriptors, rhs->descriptors, matches, 2);
for(int i = 0; i < std::min(rhs->descriptors.rows-1,(int) matches.size()); i++) //THIS LOOP IS SENSITIVE TO SEGFAULTS
{
if((matches[i][0].distance < 0.8*(matches[i][1].distance)) && ((int) matches[i].size()<=2 && (int) matches[i].size()>0))
{
good_matches.push_back(matches[i][0]);
}
}
res=-1.*good_matches.size();///rhs->keypoints.size();
return (float)res;
#else
for(int k=0;k<COLORS_COUNT;++k){
for (int row = 0; row<pointsInH; row += NUM_OF_ROWS){
res+=getRowDistance(rhs, k, row);
}
}
return (float)(res / (COLORS_COUNT*pointsInH*pointsInW));
#endif
#endif
}
#else
#include "ThreadPool.h"
#include "PrivateThreadPool.h"
using namespace windowsthreadpool;
namespace{
CRITICAL_SECTION csCheckBest;
PrivateThreadPool threadPool;
class ParallelDistance{
public:
ParallelDistance();
~ParallelDistance();
};
ParallelDistance::ParallelDistance(){
InitializeCriticalSection(&csCheckBest);
//threadPool.SetThreadpoolMin(thread_count);
threadPool.SetThreadpoolMax(thread_count);
}
ParallelDistance::~ParallelDistance(){
DeleteCriticalSection(&csCheckBest);
}
ParallelDistance parallelDistance;
const FaceImage *lhsFaceImage, *rhsFaceImage;
float res_distance;
//volatile int tasksCount;
DWORD WINAPI calculateRowDistance(PVOID param1, PVOID param2)
{
int k = (int)param1;
int row = (int)param2;
float tmpDist=lhsFaceImage->getRowDistance(rhsFaceImage,k,row);
EnterCriticalSection(&csCheckBest);
res_distance+=tmpDist;
//--tasksCount;
/*if(tasksCount==0)
SetEvent(jobCompletedEvent);*/
LeaveCriticalSection(&csCheckBest);
//std::cerr<<tasksCount<<" hi\n";
return 0;
}
}
//int checks=10;
float FaceImage::distance(const FaceImage* rhs){
res_distance=0;
lhsFaceImage=this;
rhsFaceImage=rhs;
//tasksCount=COLORS_COUNT*pointsInH;
//ResetEvent(jobCompletedEvent);
//std::cerr<<CThreadPool::GetThreadPool().GetWorkingThreadCount()<<"\n";
for(int k=0;k<COLORS_COUNT;++k)
for(int row=0;row<pointsInH;row+=NUM_OF_ROWS)
//CThreadPool::GetThreadPool().Run(calculateRowDistance,(LPVOID)k, (LPVOID)row);
threadPool.QueueUserWorkItem(calculateRowDistance,(LPVOID)k, (LPVOID)row);
/*
//if(WaitForSingleObject(jobCompletedEvent,10000)==WAIT_TIMEOUT){
do{
if(!CThreadPool::GetThreadPool().WaitForAllTasksCompletion()){
std::cout<<tasksCount<<" "<<CThreadPool::GetThreadPool().GetWorkingThreadCount()<<" timeout\n";
for(int k=0;k<COLORS_COUNT;++k){
for(int row=0;row<pointsInH;++row){
res_distance+=getRowDistance(rhs, k, row);
}
}
break;
}
}while(tasksCount!=0);
*/
threadPool.WaitForAll();
return res_distance/(COLORS_COUNT*pointsInH*pointsInW);
}
#endif
| 29.163625 | 153 | 0.604359 | [
"vector"
] |
f6b44e82096a1a35dd13380e7f1f31377cd31d24 | 13,050 | cpp | C++ | src/ar_track_alvar/ar_track_alvar/nodes/IndividualMarkersNoKinectSawyer.cpp | SaahilParikh/Interceptor | 2c9f1baa7d655cd585e03057fbda114e73995bf9 | [
"MIT"
] | 1 | 2021-12-22T21:34:01.000Z | 2021-12-22T21:34:01.000Z | src/ar_track_alvar/ar_track_alvar/nodes/IndividualMarkersNoKinectSawyer.cpp | SaahilParikh/Interceptor | 2c9f1baa7d655cd585e03057fbda114e73995bf9 | [
"MIT"
] | null | null | null | src/ar_track_alvar/ar_track_alvar/nodes/IndividualMarkersNoKinectSawyer.cpp | SaahilParikh/Interceptor | 2c9f1baa7d655cd585e03057fbda114e73995bf9 | [
"MIT"
] | null | null | null | /*
Software License Agreement (BSD License)
Copyright (c) 2012, Scott Niekum
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 Willow Garage nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
author: Scott Niekum
*/
#include <std_msgs/Bool.h>
#include "ar_track_alvar/CvTestbed.h"
#include "ar_track_alvar/MarkerDetector.h"
#include "ar_track_alvar/Shared.h"
#include <cv_bridge/cv_bridge.h>
#include <ar_track_alvar_msgs/AlvarMarker.h>
#include <ar_track_alvar_msgs/AlvarMarkers.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
#include <sensor_msgs/image_encodings.h>
#include <dynamic_reconfigure/server.h>
#include <ar_track_alvar/ParamsConfig.h>
using namespace alvar;
using namespace std;
bool init=true;
Camera *cam;
cv_bridge::CvImagePtr cv_ptr_;
image_transport::Subscriber cam_sub_;
ros::Publisher arMarkerPub_;
ros::Publisher rvizMarkerPub_;
ar_track_alvar_msgs::AlvarMarkers arPoseMarkers_;
visualization_msgs::Marker rvizMarker_;
tf::TransformListener *tf_listener;
tf::TransformBroadcaster *tf_broadcaster;
MarkerDetector<MarkerData> marker_detector;
bool enableSwitched = false;
bool enabled = true;
double max_frequency;
double marker_size;
double max_new_marker_error;
double max_track_error;
std::string cam_image_topic;
std::string cam_info_topic;
std::string output_frame;
int marker_resolution = 5; // default marker resolution
int marker_margin = 2; // default marker margin
void getCapCallback (const sensor_msgs::ImageConstPtr & image_msg);
void getCapCallback (const sensor_msgs::ImageConstPtr & image_msg)
{
//If we've already gotten the cam info, then go ahead
if(cam->getCamInfo_){
try{
tf::StampedTransform CamToOutput;
try{
tf_listener->waitForTransform(output_frame, image_msg->header.frame_id, image_msg->header.stamp, ros::Duration(1.0));
tf_listener->lookupTransform(output_frame, image_msg->header.frame_id, image_msg->header.stamp, CamToOutput);
}
catch (tf::TransformException ex){
ROS_ERROR("%s",ex.what());
}
//Convert the image
cv_ptr_ = cv_bridge::toCvCopy(image_msg, sensor_msgs::image_encodings::BGR8);
//Get the estimated pose of the main markers by using all the markers in each bundle
// GetMultiMarkersPoses expects an IplImage*, but as of ros groovy, cv_bridge gives
// us a cv::Mat. I'm too lazy to change to cv::Mat throughout right now, so I
// do this conversion here -jbinney
IplImage ipl_image = cv_ptr_->image;
marker_detector.Detect(&ipl_image, cam, true, false, max_new_marker_error, max_track_error, CVSEQ, true);
arPoseMarkers_.markers.clear ();
for (size_t i=0; i<marker_detector.markers->size(); i++)
{
//Get the pose relative to the camera
int id = (*(marker_detector.markers))[i].GetId();
Pose p = (*(marker_detector.markers))[i].pose;
double px = p.translation[0]/100.0;
double py = p.translation[1]/100.0;
double pz = p.translation[2]/100.0;
double qx = p.quaternion[1];
double qy = p.quaternion[2];
double qz = p.quaternion[3];
double qw = p.quaternion[0];
tf::Quaternion rotation (qx,qy,qz,qw);
tf::Vector3 origin (px,py,pz);
tf::Transform t (rotation, origin);
tf::Vector3 markerOrigin (0, 0, 0);
tf::Transform m (tf::Quaternion::getIdentity (), markerOrigin);
tf::Transform markerPose = t * m; // marker pose in the camera frame
tf::Vector3 z_axis_cam = tf::Transform(rotation, tf::Vector3(0,0,0)) * tf::Vector3(0, 0, 1);
// ROS_INFO("%02i Z in cam frame: %f %f %f",id, z_axis_cam.x(), z_axis_cam.y(), z_axis_cam.z());
/// as we can't see through markers, this one is false positive detection
if (z_axis_cam.z() > 0)
{
continue;
}
//Publish the transform from the camera to the marker
std::string markerFrame = "ar_marker2_";
std::stringstream out;
out << id;
std::string id_string = out.str();
markerFrame += id_string;
tf::StampedTransform camToMarker (t, image_msg->header.stamp, image_msg->header.frame_id, markerFrame.c_str());
tf_broadcaster->sendTransform(camToMarker);
//Create the rviz visualization messages
tf::poseTFToMsg (markerPose, rvizMarker_.pose);
rvizMarker_.header.frame_id = image_msg->header.frame_id;
rvizMarker_.header.stamp = image_msg->header.stamp;
rvizMarker_.id = id;
rvizMarker_.scale.x = 1.0 * marker_size/100.0;
rvizMarker_.scale.y = 1.0 * marker_size/100.0;
rvizMarker_.scale.z = 0.2 * marker_size/100.0;
rvizMarker_.ns = "basic_shapes";
rvizMarker_.type = visualization_msgs::Marker::CUBE;
rvizMarker_.action = visualization_msgs::Marker::ADD;
switch (id)
{
case 0:
rvizMarker_.color.r = 0.0f;
rvizMarker_.color.g = 0.0f;
rvizMarker_.color.b = 1.0f;
rvizMarker_.color.a = 1.0;
break;
case 1:
rvizMarker_.color.r = 1.0f;
rvizMarker_.color.g = 0.0f;
rvizMarker_.color.b = 0.0f;
rvizMarker_.color.a = 1.0;
break;
case 2:
rvizMarker_.color.r = 0.0f;
rvizMarker_.color.g = 1.0f;
rvizMarker_.color.b = 0.0f;
rvizMarker_.color.a = 1.0;
break;
case 3:
rvizMarker_.color.r = 0.0f;
rvizMarker_.color.g = 0.5f;
rvizMarker_.color.b = 0.5f;
rvizMarker_.color.a = 1.0;
break;
case 4:
rvizMarker_.color.r = 0.5f;
rvizMarker_.color.g = 0.5f;
rvizMarker_.color.b = 0.0;
rvizMarker_.color.a = 1.0;
break;
default:
rvizMarker_.color.r = 0.5f;
rvizMarker_.color.g = 0.0f;
rvizMarker_.color.b = 0.5f;
rvizMarker_.color.a = 1.0;
break;
}
rvizMarker_.lifetime = ros::Duration (1.0);
rvizMarkerPub_.publish (rvizMarker_);
//Get the pose of the tag in the camera frame, then the output frame (usually torso)
tf::Transform tagPoseOutput = CamToOutput * markerPose;
//Create the pose marker messages
ar_track_alvar_msgs::AlvarMarker ar_pose_marker;
tf::poseTFToMsg (tagPoseOutput, ar_pose_marker.pose.pose);
ar_pose_marker.header.frame_id = output_frame;
ar_pose_marker.header.stamp = image_msg->header.stamp;
ar_pose_marker.id = id;
arPoseMarkers_.markers.push_back (ar_pose_marker);
}
arMarkerPub_.publish (arPoseMarkers_);
}
catch (cv_bridge::Exception& e){
ROS_ERROR ("Could not convert from '%s' to 'rgb8'.", image_msg->encoding.c_str ());
}
}
}
void configCallback(ar_track_alvar::ParamsConfig &config, uint32_t level)
{
ROS_INFO("AR tracker reconfigured: %s %.2f %.2f %.2f %.2f", config.enabled ? "ENABLED" : "DISABLED",
config.max_frequency, config.marker_size, config.max_new_marker_error, config.max_track_error);
enableSwitched = enabled != config.enabled;
enabled = config.enabled;
max_frequency = config.max_frequency;
marker_size = config.marker_size;
max_new_marker_error = config.max_new_marker_error;
max_track_error = config.max_track_error;
}
void enableCallback(const std_msgs::BoolConstPtr& msg)
{
enableSwitched = enabled != msg->data;
enabled = msg->data;
}
int main(int argc, char *argv[])
{
ros::init (argc, argv, "marker_detect");
ros::NodeHandle n, pn("~");
if(argc > 1) {
ROS_WARN("Command line arguments are deprecated. Consider using ROS parameters and remappings.");
if(argc < 7){
std::cout << std::endl;
cout << "Not enough arguments provided." << endl;
cout << "Usage: ./individualMarkersNoKinect <marker size in cm> <max new marker error> <max track error> "
<< "<cam image topic> <cam info topic> <output frame> [ <max frequency> <marker_resolution> <marker_margin>]";
std::cout << std::endl;
return 0;
}
// Get params from command line
marker_size = atof(argv[1]);
max_new_marker_error = atof(argv[2]);
max_track_error = atof(argv[3]);
cam_image_topic = argv[4];
cam_info_topic = argv[5];
output_frame = argv[6];
if (argc > 7) {
max_frequency = atof(argv[7]);
pn.setParam("max_frequency", max_frequency);
}
if (argc > 8)
marker_resolution = atoi(argv[8]);
if (argc > 9)
marker_margin = atoi(argv[9]);
} else {
// Get params from ros param server.
pn.param("marker_size", marker_size, 10.0);
pn.param("max_new_marker_error", max_new_marker_error, 0.08);
pn.param("max_track_error", max_track_error, 0.2);
pn.param("max_frequency", max_frequency, 8.0);
pn.setParam("max_frequency", max_frequency); // in case it was not set.
pn.param("marker_resolution", marker_resolution, 5);
pn.param("marker_margin", marker_margin, 2);
if (!pn.getParam("output_frame", output_frame)) {
ROS_ERROR("Param 'output_frame' has to be set.");
exit(EXIT_FAILURE);
}
// Camera input topics. Use remapping to map to your camera topics.
cam_image_topic = "camera_image";
cam_info_topic = "camera_info";
}
// Set dynamically configurable parameters so they don't get replaced by default values
pn.setParam("marker_size", marker_size);
pn.setParam("max_new_marker_error", max_new_marker_error);
pn.setParam("max_track_error", max_track_error);
marker_detector.SetMarkerSize(marker_size, marker_resolution, marker_margin);
cam = new Camera(n, cam_info_topic);
tf_listener = new tf::TransformListener(n);
tf_broadcaster = new tf::TransformBroadcaster();
arMarkerPub_ = n.advertise < ar_track_alvar_msgs::AlvarMarkers > ("ar_pose_marker", 0);
rvizMarkerPub_ = n.advertise < visualization_msgs::Marker > ("visualization_marker", 0);
// Prepare dynamic reconfiguration
dynamic_reconfigure::Server < ar_track_alvar::ParamsConfig > server;
dynamic_reconfigure::Server<ar_track_alvar::ParamsConfig>::CallbackType f;
f = boost::bind(&configCallback, _1, _2);
server.setCallback(f);
//Give tf a chance to catch up before the camera callback starts asking for transforms
// It will also reconfigure parameters for the first time, setting the default values
ros::Duration(1.0).sleep();
ros::spinOnce();
image_transport::ImageTransport it_(n);
// Run at the configured rate, discarding pointcloud msgs if necessary
ros::Rate rate(max_frequency);
/// Subscriber for enable-topic so that a user can turn off the detection if it is not used without
/// having to use the reconfigure where he has to know all parameters
ros::Subscriber enable_sub_ = pn.subscribe("enable_detection", 1, &enableCallback);
enableSwitched = true;
while (ros::ok())
{
ros::spinOnce();
rate.sleep();
if (std::abs((rate.expectedCycleTime() - ros::Duration(1.0 / max_frequency)).toSec()) > 0.001)
{
// Change rate dynamically; if must be above 0, as 0 will provoke a segfault on next spinOnce
ROS_DEBUG("Changing frequency from %.2f to %.2f", 1.0 / rate.expectedCycleTime().toSec(), max_frequency);
rate = ros::Rate(max_frequency);
}
if (enableSwitched)
{
// Enable/disable switch: subscribe/unsubscribe to make use of pointcloud processing nodelet
// lazy publishing policy; in CPU-scarce computer as TurtleBot's laptop this is a huge saving
if (enabled)
cam_sub_ = it_.subscribe(cam_image_topic, 1, &getCapCallback);
else
cam_sub_.shutdown();
enableSwitched = false;
}
}
return 0;
}
| 36.968839 | 122 | 0.686513 | [
"transform"
] |
f6bdc29cfafea97433779ad296f81a54e5fbb3eb | 25,871 | cpp | C++ | gpac-0.7.1/applications/osmo4_w32/Osmo4.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | null | null | null | gpac-0.7.1/applications/osmo4_w32/Osmo4.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | null | null | null | gpac-0.7.1/applications/osmo4_w32/Osmo4.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 1 | 2021-04-15T18:27:37.000Z | 2021-04-15T18:27:37.000Z | // GPAC.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "Osmo4.h"
#include <gpac/network.h>
#include <direct.h>
#include "MainFrm.h"
#include "OpenUrl.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// Osmo4
BEGIN_MESSAGE_MAP(Osmo4, CWinApp)
//{{AFX_MSG_MAP(Osmo4)
ON_COMMAND(ID_OPEN_FILE, OnOpenFile)
ON_COMMAND(ID_FILE_STEP, OnFileStep)
ON_COMMAND(ID_OPEN_URL, OnOpenUrl)
ON_COMMAND(ID_FILE_RELOAD, OnFileReload)
ON_COMMAND(ID_CONFIG_RELOAD, OnConfigReload)
ON_COMMAND(ID_FILE_PLAY, OnFilePlay)
ON_UPDATE_COMMAND_UI(ID_FILE_PLAY, OnUpdateFilePlay)
ON_UPDATE_COMMAND_UI(ID_FILE_STEP, OnUpdateFileStep)
ON_COMMAND(ID_FILE_STOP, OnFileStop)
ON_UPDATE_COMMAND_UI(ID_FILE_STOP, OnUpdateFileStop)
ON_COMMAND(ID_SWITCH_RENDER, OnSwitchRender)
ON_UPDATE_COMMAND_UI(ID_FILE_RELOAD, OnUpdateFileStop)
ON_COMMAND(ID_H_ABOUT, OnAbout)
ON_COMMAND(ID_FILE_MIGRATE, OnFileMigrate)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Osmo4 construction
Osmo4::Osmo4()
{
}
/////////////////////////////////////////////////////////////////////////////
// The one and only Osmo4 object
Osmo4 theApp;
class UserPassDialog : public CDialog
{
// Construction
public:
UserPassDialog(CWnd* pParent = NULL); // standard constructor
Bool GetPassword(const char *site_url, char *user, char *password);
// Dialog Data
//{{AFX_DATA(UserPassDialog)
enum { IDD = IDD_PASSWD };
CStatic m_SiteURL;
CEdit m_User;
CEdit m_Pass;
//}}AFX_DATA
void SetSelection(u32 sel);
char cur_ext[200], cur_mime[200];
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(UserPassDialog)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
const char *m_site_url;
char *m_user, *m_password;
// Generated message map functions
//{{AFX_MSG(UserPassDialog)
virtual BOOL OnInitDialog();
afx_msg void OnClose();
//}}AFX_MSG
};
UserPassDialog::UserPassDialog(CWnd* pParent /*=NULL*/)
: CDialog(UserPassDialog::IDD, pParent)
{
//{{AFX_DATA_INIT(COptStream)
//}}AFX_DATA_INIT
}
void UserPassDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(UserPassDialog)
DDX_Control(pDX, IDC_TXT_SITE, m_SiteURL);
DDX_Control(pDX, IDC_EDIT_USER, m_User);
DDX_Control(pDX, IDC_EDIT_PASSWORD, m_Pass);
//}}AFX_DATA_MAP
}
BOOL UserPassDialog::OnInitDialog()
{
CDialog::OnInitDialog();
m_SiteURL.SetWindowText(m_site_url);
m_User.SetWindowText(m_user);
m_Pass.SetWindowText("");
return TRUE;
}
void UserPassDialog::OnClose()
{
m_User.GetWindowText(m_user, 50);
m_Pass.GetWindowText(m_password, 50);
}
Bool UserPassDialog::GetPassword(const char *site_url, char *user, char *password)
{
m_site_url = site_url;
m_user = user;
if (DoModal() != IDOK) return GF_FALSE;
return GF_TRUE;
}
static void Osmo4_progress_cbk(const void *usr, const char *title, u64 done, u64 total)
{
if (!total) return;
CMainFrame *pFrame = (CMainFrame *) ((Osmo4 *) usr)->m_pMainWnd;
s32 prog = (s32) ( (100 * (u64)done) / total);
if (pFrame->m_last_prog < prog) {
pFrame->console_err = GF_OK;
pFrame->m_last_prog = prog;
pFrame->console_message.Format("%s %02d %%", title, prog);
pFrame->PostMessage(WM_CONSOLEMSG, 0, 0);
if (done==total) pFrame->m_last_prog = -1;
}
}
#define W32_MIN_WIDTH 120
static void log_msg(char *msg)
{
::MessageBox(NULL, msg, "GPAC", MB_OK);
}
Bool Osmo4_EventProc(void *priv, GF_Event *evt)
{
u32 dur;
Osmo4 *gpac = (Osmo4 *) priv;
CMainFrame *pFrame = (CMainFrame *) gpac->m_pMainWnd;
/*shutdown*/
if (!pFrame) return GF_FALSE;
switch (evt->type) {
case GF_EVENT_DURATION:
dur = (u32) (1000 * evt->duration.duration);
//if (dur<1100) dur = 0;
pFrame->m_pPlayList->SetDuration((u32) evt->duration.duration );
gpac->max_duration = dur;
gpac->can_seek = evt->duration.can_seek;
if (!gpac->can_seek) {
pFrame->m_Sliders.m_PosSlider.EnableWindow(FALSE);
} else {
pFrame->m_Sliders.m_PosSlider.EnableWindow(TRUE);
pFrame->m_Sliders.m_PosSlider.SetRangeMin(0);
pFrame->m_Sliders.m_PosSlider.SetRangeMax(dur);
}
break;
case GF_EVENT_MESSAGE:
if (!evt->message.service || !strcmp(evt->message.service, (LPCSTR) pFrame->m_pPlayList->GetURL() )) {
pFrame->console_service = "main service";
} else {
pFrame->console_service = evt->message.service;
}
if (evt->message.error!=GF_OK) {
if (evt->message.error<GF_OK || !gpac->m_NoConsole) {
pFrame->console_err = evt->message.error;
pFrame->console_message = evt->message.message;
gpac->m_pMainWnd->PostMessage(WM_CONSOLEMSG, 0, 0);
/*any error before connection confirm is a service connection error*/
if (!gpac->m_isopen) pFrame->m_pPlayList->SetDead();
}
return GF_FALSE;
}
if (gpac->m_NoConsole) return GF_FALSE;
/*process user message*/
pFrame->console_err = GF_OK;
pFrame->console_message = evt->message.message;
gpac->m_pMainWnd->PostMessage(WM_CONSOLEMSG, 0, 0);
break;
case GF_EVENT_PROGRESS:
char *szType;
if (evt->progress.progress_type==0) szType = "Buffer ";
else if (evt->progress.progress_type==1) szType = "Download ";
else if (evt->progress.progress_type==2) szType = "Import ";
gf_set_progress(szType, evt->progress.done, evt->progress.total);
break;
case GF_EVENT_NAVIGATE_INFO:
pFrame->console_message = evt->navigate.to_url;
gpac->m_pMainWnd->PostMessage(WM_CONSOLEMSG, 1000, 0);
break;
case GF_EVENT_SCENE_SIZE:
if (evt->size.width && evt->size.height) {
gpac->orig_width = evt->size.width;
gpac->orig_height = evt->size.height;
if (gpac->m_term && !pFrame->m_bFullScreen)
pFrame->PostMessage(WM_SETSIZE, evt->size.width, evt->size.height);
}
break;
/*don't resize on win32 msg notif*/
#if 0
case GF_EVENT_SIZE:
if (/*gpac->m_term && !pFrame->m_bFullScreen && */gpac->orig_width && (evt->size.width < W32_MIN_WIDTH) )
pFrame->PostMessage(WM_SETSIZE, W32_MIN_WIDTH, (W32_MIN_WIDTH*gpac->orig_height) / gpac->orig_width);
else
pFrame->PostMessage(WM_SETSIZE, evt->size.width, evt->size.height);
break;
#endif
case GF_EVENT_CONNECT:
// if (pFrame->m_bStartupFile) return 0;
pFrame->BuildStreamList(GF_TRUE);
if (evt->connect.is_connected) {
pFrame->BuildChapterList(GF_FALSE);
gpac->m_isopen = GF_TRUE;
//resetting sliders when opening a new file creates a deadlock on the window thread which is disconnecting
pFrame->m_wndToolBar.SetButtonInfo(5, ID_FILE_PLAY, TBBS_BUTTON, gpac->m_isopen ? 4 : 3);
pFrame->m_Sliders.m_PosSlider.SetPos(0);
pFrame->SetProgTimer(GF_TRUE);
} else {
gpac->max_duration = 0;
gpac->m_isopen = GF_FALSE;
pFrame->BuildChapterList(GF_TRUE);
}
if (!pFrame->m_bFullScreen) {
pFrame->SetFocus();
pFrame->SetForegroundWindow();
}
break;
case GF_EVENT_QUIT:
pFrame->PostMessage(WM_CLOSE, 0L, 0L);
break;
case GF_EVENT_MIGRATE:
{
}
break;
case GF_EVENT_KEYDOWN:
gf_term_process_shortcut(gpac->m_term, evt);
/*update volume control*/
pFrame->m_Sliders.SetVolume();
switch (evt->key.key_code) {
case GF_KEY_HOME:
gf_term_set_option(gpac->m_term, GF_OPT_NAVIGATION_TYPE, 1);
break;
case GF_KEY_ESCAPE:
pFrame->PostMessage(WM_COMMAND, ID_VIEW_FULLSCREEN);
break;
case GF_KEY_MEDIANEXTTRACK:
pFrame->m_pPlayList->PlayNext();
break;
case GF_KEY_MEDIAPREVIOUSTRACK:
pFrame->m_pPlayList->PlayPrev();
break;
case GF_KEY_H:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && gpac->m_isopen)
gf_term_switch_quality(gpac->m_term, GF_TRUE);
break;
case GF_KEY_L:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && gpac->m_isopen)
gf_term_switch_quality(gpac->m_term, GF_FALSE);
break;
case GF_KEY_LEFT:
case GF_KEY_RIGHT:
if (gpac->m_isopen && (gf_term_get_option(gpac->m_term, GF_OPT_NAVIGATION) == GF_NAVIGATE_NONE)) {
if (evt->key.flags & GF_KEY_MOD_CTRL) {
if (evt->key.key_code==GF_KEY_LEFT) pFrame->m_pPlayList->PlayPrev();
else if (evt->key.key_code==GF_KEY_RIGHT) pFrame->m_pPlayList->PlayNext();
}
else if (gpac->can_seek && (evt->key.flags & GF_KEY_MOD_ALT)) {
u32 duration = gpac->max_duration;
s32 current_time = gf_term_get_time_in_ms(gpac->m_term);
if (evt->key.key_code==GF_KEY_LEFT) {
current_time -= 5*duration/100;
if (current_time<0) current_time=0;
gf_term_play_from_time(gpac->m_term, (u64) current_time, 0);
}
else if (evt->key.key_code==GF_KEY_RIGHT) {
current_time += 5*duration/100;
if ((u32) current_time < duration) {
gf_term_play_from_time(gpac->m_term, (u64) current_time, 0);
}
}
}
}
break;
}
break;
case GF_EVENT_NAVIGATE:
/*fixme - a proper browser would require checking mime type & co*/
/*store URL since it may be destroyed, and post message*/
gpac->m_navigate_url = evt->navigate.to_url;
pFrame->PostMessage(WM_NAVIGATE, NULL, NULL);
return GF_TRUE;
case GF_EVENT_VIEWPOINTS:
pFrame->BuildViewList();
return GF_FALSE;
case GF_EVENT_STREAMLIST:
pFrame->BuildStreamList(GF_FALSE);
return GF_FALSE;
case GF_EVENT_SET_CAPTION:
pFrame->SetWindowText(evt->caption.caption);
break;
case GF_EVENT_DBLCLICK:
pFrame->PostMessage(WM_COMMAND, ID_VIEW_FULLSCREEN);
return GF_FALSE;
case GF_EVENT_AUTHORIZATION:
{
UserPassDialog passdlg;
return passdlg.GetPassword(evt->auth.site_url, evt->auth.user, evt->auth.password);
}
}
return GF_FALSE;
}
/*here's the trick: use a storage section shared among all processes for the wnd handle and for the command line
NOTE: this has to be static memory of course, don't try to alloc anything there...*/
#pragma comment(linker, "/SECTION:.shr,RWS")
#pragma data_seg(".shr")
HWND static_gpac_hwnd = NULL;
char static_szCmdLine[MAX_PATH] = "";
#pragma data_seg()
const char *static_gpac_get_url()
{
return (const char *) static_szCmdLine;
}
static void osmo4_do_log(void *cbk, GF_LOG_Level level, GF_LOG_Tool tool, const char *fmt, va_list list)
{
FILE *logs = (FILE *) cbk;
vfprintf(logs, fmt, list);
fflush(logs);
}
BOOL Osmo4::InitInstance()
{
CCommandLineInfo cmdInfo;
afxAmbientActCtx = FALSE;
m_logs = NULL;
m_term = NULL;
memset(&m_user, 0, sizeof(GF_User));
/*get Osmo4.exe path*/
strcpy((char *) szApplicationPath, AfxGetApp()->m_pszHelpFilePath);
while (szApplicationPath[strlen((char *) szApplicationPath)-1] != '\\') szApplicationPath[strlen((char *) szApplicationPath)-1] = 0;
if (szApplicationPath[strlen((char *) szApplicationPath)-1] != '\\') strcat(szApplicationPath, "\\");
gf_sys_init(GF_MemTrackerNone);
/*setup user*/
memset(&m_user, 0, sizeof(GF_User));
Bool first_launch = GF_FALSE;
/*init config and modules*/
m_user.config = gf_cfg_init(NULL, &first_launch);
if (!m_user.config) {
MessageBox(NULL, "GPAC Configuration file not found", "Fatal Error", MB_OK);
m_pMainWnd->PostMessage(WM_CLOSE);
}
char *name = gf_cfg_get_filename(m_user.config);
char *sep = strrchr(name, '\\');
if (sep) sep[0] = 0;
strcpy(szUserPath, name);
if (sep) sep[0] = '\\';
gf_free(name);
const char *opt = gf_cfg_get_key(m_user.config, "General", "SingleInstance");
m_SingleInstance = (opt && !stricmp(opt, "yes")) ? GF_TRUE : GF_FALSE;
m_hMutex = NULL;
if (m_SingleInstance) {
m_hMutex = CreateMutex(NULL, FALSE, "Osmo4_GPAC_INSTANCE");
if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
char szDIR[1024];
if (m_hMutex) CloseHandle(m_hMutex);
m_hMutex = NULL;
if (!static_gpac_hwnd || !IsWindow(static_gpac_hwnd) ) {
::MessageBox(NULL, "Osmo4 ghost process detected", "Error at last shutdown" , MB_OK);
} else {
::SetForegroundWindow(static_gpac_hwnd);
if (m_lpCmdLine && strlen(m_lpCmdLine)) {
DWORD_PTR res;
size_t len;
char *the_url, *cmd;
GetCurrentDirectory(1024, szDIR);
if (szDIR[strlen(szDIR)-1] != '\\') strcat(szDIR, "\\");
cmd = (char *)(const char *) m_lpCmdLine;
strcpy(static_szCmdLine, "");
if (cmd[0]=='"') cmd+=1;
if (!strnicmp(cmd, "-queue ", 7)) {
strcat(static_szCmdLine, "-queue ");
cmd += 7;
}
the_url = gf_url_concatenate(szDIR, cmd);
if (!the_url) {
strcat(static_szCmdLine, cmd);
} else {
strcat(static_szCmdLine, the_url);
gf_free(the_url);
}
while ( (len = strlen(static_szCmdLine)) ) {
char s = static_szCmdLine[len-1];
if ((s==' ') || (s=='"')) static_szCmdLine[len-1]=0;
else break;
}
::SendMessageTimeout(static_gpac_hwnd, WM_NEWINSTANCE, 0, 0, 0, 1000, &res);
}
}
return FALSE;
}
}
#if 0
// Standard initialization
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
#endif
SetRegistryKey(_T("GPAC"));
CMainFrame* pFrame = new CMainFrame;
m_pMainWnd = pFrame;
pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL);
pFrame->LoadAccelTable( MAKEINTRESOURCE(IDR_MAINACCEL));
m_pMainWnd->DragAcceptFiles();
if (m_SingleInstance) static_gpac_hwnd = m_pMainWnd->m_hWnd;
m_user.modules = gf_modules_new(NULL, m_user.config);
if (!m_user.modules || ! gf_modules_get_count(m_user.modules) ) {
MessageBox(NULL, "No modules available - system cannot work", "Fatal Error", MB_OK);
m_pMainWnd->PostMessage(WM_CLOSE);
}
else if (first_launch) {
/*first launch, register all files ext*/
u32 i;
for (i=0; i<gf_modules_get_count(m_user.modules); i++) {
GF_InputService *ifce = (GF_InputService *) gf_modules_load_interface(m_user.modules, i, GF_NET_CLIENT_INTERFACE);
if (!ifce) continue;
if (ifce) {
ifce->CanHandleURL(ifce, "test.test");
gf_modules_close_interface((GF_BaseInterface *)ifce);
}
}
/*set some shortcuts*/
gf_cfg_set_key(m_user.config, "Shortcuts", "VolumeUp", "ctrl+Up");
gf_cfg_set_key(m_user.config, "Shortcuts", "VolumeDown", "ctrl+Down");
gf_cfg_set_key(m_user.config, "Shortcuts", "FastRewind", "ctrl+Left");
gf_cfg_set_key(m_user.config, "Shortcuts", "FastForward", "ctrl+Right");
gf_cfg_set_key(m_user.config, "Shortcuts", "Play", "ctrl+ ");
}
/*check log file*/
const char *str = gf_cfg_get_key(m_user.config, "General", "LogFile");
if (str) {
m_logs = gf_fopen(str, "wt");
gf_log_set_callback(m_logs, osmo4_do_log);
}
else m_logs = NULL;
/*set log level*/
if (gf_log_set_tools_levels(gf_cfg_get_key(m_user.config, "General", "Logs")) != GF_OK)
fprintf(stdout, "osmo4: invalid log level specified\n");
m_user.opaque = this;
m_user.os_window_handler = pFrame->m_pWndView->m_hWnd;
m_user.EventProc = Osmo4_EventProc;
m_reset = GF_FALSE;
orig_width = 320;
orig_height = 240;
gf_set_progress_callback(this, Osmo4_progress_cbk);
m_term = gf_term_new(&m_user);
if (! m_term) {
MessageBox(NULL, "Cannot load GPAC Terminal", "Fatal Error", MB_OK);
m_pMainWnd->PostMessage(WM_CLOSE);
return TRUE;
}
SetOptions();
UpdateRenderSwitch();
pFrame->SendMessage(WM_SETSIZE, orig_width, orig_height);
pFrame->m_Address.ReloadURLs();
pFrame->m_Sliders.SetVolume();
m_reconnect_time = 0;
ParseCommandLine(cmdInfo);
start_mode = 0;
if (! cmdInfo.m_strFileName.IsEmpty()) {
pFrame->m_pPlayList->QueueURL(cmdInfo.m_strFileName);
pFrame->m_pPlayList->RefreshList();
pFrame->m_pPlayList->PlayNext();
} else {
char sPL[MAX_PATH];
strcpy((char *) sPL, szUserPath);
strcat(sPL, "gpac_pl.m3u");
pFrame->m_pPlayList->OpenPlayList(sPL);
const char *sOpt = gf_cfg_get_key(GetApp()->m_user.config, "General", "PLEntry");
if (sOpt) {
s32 count = (s32)gf_list_count(pFrame->m_pPlayList->m_entries);
pFrame->m_pPlayList->m_cur_entry = atoi(sOpt);
if (pFrame->m_pPlayList->m_cur_entry>=count)
pFrame->m_pPlayList->m_cur_entry = count-1;
} else {
pFrame->m_pPlayList->m_cur_entry = -1;
}
#if 0
if (pFrame->m_pPlayList->m_cur_entry>=0) {
start_mode = 1;
pFrame->m_pPlayList->Play();
}
#endif
sOpt = gf_cfg_get_key(m_user.config, "General", "StartupFile");
if (sOpt && !strstr(sOpt, "gui") ) gf_term_connect(m_term, sOpt);
sOpt = gf_cfg_get_key(m_user.config, "General", "PlaylistLoop");
m_Loop = (sOpt && !strcmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
}
pFrame->SetFocus();
pFrame->SetForegroundWindow();
return TRUE;
}
int Osmo4::ExitInstance()
{
if (m_term) gf_term_del(m_term);
if (m_user.modules) gf_modules_del(m_user.modules);
if (m_user.config) gf_cfg_del(m_user.config);
gf_sys_close();
/*last instance*/
if (m_hMutex) {
CloseHandle(m_hMutex);
static_gpac_hwnd = NULL;
}
if (m_logs) gf_fclose(m_logs);
return CWinApp::ExitInstance();
}
/////////////////////////////////////////////////////////////////////////////
// Osmo4 message handlers
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
virtual BOOL OnInitDialog();
afx_msg void OnGogpac();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
ON_BN_CLICKED(IDC_GOGPAC, OnGogpac)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void Osmo4::OnAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CString str = "GPAC/Osmo4 - version " GPAC_FULL_VERSION;
SetWindowText(str);
return TRUE;
}
void CAboutDlg::OnGogpac()
{
ShellExecute(NULL, "open", "http://gpac.sourceforge.net", NULL, NULL, SW_SHOWNORMAL);
}
/////////////////////////////////////////////////////////////////////////////
// Osmo4 message handlers
void Osmo4::SetOptions()
{
const char *sOpt = gf_cfg_get_key(m_user.config, "General", "Loop");
m_Loop = (sOpt && !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
sOpt = gf_cfg_get_key(m_user.config, "General", "LookForSubtitles");
m_LookForSubtitles = (sOpt && !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
sOpt = gf_cfg_get_key(m_user.config, "General", "ConsoleOff");
m_NoConsole = (sOpt && !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
sOpt = gf_cfg_get_key(m_user.config, "General", "ViewXMT");
m_ViewXMTA = (sOpt && !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
sOpt = gf_cfg_get_key(m_user.config, "General", "NoMIMETypeFetch");
m_NoMimeFetch = (!sOpt || !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
}
void Osmo4::OnOpenUrl()
{
COpenUrl url;
if (url.DoModal() != IDOK) return;
CMainFrame *pFrame = (CMainFrame *) m_pMainWnd;
pFrame->m_pPlayList->Truncate();
pFrame->m_pPlayList->QueueURL(url.m_url);
pFrame->m_pPlayList->RefreshList();
pFrame->m_pPlayList->PlayNext();
}
CString Osmo4::GetFileFilter()
{
u32 keyCount, i;
CString sFiles;
CString sExts;
CString supportedFiles;
/*force MP4 and 3GP files at beginning to make sure they are selected (Win32 bug with too large filters)*/
supportedFiles = "All Known Files|*.m3u;*.pls;*.mp4;*.3gp;*.3g2";
sExts = "";
sFiles = "";
keyCount = gf_cfg_get_key_count(m_user.config, "MimeTypes");
for (i=0; i<keyCount; i++) {
const char *sMime;
Bool first;
char *sKey;
const char *opt;
char szKeyList[1000], sDesc[1000];
sMime = gf_cfg_get_key_name(m_user.config, "MimeTypes", i);
if (!sMime) continue;
CString sOpt;
opt = gf_cfg_get_key(m_user.config, "MimeTypes", sMime);
/*remove module name*/
strcpy(szKeyList, opt+1);
sKey = strrchr(szKeyList, '\"');
if (!sKey) continue;
sKey[0] = 0;
/*get description*/
sKey = strrchr(szKeyList, '\"');
if (!sKey) continue;
strcpy(sDesc, sKey+1);
sKey[0] = 0;
sKey = strrchr(szKeyList, '\"');
if (!sKey) continue;
sKey[0] = 0;
/*if same description for # mime types skip (means an old mime syntax)*/
if (sFiles.Find(sDesc)>=0) continue;
/*if same extensions for # mime types skip (don't polluate the file list)*/
if (sExts.Find(szKeyList)>=0) continue;
sExts += szKeyList;
sExts += " ";
sFiles += sDesc;
sFiles += "|";
first = GF_TRUE;
sOpt = CString(szKeyList);
while (1) {
int pos = sOpt.Find(' ');
CString ext = (pos==-1) ? sOpt : sOpt.Left(pos);
/*WATCHOUT: we do have some "double" ext , eg .wrl.gz - these are NOT supported by windows*/
if (ext.Find(".")<0) {
if (!first) {
sFiles += ";";
} else {
first = GF_FALSE;
}
sFiles += "*.";
sFiles += ext;
CString sext = ext;
sext += ";";
if (supportedFiles.Find(sext)<0) {
supportedFiles += ";*.";
supportedFiles += ext;
}
}
if (sOpt==ext) break;
CString rem;
rem.Format("%s ", (LPCTSTR) ext);
sOpt.Replace((LPCTSTR) rem, "");
}
sFiles += "|";
}
supportedFiles += "|";
supportedFiles += sFiles;
supportedFiles += "M3U Playlists|*.m3u|ShoutCast Playlists|*.pls|All Files |*.*|";
return supportedFiles;
}
void Osmo4::OnOpenFile()
{
CString sFiles = GetFileFilter();
u32 nb_items;
/*looks like there's a bug here, main filter isn't used correctly while the others are*/
CFileDialog fd(TRUE,NULL,NULL, OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY | OFN_FILEMUSTEXIST , sFiles);
fd.m_ofn.nMaxFile = 25000;
fd.m_ofn.lpstrFile = (char *) gf_malloc(sizeof(char) * fd.m_ofn.nMaxFile);
fd.m_ofn.lpstrFile[0] = 0;
if (fd.DoModal()!=IDOK) {
gf_free(fd.m_ofn.lpstrFile);
return;
}
CMainFrame *pFrame = (CMainFrame *) m_pMainWnd;
nb_items = 0;
POSITION pos = fd.GetStartPosition();
while (pos) {
CString file = fd.GetNextPathName(pos);
nb_items++;
}
/*if several items, act as playlist (replace playlist), otherwise as browser (lost all "next" context)*/
if (nb_items==1)
pFrame->m_pPlayList->Truncate();
else
pFrame->m_pPlayList->Clear();
pos = fd.GetStartPosition();
while (pos) {
CString file = fd.GetNextPathName(pos);
pFrame->m_pPlayList->QueueURL(file);
}
gf_free(fd.m_ofn.lpstrFile);
pFrame->m_pPlayList->RefreshList();
pFrame->m_pPlayList->PlayNext();
}
void Osmo4::Pause()
{
if (!m_isopen) return;
gf_term_set_option(m_term, GF_OPT_PLAY_STATE, (gf_term_get_option(m_term, GF_OPT_PLAY_STATE)==GF_STATE_PLAYING) ? GF_STATE_PAUSED : GF_STATE_PLAYING);
}
void Osmo4::OnMainPause()
{
Pause();
}
void Osmo4::OnFileStep()
{
gf_term_set_option(m_term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE);
((CMainFrame *) m_pMainWnd)->m_wndToolBar.SetButtonInfo(5, ID_FILE_PLAY, TBBS_BUTTON, 3);
}
void Osmo4::OnUpdateFileStep(CCmdUI* pCmdUI)
{
pCmdUI->Enable(m_isopen && !m_reset);
}
void Osmo4::PlayFromTime(u32 time)
{
Bool do_pause;
if (start_mode==1) do_pause = GF_TRUE;
else if (start_mode==2) do_pause = GF_FALSE;
else do_pause = /*!m_AutoPlay*/GF_FALSE;
gf_term_play_from_time(m_term, time, do_pause);
m_reset = GF_FALSE;
}
void Osmo4::OnFileReload()
{
gf_term_disconnect(m_term);
m_pMainWnd->PostMessage(WM_OPENURL);
}
void Osmo4::OnFileMigrate()
{
}
void Osmo4::OnConfigReload()
{
gf_term_set_option(m_term, GF_OPT_RELOAD_CONFIG, 1);
}
void Osmo4::UpdatePlayButton(Bool force_play)
{
if (!force_play && gf_term_get_option(m_term, GF_OPT_PLAY_STATE)==GF_STATE_PLAYING) {
((CMainFrame *) m_pMainWnd)->m_wndToolBar.SetButtonInfo(5, ID_FILE_PLAY, TBBS_BUTTON, 4);
} else {
((CMainFrame *) m_pMainWnd)->m_wndToolBar.SetButtonInfo(5, ID_FILE_PLAY, TBBS_BUTTON, 3);
}
}
void Osmo4::OnFilePlay()
{
if (m_isopen) {
if (m_reset) {
m_reset = GF_FALSE;
PlayFromTime(0);
((CMainFrame *)m_pMainWnd)->SetProgTimer(GF_TRUE);
} else {
Pause();
}
UpdatePlayButton();
} else {
((CMainFrame *) m_pMainWnd)->m_pPlayList->Play();
}
}
void Osmo4::OnUpdateFilePlay(CCmdUI* pCmdUI)
{
if (m_isopen) {
pCmdUI->Enable(TRUE);
if (pCmdUI->m_nID==ID_FILE_PLAY) {
if (!m_isopen) {
pCmdUI->SetText("Play/Pause\tCtrl+P");
} else if (gf_term_get_option(m_term, GF_OPT_PLAY_STATE)==GF_STATE_PLAYING) {
pCmdUI->SetText("Pause\tCtrl+P");
} else {
pCmdUI->SetText("Resume\tCtrl+P");
}
}
} else {
pCmdUI->Enable(((CMainFrame *)m_pMainWnd)->m_pPlayList->HasValidEntries() );
pCmdUI->SetText("Play\tCtrl+P");
}
}
void Osmo4::OnFileStop()
{
CMainFrame *pFrame = (CMainFrame *) m_pMainWnd;
if (m_reset) return;
if (gf_term_get_option(m_term, GF_OPT_PLAY_STATE)==GF_STATE_PLAYING) Pause();
m_reset = GF_TRUE;
pFrame->m_Sliders.m_PosSlider.SetPos(0);
pFrame->SetProgTimer(GF_FALSE);
pFrame->m_wndToolBar.SetButtonInfo(5, ID_FILE_PLAY, TBBS_BUTTON, 3);
start_mode = 2;
}
void Osmo4::OnUpdateFileStop(CCmdUI* pCmdUI)
{
// pCmdUI->Enable(m_isopen);
}
void Osmo4::OnSwitchRender()
{
const char *opt = gf_cfg_get_key(m_user.config, "Compositor", "OpenGLMode");
Bool use_gl = (opt && !stricmp(opt, "always")) ? GF_TRUE : GF_FALSE;
gf_cfg_set_key(m_user.config, "Compositor", "OpenGLMode", use_gl ? "disable" : "always");
gf_term_set_option(m_term, GF_OPT_USE_OPENGL, !use_gl);
UpdateRenderSwitch();
}
void Osmo4::UpdateRenderSwitch()
{
const char *opt = gf_cfg_get_key(m_user.config, "Compositor", "OpenGLMode");
if (opt && !stricmp(opt, "disable"))
((CMainFrame *) m_pMainWnd)->m_wndToolBar.SetButtonInfo(12, ID_SWITCH_RENDER, TBBS_BUTTON, 10);
else
((CMainFrame *) m_pMainWnd)->m_wndToolBar.SetButtonInfo(12, ID_SWITCH_RENDER, TBBS_BUTTON, 9);
}
| 27.34778 | 151 | 0.68857 | [
"object"
] |
f6be1ed99d014d1bede1acdbb17d0f77e48f41f0 | 3,847 | cc | C++ | lib/application/lines_renderable.cc | tdelame/Graphics-Origin | 27b7d6ac72c4cb1858fc85dc18fe864de1496c6d | [
"MIT"
] | null | null | null | lib/application/lines_renderable.cc | tdelame/Graphics-Origin | 27b7d6ac72c4cb1858fc85dc18fe864de1496c6d | [
"MIT"
] | null | null | null | lib/application/lines_renderable.cc | tdelame/Graphics-Origin | 27b7d6ac72c4cb1858fc85dc18fe864de1496c6d | [
"MIT"
] | null | null | null | # include "../../graphics-origin/application/renderables/lines_renderable.h"
# include "../../graphics-origin/application/renderer.h"
# include "../../graphics-origin/application/gl_helper.h"
# include <GL/glew.h>
namespace graphics_origin { namespace application {
lines_renderable::storage::storage()
{}
lines_renderable::storage&
lines_renderable::storage::operator=( storage&& other )
{
p1 = other.p1;
color1 = other.color1;
p2 = other.p2;
color2 = other.color2;
return *this;
}
lines_renderable::storage&
lines_renderable::storage::operator=( const storage& other )
{
p1 = other.p1;
color1 = other.color1;
p2 = other.p2;
color2 = other.color2;
return *this;
}
lines_renderable::storage::storage( const storage& other )
: p1{ other.p1 }, color1{ other.color1 }, p2{ other.p2 }, color2{ other.color2}
{}
lines_renderable::lines_renderable(
shader_program_ptr program,
size_t expected_number_of_lines )
: m_lines{ expected_number_of_lines },
m_vao{ 0 }, m_lines_vbo{ 0 }
{
model = gl_mat4(1.0);
this->program = program;
}
lines_renderable::lines_buffer::handle
lines_renderable::add(
const gl_vec3& p1, const gl_vec3& color1,
const gl_vec3& p2, const gl_vec3& color2 )
{
m_dirty = true;
auto pair = m_lines.create();
pair.second.p1 = p1;
pair.second.color1 = color1;
pair.second.p2 = p2;
pair.second.color2 = color2;
return pair.first;
}
void
lines_renderable::remove( lines_buffer::handle handle )
{
m_lines.remove( handle );
m_dirty = true;
}
void
lines_renderable::update_gpu_data()
{
if( !m_vao )
{
glcheck(glGenVertexArrays( 1, &m_vao ));
glcheck(glGenBuffers( 1, &m_lines_vbo ) );
}
int position_location = program->get_attribute_location( "position" );
int color_location = program->get_attribute_location( "color" );
glcheck(glBindVertexArray( m_vao ));
glcheck(glBindBuffer( GL_ARRAY_BUFFER, m_lines_vbo ));
glcheck(glBufferData( GL_ARRAY_BUFFER, sizeof(storage) * m_lines.get_size(), m_lines.data(), GL_STATIC_DRAW ));
glcheck(glEnableVertexAttribArray( position_location ));
glcheck(glVertexAttribPointer( position_location, // format of center:
3, GL_FLOAT, GL_FALSE, // 3 unnormalized floats
sizeof(storage)>>1, // each attribute has the size of storage
reinterpret_cast<void*>(offsetof(storage,p1)))); // offset of the center inside an attribute
glcheck(glEnableVertexAttribArray( color_location ));
glcheck(glVertexAttribPointer( color_location, // format of color:
4, GL_FLOAT, GL_FALSE, // 4 unnormalized floats
sizeof(storage)>>1, // each attribute has the size of storage
reinterpret_cast<void*>(offsetof(storage,color1))));// offset of the color inside an attribute
glcheck(glBindVertexArray( 0 ));
}
void
lines_renderable::do_render()
{
gl_mat4 temp = renderer_ptr->get_projection_matrix() * renderer_ptr->get_view_matrix() * model;
glcheck(glUniformMatrix4fv( program->get_uniform_location( "mvp"), 1, GL_FALSE, glm::value_ptr(temp)));
glcheck(glLineWidth(2.5));
glcheck(glBindVertexArray( m_vao ));
glcheck(glDrawArrays( GL_LINES, 0, m_lines.get_size() * 2));
glcheck(glBindVertexArray( 0 ) );
}
void
lines_renderable::remove_gpu_data()
{
if( m_vao )
{
glcheck(glDeleteBuffers( 1, &m_lines_vbo ));
glcheck(glDeleteVertexArrays( 1, &m_vao ));
m_lines_vbo = (unsigned int)0;
m_vao = (unsigned int)0;
}
}
lines_renderable::~lines_renderable()
{
remove_gpu_data();
}
}}
| 31.024194 | 117 | 0.646998 | [
"model"
] |
f6be5f7935719c59a88b570c78a59eb6ef7d7671 | 6,979 | cpp | C++ | metrics/src/vespa/metrics/metric.cpp | atveit/vespa | 545898728f29a9ed7fcae223bfb0c85f24227af8 | [
"Apache-2.0"
] | null | null | null | metrics/src/vespa/metrics/metric.cpp | atveit/vespa | 545898728f29a9ed7fcae223bfb0c85f24227af8 | [
"Apache-2.0"
] | 1 | 2021-01-21T01:37:37.000Z | 2021-01-21T01:37:37.000Z | metrics/src/vespa/metrics/metric.cpp | atveit/vespa | 545898728f29a9ed7fcae223bfb0c85f24227af8 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "metric.h"
#include "countmetric.h"
#include "valuemetric.h"
#include "metricset.h"
#include "namehash.h"
#include <vespa/vespalib/text/stringtokenizer.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <iterator>
#include <cassert>
#include <algorithm>
namespace metrics {
bool
MetricVisitor::visitCountMetric(const AbstractCountMetric& m, bool autoGenerated)
{
return visitMetric(m, autoGenerated);
}
bool
MetricVisitor::visitValueMetric(const AbstractValueMetric& m, bool autoGenerated)
{
return visitMetric(m, autoGenerated);
}
bool
MetricVisitor::visitMetric(const Metric&, bool)
{
throw vespalib::IllegalStateException(
"visitMetric called with default implementation. You should either "
"override specific visit functions or this catchall function.",
VESPA_STRLOC);
}
namespace {
Metric::Tags legacyTagStringToKeyedTags(const std::string& tagStr) {
vespalib::StringTokenizer tokenizer(tagStr, " \t\r\f");
Metric::Tags tags;
std::transform(tokenizer.getTokens().begin(),
tokenizer.getTokens().end(),
std::back_inserter(tags),
[](const std::string& s) { return Tag(s, ""); });
return tags;
}
std::string namePattern = "[a-zA-Z][_a-zA-Z0-9]*";
}
vespalib::Regexp Metric::_namePattern(namePattern);
Tag::Tag(vespalib::stringref k, vespalib::stringref v)
: key(k),
value(v)
{ }
Tag::Tag(const Tag &) = default;
Tag & Tag::operator = (const Tag &) = default;
Tag::~Tag() {}
Metric::Metric(const String& name,
const String& tags,
const String& description,
MetricSet* owner)
: _name(name),
_description(description),
_tags(legacyTagStringToKeyedTags(tags)),
_owner(nullptr) // Set later by registry
{
verifyConstructionParameters();
assignMangledNameWithDimensions();
registerWithOwnerIfRequired(owner);
}
Metric::Metric(const String& name,
Tags dimensions,
const String& description,
MetricSet* owner)
: _name(name),
_description(description),
_tags(std::move(dimensions)),
_owner(nullptr)
{
verifyConstructionParameters();
assignMangledNameWithDimensions();
registerWithOwnerIfRequired(owner);
}
Metric::Metric(const Metric& other, MetricSet* owner)
: Printable(other),
_name(other._name),
_description(other._description),
_tags(other._tags),
_owner(nullptr)
{
assignMangledNameWithDimensions();
registerWithOwnerIfRequired(owner);
}
Metric::Metric(const Metric& rhs) = default;
Metric & Metric::operator =(const Metric& rhs) = default;
Metric::~Metric() { }
bool
Metric::tagsSpecifyAtLeastOneDimension(const Tags& tags) const
{
auto hasNonEmptyTagValue = [](const Tag& t) { return !t.value.empty(); };
return std::any_of(tags.begin(), tags.end(), hasNonEmptyTagValue);
}
void
Metric::assignMangledNameWithDimensions()
{
if (!tagsSpecifyAtLeastOneDimension(_tags)) {
return;
}
sortTagsInDeterministicOrder();
_mangledName = createMangledNameWithDimensions();
}
void
Metric::sortTagsInDeterministicOrder()
{
std::sort(_tags.begin(), _tags.end(), [](const Tag& a, const Tag& b) {
return a.key < b.key;
});
}
std::string
Metric::createMangledNameWithDimensions() const
{
vespalib::asciistream s;
s << _name << '{';
const size_t sz = _tags.size();
for (size_t i = 0; i < sz; ++i) {
const Tag& dimension(_tags[i]);
if (dimension.value.empty()) {
continue;
}
if (i != 0) {
s << ',';
}
s << dimension.key << ':' << dimension.value;
}
s << '}';
return s.str();
}
void
Metric::verifyConstructionParameters()
{
if (_name.size() == 0) {
throw vespalib::IllegalArgumentException(
"Metric cannot have empty name", VESPA_STRLOC);
}
if (!_namePattern.match(_name)) {
throw vespalib::IllegalArgumentException(
"Illegal metric name '" + _name + "'. Names must match pattern "
+ namePattern, VESPA_STRLOC);
}
}
void
Metric::registerWithOwnerIfRequired(MetricSet* owner)
{
if (owner) {
owner->registerMetric(*this);
}
}
const MetricSet*
Metric::getRoot() const
{
return (_owner == 0 ? (isMetricSet() ? static_cast<const MetricSet*>(this)
: 0)
: _owner->getRoot());
}
vespalib::string
Metric::getPath() const
{
if (_owner == 0 || _owner->_owner == 0) {
return _name;
} else {
return _owner->getPath() + "." + _name;
}
}
std::vector<Metric::String>
Metric::getPathVector() const
{
std::vector<String> result;
result.push_back(_name);
const MetricSet* owner(_owner);
while (owner != 0) {
result.push_back(owner->_name);
owner = owner->_owner;
}
std::reverse(result.begin(), result.end());
return result;
}
bool
Metric::hasTag(const String& tag) const
{
return std::find_if(_tags.begin(), _tags.end(), [&](const Tag& t) {
return t.key == tag;
}) != _tags.end();
}
void
Metric::addMemoryUsage(MemoryConsumption& mc) const
{
++mc._metricCount;
mc._metricName += mc.getStringMemoryUsage(_name, mc._metricNameUnique);
mc._metricDescription += mc.getStringMemoryUsage(
_description, mc._metricDescriptionUnique);
mc._metricTagCount += _tags.size();
// XXX figure out what we actually want to report from tags here...
// XXX we don't care about unique strings since they don't matter anymore.
//mc._metricTags += mc.getStringMemoryUsage(_tags, mc._metricTagsUnique);
mc._metricMeta += sizeof(Metric);
}
void
Metric::updateNames(NameHash& hash) const
{
Metric& m(const_cast<Metric&>(*this));
hash.updateName(m._name);
hash.updateName(m._description);
// Tags use vespalib::string which isn't refcounted under the hood and
// use small string optimizations, meaning the implicit ref sharing hack
// won't work for them anyway.
}
void
Metric::printDebug(std::ostream& out, const std::string& indent) const
{
(void) indent;
out << "name=" << _name << ", instance=" << ((const void*) this)
<< ", owner=" << ((const void*) _owner);
}
Metric*
Metric::assignValues(const Metric& m) {
std::vector<Metric::UP> ownerList;
const_cast<Metric&>(m).addToSnapshot(*this, ownerList);
// As this should only be called among active metrics, all metrics
// should exist and owner list should thus always end up empty.
assert(ownerList.empty());
return this;
}
} // metrics
| 27.050388 | 118 | 0.639347 | [
"vector",
"transform"
] |
f6bf6adc75410db41a0e623c34a569264cbb6da8 | 10,576 | cpp | C++ | Userland/Applications/Help/main.cpp | Camisul/serenity | 7cf0c7cc0d74b84b0a2cc6f180914178cbb9ea20 | [
"BSD-2-Clause"
] | 2 | 2021-02-10T17:03:23.000Z | 2021-11-08T09:58:24.000Z | Userland/Applications/Help/main.cpp | Camisul/serenity | 7cf0c7cc0d74b84b0a2cc6f180914178cbb9ea20 | [
"BSD-2-Clause"
] | 78 | 2020-08-25T08:13:30.000Z | 2021-03-02T10:20:05.000Z | Userland/Applications/Help/main.cpp | Camisul/serenity | 7cf0c7cc0d74b84b0a2cc6f180914178cbb9ea20 | [
"BSD-2-Clause"
] | 1 | 2021-06-10T00:18:29.000Z | 2021-06-10T00:18:29.000Z | /*
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "History.h"
#include "ManualModel.h"
#include <AK/URL.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <LibDesktop/Launcher.h>
#include <LibGUI/Action.h>
#include <LibGUI/Application.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/FilteringProxyModel.h>
#include <LibGUI/ListView.h>
#include <LibGUI/Menu.h>
#include <LibGUI/MenuBar.h>
#include <LibGUI/MessageBox.h>
#include <LibGUI/Splitter.h>
#include <LibGUI/TabWidget.h>
#include <LibGUI/TextBox.h>
#include <LibGUI/ToolBar.h>
#include <LibGUI/ToolBarContainer.h>
#include <LibGUI/TreeView.h>
#include <LibGUI/Window.h>
#include <LibMarkdown/Document.h>
#include <LibWeb/OutOfProcessWebView.h>
#include <libgen.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
if (pledge("stdio recvfd sendfd accept rpath unix cpath fattr", nullptr) < 0) {
perror("pledge");
return 1;
}
auto app = GUI::Application::construct(argc, argv);
if (pledge("stdio recvfd sendfd accept rpath unix", nullptr) < 0) {
perror("pledge");
return 1;
}
if (unveil("/res", "r") < 0) {
perror("unveil");
return 1;
}
if (unveil("/usr/share/man", "r") < 0) {
perror("unveil");
return 1;
}
if (unveil("/tmp/portal/launch", "rw") < 0) {
perror("unveil");
return 1;
}
if (unveil("/tmp/portal/webcontent", "rw") < 0) {
perror("unveil");
return 1;
}
unveil(nullptr, nullptr);
const char* start_page = nullptr;
Core::ArgsParser args_parser;
args_parser.add_positional_argument(start_page, "Page to open at launch", "page", Core::ArgsParser::Required::No);
args_parser.parse(argc, argv);
auto app_icon = GUI::Icon::default_icon("app-help");
auto window = GUI::Window::construct();
window->set_icon(app_icon.bitmap_for_size(16));
window->set_title("Help");
window->resize(570, 500);
auto& widget = window->set_main_widget<GUI::Widget>();
widget.set_layout<GUI::VerticalBoxLayout>();
widget.set_fill_with_background_color(true);
widget.layout()->set_spacing(2);
auto& toolbar_container = widget.add<GUI::ToolBarContainer>();
auto& toolbar = toolbar_container.add<GUI::ToolBar>();
auto& splitter = widget.add<GUI::HorizontalSplitter>();
auto model = ManualModel::create();
auto& left_tab_bar = splitter.add<GUI::TabWidget>();
auto& tree_view_container = left_tab_bar.add_tab<GUI::Widget>("Browse");
tree_view_container.set_layout<GUI::VerticalBoxLayout>();
tree_view_container.layout()->set_margins({ 4, 4, 4, 4 });
auto& tree_view = tree_view_container.add<GUI::TreeView>();
auto& search_view = left_tab_bar.add_tab<GUI::Widget>("Search");
search_view.set_layout<GUI::VerticalBoxLayout>();
search_view.layout()->set_margins({ 4, 4, 4, 4 });
auto& search_box = search_view.add<GUI::TextBox>();
auto& search_list_view = search_view.add<GUI::ListView>();
search_box.set_fixed_height(20);
search_box.set_placeholder("Search...");
search_box.on_change = [&] {
if (auto model = search_list_view.model()) {
auto& search_model = *static_cast<GUI::FilteringProxyModel*>(model);
search_model.set_filter_term(search_box.text());
search_model.update();
}
};
search_list_view.set_model(GUI::FilteringProxyModel::construct(model));
search_list_view.model()->update();
tree_view.set_model(model);
left_tab_bar.set_fixed_width(200);
auto& page_view = splitter.add<Web::OutOfProcessWebView>();
History history;
RefPtr<GUI::Action> go_back_action;
RefPtr<GUI::Action> go_forward_action;
auto update_actions = [&]() {
go_back_action->set_enabled(history.can_go_back());
go_forward_action->set_enabled(history.can_go_forward());
};
auto open_page = [&](const String& path) {
if (path.is_null()) {
window->set_title("Help");
page_view.load_empty_document();
return;
}
auto source_result = model->page_view(path);
if (source_result.is_error()) {
GUI::MessageBox::show(window, source_result.error().string(), "Failed to open man page", GUI::MessageBox::Type::Error);
return;
}
auto source = source_result.value();
String html;
{
auto md_document = Markdown::Document::parse(source);
ASSERT(md_document);
html = md_document->render_to_html();
}
auto url = URL::create_with_file_protocol(path);
page_view.load_html(html, url);
auto tree_view_index = model->index_from_path(path);
if (tree_view_index.has_value())
tree_view.expand_tree(tree_view_index.value().parent());
String page_and_section = model->page_and_section(tree_view_index.value());
window->set_title(String::formatted("{} - Help", page_and_section));
};
tree_view.on_selection_change = [&] {
String path = model->page_path(tree_view.selection().first());
history.push(path);
update_actions();
open_page(path);
};
tree_view.on_toggle = [&](const GUI::ModelIndex& index, const bool open) {
model->update_section_node_on_toggle(index, open);
};
auto open_external = [&](auto& url) {
if (!Desktop::Launcher::open(url)) {
GUI::MessageBox::show(window,
String::formatted("The link to '{}' could not be opened.", url),
"Failed to open link",
GUI::MessageBox::Type::Error);
}
};
search_list_view.on_selection = [&](auto index) {
if (!index.is_valid())
return;
if (auto model = search_list_view.model()) {
auto& search_model = *static_cast<GUI::FilteringProxyModel*>(model);
index = search_model.map(index);
} else {
page_view.load_empty_document();
return;
}
String path = model->page_path(index);
if (path.is_null()) {
page_view.load_empty_document();
return;
}
tree_view.selection().clear();
tree_view.selection().add(index);
history.push(path);
update_actions();
open_page(path);
};
page_view.on_link_click = [&](auto& url, auto&, unsigned) {
if (url.protocol() != "file") {
open_external(url);
return;
}
auto path = Core::File::real_path_for(url.path());
if (!path.starts_with("/usr/share/man/")) {
open_external(url);
return;
}
auto tree_view_index = model->index_from_path(path);
if (tree_view_index.has_value()) {
dbgln("Found path _{}_ in model at index {}", path, tree_view_index.value());
tree_view.selection().set(tree_view_index.value());
return;
}
history.push(path);
update_actions();
open_page(path);
};
go_back_action = GUI::CommonActions::make_go_back_action([&](auto&) {
history.go_back();
update_actions();
open_page(history.current());
});
go_forward_action = GUI::CommonActions::make_go_forward_action([&](auto&) {
history.go_forward();
update_actions();
open_page(history.current());
});
go_back_action->set_enabled(false);
go_forward_action->set_enabled(false);
auto go_home_action = GUI::CommonActions::make_go_home_action([&](auto&) {
String path = "/usr/share/man/man7/Help-index.md";
history.push(path);
update_actions();
open_page(path);
});
toolbar.add_action(*go_back_action);
toolbar.add_action(*go_forward_action);
toolbar.add_action(*go_home_action);
auto menubar = GUI::MenuBar::construct();
auto& app_menu = menubar->add_menu("Help");
app_menu.add_action(GUI::CommonActions::make_about_action("Help", app_icon, window));
app_menu.add_separator();
app_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
GUI::Application::the()->quit();
}));
auto& go_menu = menubar->add_menu("Go");
go_menu.add_action(*go_back_action);
go_menu.add_action(*go_forward_action);
go_menu.add_action(*go_home_action);
app->set_menubar(move(menubar));
if (start_page) {
URL url = URL::create_with_url_or_path(start_page);
if (url.is_valid() && url.path().ends_with(".md")) {
history.push(url.path());
update_actions();
open_page(url.path());
} else {
left_tab_bar.set_active_widget(&search_view);
search_box.set_text(start_page);
if (auto model = search_list_view.model()) {
auto& search_model = *static_cast<GUI::FilteringProxyModel*>(model);
search_model.set_filter_term(search_box.text());
}
}
} else {
go_home_action->activate();
}
window->set_focused_widget(&left_tab_bar);
window->show();
return app->exec();
}
| 33.789137 | 131 | 0.638521 | [
"model"
] |
f6c306978e4e184c718d07c26f8375087ff3f73d | 1,772 | cpp | C++ | src/observer/sql/executor/execution_node.cpp | penggan666/miniob | 23a3c30e06b06958f70aa9dc2c31e70354e2b708 | [
"Apache-2.0"
] | null | null | null | src/observer/sql/executor/execution_node.cpp | penggan666/miniob | 23a3c30e06b06958f70aa9dc2c31e70354e2b708 | [
"Apache-2.0"
] | null | null | null | src/observer/sql/executor/execution_node.cpp | penggan666/miniob | 23a3c30e06b06958f70aa9dc2c31e70354e2b708 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
//
// Created by Wangyunlai on 2021/5/14.
//
#include "sql/executor/execution_node.h"
#include "storage/common/table.h"
#include "common/log/log.h"
SelectExeNode::SelectExeNode() : table_(nullptr) {
}
SelectExeNode::~SelectExeNode() {
for (DefaultConditionFilter * &filter : condition_filters_) {
delete filter;
}
condition_filters_.clear();
}
RC
SelectExeNode::init(Trx *trx, Table *table, TupleSchema &&tuple_schema, std::vector<DefaultConditionFilter *> &&condition_filters) {
trx_ = trx;
table_ = table;
tuple_schema_ = tuple_schema;
condition_filters_ = std::move(condition_filters);
return RC::SUCCESS;
}
void record_reader(const char *data, void *context) {
TupleRecordConverter *converter = (TupleRecordConverter *)context;
converter->add_record(data);
}
RC SelectExeNode::execute(TupleSet &tuple_set) {
CompositeConditionFilter condition_filter;
condition_filter.init((const ConditionFilter **)condition_filters_.data(), condition_filters_.size());
tuple_set.clear();
tuple_set.set_schema(tuple_schema_);
TupleRecordConverter converter(table_, tuple_set);
return table_->scan_record(trx_, &condition_filter, -1, (void *)&converter, record_reader);
} | 35.44 | 132 | 0.758465 | [
"vector"
] |
f6c308a53996908f940e801d633924f8d8d70cb3 | 92,323 | cpp | C++ | aten/src/ATen/native/RNN.cpp | xiaohanhuang/pytorch | a31aea8eaa99a5ff72b5d002c206cd68d5467a5e | [
"Intel"
] | 183 | 2018-04-06T21:10:36.000Z | 2022-03-30T15:05:24.000Z | aten/src/ATen/native/RNN.cpp | xiaohanhuang/pytorch | a31aea8eaa99a5ff72b5d002c206cd68d5467a5e | [
"Intel"
] | 818 | 2020-02-07T02:36:44.000Z | 2022-03-31T23:49:44.000Z | aten/src/ATen/native/RNN.cpp | xiaohanhuang/pytorch | a31aea8eaa99a5ff72b5d002c206cd68d5467a5e | [
"Intel"
] | 58 | 2018-06-05T16:40:18.000Z | 2022-03-16T15:37:29.000Z | #include <ATen/native/RNN.h>
#include <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <ATen/core/op_registration/op_registration.h>
#include <ATen/cpp_custom_type_hack.h>
#include <ATen/native/quantized/cpu/packed_params.h>
#include <ATen/native/quantized/cpu/fbgemm_utils.h>
#include <ATen/native/quantized/cpu/qnnpack_utils.h>
#include <c10/util/irange.h>
#include <torch/custom_class.h>
#include <torch/library.h>
int register_linear_params();
namespace at { namespace native {
namespace {
// Check if pytorch is compiled with MIOpen.
bool use_miopen(const at::Tensor& input, const double dropout_state) {
bool is_miopen_acceptable = ((input.scalar_type() == at::kFloat)|| (input.scalar_type() == at::kHalf)) &&
(detail::getCUDAHooks().compiledWithMIOpen()) &&
(input.is_cuda()) &&
(dropout_state == 0.0) &&
(at::globalContext().userEnabledCuDNN());
return is_miopen_acceptable;
}
template<typename T>
using pair_of = std::pair<T, T>;
template<typename T>
using tpair_of = std::tuple<T, T>;
// Those could have been function pointers, but MSVC chokes on function pointers as template parameters
struct tanh_f {
Tensor operator()(const Tensor& t) const { return at::tanh(t); }
};
struct relu_f {
Tensor operator()(const Tensor& t) const { return at::relu(t); }
};
struct PackedSequence {
PackedSequence() = default;
PackedSequence(Tensor _data, Tensor _batch_sizes)
: data(std::move(_data)), batch_sizes(std::move(_batch_sizes)) {}
Tensor data;
Tensor batch_sizes;
};
// Simple type for __getstate__/__setstate__ serialization
//
// Element 0 is a string key to say what kind of CellParam this is. It
// should be a valid key into cell_params_deserializers
// Element 1 is the Tensors contained within the CellParams instance
// Element 2 is the doubles (if any) contained in the CellParams instance
// Element 3 is the longs (if any) contained within the CellParams instance
using CellParamsSerializationType = std::tuple<
std::string,
std::vector<at::Tensor>,
std::vector<double>,
std::vector<int64_t>,
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>>>;
// Base class so we can polymorphically handle these
struct CellParamsBase : torch::CustomClassHolder {
virtual Tensor matmul_ih(const Tensor& input) const = 0;
virtual Tensor matmul_hh(const Tensor& h) const = 0;
// by default doing nothing. CellParams will override this
// to define correct behavior for LSTMs with projections.
// This function is not pure virtual, because it's useful to
// provide this default implementation, so that all cell params
// that don't support projections work correctly (e.g. QuantizedCellParams variations)
virtual Tensor matmul_hr(const Tensor& h) const {
return h;
}
virtual Tensor linear_ih(const Tensor& input_ih) const = 0;
virtual Tensor linear_hh(const Tensor& input_hh) const = 0;
virtual const Tensor& b_ih() const = 0;
virtual const Tensor& b_hh() const = 0;
virtual CellParamsSerializationType __getstate__() const = 0;
};
// Pretty much all cells we support take the same set of arguments, but threading those
// 4 arguments manually is really annoying. Their lifetime is externally managed, so we only
// pass this struct of references around. LSTMs with projections have 5th argument w_hr, for all
// other models it's always going to be undefined.
struct CellParams : public CellParamsBase {
CellParams(
const Tensor& _w_ih,
const Tensor& _w_hh,
const Tensor& _b_ih,
const Tensor& _b_hh,
const Tensor& _w_hr)
: w_ih(_w_ih), w_hh(_w_hh), b_ih_(_b_ih), b_hh_(_b_hh), w_hr(_w_hr) {};
const Tensor& w_ih;
const Tensor& w_hh;
const Tensor& b_ih_; /* optional */
const Tensor& b_hh_; /* optional */
const Tensor& w_hr; /* only defined for LSTMs with projections */
Tensor matmul_ih(const Tensor& input) const override {
return at::matmul(input, w_ih.t());
}
Tensor matmul_hh(const Tensor& h) const override {
return at::matmul(h, w_hh.t());
}
Tensor matmul_hr(const Tensor& h) const override {
if (w_hr.defined()) {
return at::matmul(h, w_hr.t());
}
return h;
}
Tensor linear_ih(const Tensor& input) const override {
return at::linear(input, w_ih, b_ih_);
}
Tensor linear_hh(const Tensor& h) const override {
return at::linear(h, w_hh, b_hh_);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
TORCH_INTERNAL_ASSERT(false, "Not yet implemented");
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
TORCH_INTERNAL_ASSERT(false, "Not yet implemented");
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params(
const at::Tensor& w_ih,
const at::Tensor& w_hh,
at::Tensor bias_ih,
at::Tensor bias_hh);
struct QuantizedCellParams : public CellParamsBase {
QuantizedCellParams(
Tensor _w_ih,
Tensor _w_hh,
Tensor _b_ih,
Tensor _b_hh,
Tensor _packed_ih,
Tensor _packed_hh,
Tensor _col_offsets_ih,
Tensor _col_offsets_hh,
const Scalar& _scale_ih,
const Scalar& _scale_hh,
const Scalar& _zero_point_ih,
const Scalar& _zero_point_hh)
: w_ih(std::move(_w_ih)),
w_hh(std::move(_w_hh)),
b_ih_(std::move(_b_ih)),
b_hh_(std::move(_b_hh)),
packed_ih(std::move(_packed_ih)),
packed_hh(std::move(_packed_hh)),
col_offsets_ih(std::move(_col_offsets_ih)),
col_offsets_hh(std::move(_col_offsets_hh)),
// NOLINTNEXTLINE(performance-move-const-arg)
scale_ih(std::move(_scale_ih)),
// NOLINTNEXTLINE(performance-move-const-arg)
scale_hh(std::move(_scale_hh)),
// NOLINTNEXTLINE(performance-move-const-arg)
zero_point_ih(std::move(_zero_point_ih)),
// NOLINTNEXTLINE(performance-move-const-arg)
zero_point_hh(std::move(_zero_point_hh)) {}
const Tensor w_ih;
const Tensor w_hh;
const Tensor b_ih_;
const Tensor b_hh_;
const Tensor packed_ih;
const Tensor packed_hh;
const Tensor col_offsets_ih;
const Tensor col_offsets_hh;
const Scalar scale_ih;
const Scalar scale_hh;
const Scalar zero_point_ih;
const Scalar zero_point_hh;
Tensor matmul_ih(const Tensor& input) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor matmul_hh(const Tensor& h) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor linear_ih(const Tensor& input) const override {
return at::fbgemm_linear_int8_weight_fp32_activation(
input, w_ih, packed_ih, col_offsets_ih, scale_ih, zero_point_ih, b_ih_);
}
Tensor linear_hh(const Tensor& h) const override {
return at::fbgemm_linear_int8_weight_fp32_activation(
h, w_hh, packed_hh, col_offsets_hh, scale_hh, zero_point_hh, b_hh_);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
std::vector<at::Tensor> tensors_to_serialize = {
w_ih, w_hh, b_ih_, b_hh_, col_offsets_ih, col_offsets_hh};
std::vector<double> doubles_to_serialize = {scale_ih.toDouble(),
scale_hh.toDouble()};
std::vector<int64_t> longs_to_serialize = {zero_point_ih.toLong(),
zero_point_hh.toLong()};
return CellParamsSerializationType(
"quantized",
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(tensors_to_serialize),
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(doubles_to_serialize),
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(longs_to_serialize),
{});
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
std::vector<at::Tensor> tensors;
std::vector<double> doubles;
std::vector<int64_t> longs;
std::tie(std::ignore, tensors, doubles, longs, std::ignore) =
std::move(state);
TORCH_INTERNAL_ASSERT(tensors.size() == 6);
TORCH_INTERNAL_ASSERT(doubles.size() == 2);
TORCH_INTERNAL_ASSERT(longs.size() == 2);
at::Tensor qw_ih = std::move(tensors[0]), qw_hh = std::move(tensors[1]),
b_ih = std::move(tensors[2]), b_hh = std::move(tensors[3]),
col_offsets_ih = std::move(tensors[4]),
col_offsets_hh = std::move(tensors[5]);
double scale_ih = doubles[0], scale_hh = doubles[1];
int64_t zero_point_ih = longs[0], zero_point_hh = longs[1];
at::Tensor packed_ih = at::native::fbgemm_pack_quantized_matrix(qw_ih);
at::Tensor packed_hh = at::native::fbgemm_pack_quantized_matrix(qw_hh);
return c10::make_intrusive<QuantizedCellParams>(
/*w_ih=*/std::move(qw_ih),
/*w_hh=*/std::move(qw_hh),
/*b_ih_=*/std::move(b_ih),
/*b_hh_=*/std::move(b_hh),
/*packed_ih=*/std::move(packed_ih),
/*packed_hh=*/std::move(packed_hh),
/*col_offsets_ih=*/std::move(col_offsets_ih),
/*col_offsets_hh=*/std::move(col_offsets_hh),
// NOLINTNEXTLINE(performance-move-const-arg)
/*scale_ih=*/std::move(scale_ih),
// NOLINTNEXTLINE(performance-move-const-arg)
/*scale_hh=*/std::move(scale_hh),
// NOLINTNEXTLINE(performance-move-const-arg)
/*zero_point_ih=*/std::move(zero_point_ih),
// NOLINTNEXTLINE(performance-move-const-arg)
/*zero_point_hh=*/std::move(zero_point_hh));
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params(
const at::Tensor& w_ih,
const at::Tensor& w_hh,
at::Tensor b_ih,
at::Tensor b_hh) {
auto make_vals = [&](const at::Tensor& W) {
auto params = at::native::fbgemm_linear_quantize_weight(W);
at::Tensor packed_weight =
at::native::fbgemm_pack_quantized_matrix(std::get<0>(params));
return std::tuple_cat(
std::make_tuple(std::move(packed_weight)), std::move(params));
};
at::Tensor qw_ih, qw_hh, packed_ih, packed_hh, col_offsets_ih, col_offsets_hh;
at::Scalar scale_ih, scale_hh, zero_point_ih, zero_point_hh;
std::tie(packed_ih, qw_ih, col_offsets_ih, scale_ih, zero_point_ih) =
make_vals(w_ih);
std::tie(packed_hh, qw_hh, col_offsets_hh, scale_hh, zero_point_hh) =
make_vals(w_hh);
return c10::make_intrusive<QuantizedCellParams>(
/*qw_ih=*/std::move(qw_ih),
/*qw_hh=*/std::move(qw_hh),
/*b_ih=*/std::move(b_ih),
/*b_hh=*/std::move(b_hh),
/*packed_ih=*/std::move(packed_ih),
/*packed_hh=*/std::move(packed_hh),
/*col_offsets_ih=*/std::move(col_offsets_ih),
/*col_offsets_hh=*/std::move(col_offsets_hh),
// NOLINTNEXTLINE(performance-move-const-arg)
/*scale_ih=*/std::move(scale_ih),
// NOLINTNEXTLINE(performance-move-const-arg)
/*scale_hh=*/std::move(scale_hh),
// NOLINTNEXTLINE(performance-move-const-arg)
/*zero_point_ih=*/std::move(zero_point_ih),
// NOLINTNEXTLINE(performance-move-const-arg)
/*zero_point_hh=*/std::move(zero_point_hh));
}
// QuantizedCellParams vs. QuantizedCellParamsDynamic
//
// QuantizedCellParams uses the legacy
// fbgemm_linear_int8_weight_fp32_activation API, which requires the explicit
// scale and zero point parameters for the weight. QuantizedCellParamsDynamic
// uses the new fbgemm_linear_dynamic API, which doesn't require the explicit
// scale and zero point parameters. These quantization parameters are
// encapsulated in the `PackedLinearWeight` struct in
// aten/src/ATen/native/quantized/cpu/fbgemm_utils.h.
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_dynamic(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed,
at::Tensor bias_ih,
at::Tensor bias_hh,
bool reduce_range);
struct QuantizedCellParamsDynamic : public CellParamsBase {
QuantizedCellParamsDynamic(
c10::intrusive_ptr<LinearPackedParamsBase>
_packed_w_ih, /* Prepacked Weight Tensor */
c10::intrusive_ptr<LinearPackedParamsBase>
_packed_w_hh, /* Prepacked Weight Tensor */
Tensor _b_ih, /* float Bias Tensor */
Tensor _b_hh, /* float Bias Tensor */
bool _reduce_range = false /* Use reduced range for activation tensors */)
: packed_w_ih(std::move(_packed_w_ih)),
packed_w_hh(std::move(_packed_w_hh)),
b_ih_(std::move(_b_ih)),
b_hh_(std::move(_b_hh)),
reduce_range_(_reduce_range) {}
c10::intrusive_ptr<LinearPackedParamsBase> packed_w_ih;
c10::intrusive_ptr<LinearPackedParamsBase> packed_w_hh;
const Tensor b_ih_;
const Tensor b_hh_;
bool reduce_range_;
Tensor matmul_ih(const Tensor& input) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor matmul_hh(const Tensor& h) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor linear_ih(const Tensor& input_ih) const override {
return packed_w_ih->apply_dynamic(input_ih, reduce_range_);
}
Tensor linear_hh(const Tensor& input_hh) const override {
return packed_w_hh->apply_dynamic(input_hh, reduce_range_);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
// Boxed dispatch nonsense
// This will be cleaned up in the subsequent PR
auto unpacked_ih = packed_w_ih->unpack();
auto unpacked_hh = packed_w_hh->unpack();
std::vector<at::Tensor> tensors_to_serialize{
/*b_ih=*/b_ih_,
/*b_hh=*/b_hh_,
};
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>>
packed_params_to_serialize{packed_w_ih, packed_w_hh};
// reduce_range parameter is serialized along with the int field values.
return CellParamsSerializationType(
"quantized_dynamic",
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(tensors_to_serialize),
{},
{reduce_range_},
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(packed_params_to_serialize));
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
std::vector<at::Tensor> tensors;
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>> packed_params;
std::vector<int64_t> serialized_ints;
std::tie(std::ignore, tensors, std::ignore, serialized_ints, packed_params) =
std::move(state);
TORCH_INTERNAL_ASSERT(tensors.size() == 2);
TORCH_INTERNAL_ASSERT(packed_params.size() == 2);
bool reduce_range = serialized_ints.empty() ? false : serialized_ints[0];
return make_quantized_cell_params_dynamic(
/*w_ih_packed=*/std::move(packed_params[0]),
/*w_hh_packed=*/std::move(packed_params[1]),
/*bias_ih=*/std::move(tensors[0]),
/*bias_hh=*/std::move(tensors[1]),
/*reduce_range=*/reduce_range);
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_dynamic(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed,
at::Tensor bias_ih,
at::Tensor bias_hh,
bool reduce_range) {
return c10::make_intrusive<QuantizedCellParamsDynamic>(
/*_packed_w_ih=*/std::move(w_ih_packed),
/*_packed_w_hh=*/std::move(w_hh_packed),
/*_b_ih=*/std::move(bias_ih),
/*_b_hh=*/std::move(bias_hh),
/*_reduce_range=*/reduce_range);
}
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_fp16(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed);
struct QuantizedCellParamsFP16 : public CellParamsBase {
QuantizedCellParamsFP16(
c10::intrusive_ptr<LinearPackedParamsBase> _packed_ih,
c10::intrusive_ptr<LinearPackedParamsBase> _packed_hh)
: packed_ih(std::move(_packed_ih)), packed_hh(std::move(_packed_hh)) {}
c10::intrusive_ptr<LinearPackedParamsBase> packed_ih;
c10::intrusive_ptr<LinearPackedParamsBase> packed_hh;
const Tensor b_ih_;
const Tensor b_hh_;
Tensor matmul_ih(const Tensor& /* unused */) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor matmul_hh(const Tensor& /* unused */) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor linear_ih(const Tensor& input) const override {
return packed_ih->apply_dynamic(input);
}
Tensor linear_hh(const Tensor& h) const override {
return packed_hh->apply_dynamic(h);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>>
packed_params_to_serialize{packed_ih, packed_hh};
return CellParamsSerializationType(
// NOLINTNEXTLINE(performance-move-const-arg)
"quantized_fp16", {}, {}, {}, std::move(packed_params_to_serialize));
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>> packed_params;
std::tie(
std::ignore, std::ignore, std::ignore, std::ignore, packed_params) =
std::move(state);
TORCH_INTERNAL_ASSERT(packed_params.size() == 2);
return make_quantized_cell_params_fp16(
/*w_ih_packed=*/std::move(packed_params[0]),
/*w_hh_packed=*/std::move(packed_params[1]));
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_fp16(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed) {
return c10::make_intrusive<QuantizedCellParamsFP16>(
std::move(w_ih_packed), std::move(w_hh_packed));
}
static std::unordered_map<
std::string,
c10::intrusive_ptr<CellParamsBase> (*)(CellParamsSerializationType)>
cell_params_deserializers = {
{"quantized", &QuantizedCellParams::__setstate__},
{"quantized_dynamic", &QuantizedCellParamsDynamic::__setstate__},
{"quantized_fp16", &QuantizedCellParamsFP16::__setstate__}};
// Stupid wrapper to convert from -> to .
struct QRNNCellParamsWrapper {
QRNNCellParamsWrapper(c10::intrusive_ptr<CellParamsBase> param)
: param_(std::move(param)) {}
Tensor matmul_ih(const Tensor& input) const {
return param_->matmul_ih(input);
}
Tensor matmul_hh(const Tensor& h) const {
return param_->matmul_hh(h);
}
Tensor matmul_hr(const Tensor& h) const {
return param_->matmul_hr(h);
}
Tensor linear_ih(const Tensor& input) const {
return param_->linear_ih(input);
}
Tensor linear_hh(const Tensor& h) const {
return param_->linear_hh(h);
}
const Tensor& b_ih() const {
return param_->b_ih();
}
const Tensor& b_hh() const {
return param_->b_hh();
}
c10::intrusive_ptr<CellParamsBase> param_;
};
// Gathers every two elements of a vector in a vector of pairs
template<typename T>
static std::vector<pair_of<T>> pair_vec(const std::vector<T>& vals) {
TORCH_CHECK(vals.size() % 2 == 0, "Odd number of params or hiddens given to a bidirectional RNN");
std::vector<pair_of<T>> result;
result.reserve(vals.size() / 2);
for (size_t i = 0; i < vals.size(); i += 2) {
result.emplace_back(vals[i], vals[i + 1]);
}
return result;
}
// Flattens a vector of pairs
template<typename T>
static std::vector<T> unpair_vec(std::vector<pair_of<T>>&& vals) {
std::vector<T> result;
result.reserve(vals.size() * 2);
for (const auto i : c10::irange(vals.size())) {
result.push_back(std::move(vals[i].first));
result.push_back(std::move(vals[i].second));
}
return result;
}
// Parses a flat list of parameter tensors into a list of CellParams
static std::vector<CellParams> gather_params(TensorList params, bool has_biases, bool has_projections = false) {
static at::Tensor undefined;
std::vector<CellParams> result;
if (has_biases) {
if (has_projections) {
TORCH_CHECK(params.size() % 5 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 5) {
result.emplace_back(params[i], params[i + 1], params[i + 2], params[i + 3], params[i + 4]);
}
} else {
TORCH_CHECK(params.size() % 4 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 4) {
result.emplace_back(params[i], params[i + 1], params[i + 2], params[i + 3], undefined);
}
}
} else {
if (has_projections) {
TORCH_CHECK(params.size() % 3 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 3) {
result.emplace_back(params[i], params[i + 1], undefined, undefined, params[i + 2]);
}
} else {
TORCH_CHECK(params.size() % 2 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 2) {
result.emplace_back(params[i], params[i + 1], undefined, undefined, undefined);
}
}
}
return result;
}
// These gather_* functions are kept solely for the purposes of backward
// compatbility in the legacy quantized_{lstm,gru} APIs
static c10::List<c10::intrusive_ptr<CellParamsBase>> gather_quantized_params(
c10::List<at::Tensor> params) {
static at::Tensor undefined;
std::vector<c10::intrusive_ptr<CellParamsBase>> result;
TORCH_CHECK(params.size() % 12 == 0, "got an incorrect number of quantized RNN parameters");
for (size_t i = 0; i < params.size(); i += 12) {
result.emplace_back(c10::make_intrusive<QuantizedCellParams>(
static_cast<at::Tensor>(params[i]),
static_cast<at::Tensor>(params[i + 1]),
static_cast<at::Tensor>(params[i + 2]),
static_cast<at::Tensor>(params[i + 3]),
static_cast<at::Tensor>(params[i + 4]),
static_cast<at::Tensor>(params[i + 5]),
static_cast<at::Tensor>(params[i + 6]),
static_cast<at::Tensor>(params[i + 7]),
static_cast<at::Tensor>(params[i + 8]).item(),
static_cast<at::Tensor>(params[i + 9]).item(),
static_cast<at::Tensor>(params[i + 10]).item(),
static_cast<at::Tensor>(params[i + 11]).item()));
}
return c10::List<c10::intrusive_ptr<CellParamsBase>>(result);
}
static c10::List<c10::intrusive_ptr<CellParamsBase>>
gather_quantized_params_dynamic(c10::List<at::Tensor> params) {
static at::Tensor undefined;
std::vector<c10::intrusive_ptr<CellParamsBase>> result;
for (size_t i = 0; i < params.size(); i += 2) {
auto packed_struct_ih =
cpp_custom_type_hack::cast<c10::intrusive_ptr<LinearPackedParamsBase>>(
static_cast<at::Tensor>(params[i]));
auto packed_struct_hh =
cpp_custom_type_hack::cast<c10::intrusive_ptr<LinearPackedParamsBase>>(
static_cast<at::Tensor>(params[i + 1]));
auto bias_ih = packed_struct_ih->bias().value_or(undefined);
auto bias_hh = packed_struct_hh->bias().value_or(undefined);
result.emplace_back(c10::make_intrusive<QuantizedCellParamsDynamic>(
std::move(packed_struct_ih),
std::move(packed_struct_hh),
std::move(bias_ih),
std::move(bias_hh)));
}
return c10::List<c10::intrusive_ptr<CellParamsBase>>(result);
}
static c10::List<c10::intrusive_ptr<CellParamsBase>>
gather_quantized_params_fp16(c10::List<at::Tensor> params) {
static at::Tensor undefined;
std::vector<c10::intrusive_ptr<CellParamsBase>> result;
TORCH_CHECK(params.size() % 4 == 0,
"incorrect number of quantized RNN parameters FP16");
for (size_t i = 0; i < params.size(); i += 4) {
c10::intrusive_ptr<LinearPackedParamsBase> packed_struct_ih =
cpp_custom_type_hack::cast<c10::intrusive_ptr<LinearPackedParamsBase>>(
static_cast<at::Tensor>(params[i]));
c10::intrusive_ptr<LinearPackedParamsBase> packed_struct_hh =
cpp_custom_type_hack::cast<c10::intrusive_ptr<LinearPackedParamsBase>>(
static_cast<at::Tensor>(params[i + 1]));
// NB: we install the bias from the gathered parameters here because
// in the "new world", the fp16 linear apply() method always expects
// the bias to be present in the packed struct. In the "old world",
// we called `fbgemm_linear_fp16_weight_fp32_activation`, which took
// the bias explicitly and ignored the bias in the packed struct. To
// reconcile serialized models that behavied in the old style, we
// put the bias into the appropriate packed structures here.
//
// Hopefully we can remove this in the future when we eliminate
// the old style altogether
packed_struct_ih->set_bias(params[i + 2]);
packed_struct_hh->set_bias(params[i + 3]);
result.emplace_back(c10::make_intrusive<QuantizedCellParamsFP16>(
std::move(packed_struct_ih), std::move(packed_struct_hh)));
}
return c10::List<c10::intrusive_ptr<CellParamsBase>>(result);
}
////////////////////////////////////////////////////////////////////////////////
// HIDDEN STATE FUNCTIONS
//
// Functions implemented below are implemented as templates based on hidden type,
// because they need to work both with simple RNNs and GRU (which use a single Tensor),
// as well as with LSTM (or possibly more complicated architectures in the future).
// Still, there are some operations that need to be performed on the hidden states
// alone, and for this purpose we provide an overloaded set of functions below.
Tensor hidden_as_output(const Tensor& t) { return t; }
Tensor hidden_as_output(const tpair_of<Tensor>& t) { return std::get<0>(t); }
template<size_t index>
std::vector<Tensor> project(at::ArrayRef<tpair_of<Tensor>> tuples) {
std::vector<Tensor> result;
result.reserve(tuples.size());
for (auto & t : tuples) {
result.push_back(std::get<index>(t));
}
return result;
}
Tensor hidden_concat(at::ArrayRef<Tensor> hiddens) { return at::cat(hiddens, 0); }
tpair_of<Tensor> hidden_concat(at::ArrayRef<tpair_of<Tensor>> hiddens) {
return std::make_tuple(hidden_concat(project<0>(hiddens)), hidden_concat(project<1>(hiddens)));
}
Tensor hidden_slice(const Tensor& t, int64_t start, int64_t end) {
return t.narrow(0, start, end - start);
}
tpair_of<Tensor> hidden_slice(const tpair_of<Tensor>& t, int64_t start, int64_t end) {
return std::make_tuple(hidden_slice(std::get<0>(t), start, end),
hidden_slice(std::get<1>(t), start, end));
}
////////////////////////////////////////////////////////////////////////////////
// CELL IMPLEMENTATIONS
//
// Cell is a basic component of an RNN, representing a single application of the
// recurrent function. You can think of it as a function of signature
//
// (Tensor input, hidden_type hidden, CellParams) -> hidden_type
//
// which means that it consumes an input tensor, and updates the previous hidden state.
// It's a struct only because functional programming in C++ is a pain, and it's easier
// to pass around "vtable pointers" than actual function pointers.
void check_rnn_cell_forward_input(const Tensor& input, int64_t input_size) {
TORCH_CHECK(
input.size(1) == input_size,
"input has inconsistent input_size: got ", input.size(1), " expected ", input_size);
}
void check_rnn_cell_forward_hidden(const Tensor& input, const Tensor& hx, int64_t hidden_size, int64_t hidden_label) {
TORCH_CHECK(
input.size(0) == hx.size(0),
"Input batch size ", input.size(0), " doesn't match hidden", hidden_label, " batch size ", hx.size(0));
TORCH_CHECK(
hx.size(1) == hidden_size,
"hidden", hidden_label, " has inconsistent hidden_size: got ", hx.size(1), ", expected ", hidden_size);
}
template<typename hidden_type_tmpl, typename cell_params_tmpl>
struct Cell {
using hidden_type = hidden_type_tmpl;
using cell_params = cell_params_tmpl;
virtual ~Cell() = default; // This is really dumb, but enables projects with
// -Wnon-virtual-dtor to compile...
virtual hidden_type operator()(
const Tensor& input,
const hidden_type& hidden,
const cell_params& params,
bool pre_compute_input = false) const = 0;
};
template<typename nonlinearity, typename cell_params>
struct SimpleCell : Cell<Tensor, cell_params> {
using hidden_type = Tensor;
Tensor operator()(
const Tensor& input,
const Tensor& hidden,
const cell_params& params,
bool pre_compute_input = false) const override {
return nonlinearity{}(params.linear_hh(hidden).add_(
pre_compute_input ? input : params.linear_ih(input)));
}
};
// TODO: can use inplace ops?
template <typename cell_params>
struct LSTMCell : Cell<std::tuple<Tensor, Tensor>, cell_params> {
using hidden_type = std::tuple<Tensor, Tensor>;
hidden_type operator()(
const Tensor& input,
const hidden_type& hidden,
const cell_params& params,
bool pre_compute_input = false) const override {
const auto& hx = std::get<0>(hidden);
const auto& cx = std::get<1>(hidden);
if (input.is_cuda()) {
TORCH_CHECK(!pre_compute_input);
auto igates = params.matmul_ih(input);
auto hgates = params.matmul_hh(hx);
auto result = at::_thnn_fused_lstm_cell(
igates, hgates, cx, params.b_ih(), params.b_hh());
// applying projections if w_hr is defined
auto hy = params.matmul_hr(std::get<0>(result));
// Slice off the workspace argument (it's needed only for AD).
return std::make_tuple(std::move(hy), std::move(std::get<1>(result)));
}
const auto gates = params.linear_hh(hx).add_(
pre_compute_input ? input : params.linear_ih(input));
auto chunked_gates = gates.unsafe_chunk(4, 1);
auto ingate = chunked_gates[0].sigmoid_();
auto forgetgate = chunked_gates[1].sigmoid_();
auto cellgate = chunked_gates[2].tanh_();
auto outgate = chunked_gates[3].sigmoid_();
auto cy = (forgetgate * cx).add_(ingate * cellgate);
auto hy = outgate * cy.tanh();
hy = params.matmul_hr(hy);
return std::make_tuple(std::move(hy), std::move(cy));
}
};
template <typename cell_params>
struct GRUCell : Cell<Tensor, cell_params> {
using hidden_type = Tensor;
hidden_type operator()(
const Tensor& input,
const hidden_type& hidden,
const cell_params& params,
bool pre_compute_input = false) const override {
if (input.is_cuda()) {
TORCH_CHECK(!pre_compute_input);
auto igates = params.matmul_ih(input);
auto hgates = params.matmul_hh(hidden);
auto result = at::_thnn_fused_gru_cell(
igates, hgates, hidden, params.b_ih(), params.b_hh());
// Slice off the workspace argument (it's needed only for AD).
return std::move(std::get<0>(result));
}
const auto chunked_igates = pre_compute_input
? input.unsafe_chunk(3, 1)
: params.linear_ih(input).unsafe_chunk(3, 1);
auto chunked_hgates = params.linear_hh(hidden).unsafe_chunk(3, 1);
const auto reset_gate =
chunked_hgates[0].add_(chunked_igates[0]).sigmoid_();
const auto input_gate =
chunked_hgates[1].add_(chunked_igates[1]).sigmoid_();
const auto new_gate =
chunked_igates[2].add(chunked_hgates[2].mul_(reset_gate)).tanh_();
return (hidden - new_gate).mul_(input_gate).add_(new_gate);
}
};
////////////////////////////////////////////////////////////////////////////////
// LAYER IMPLEMENTATIONS
//
// Layers are scan-like higher-order functions, which take in cells, and
// transform them to functions of signature
//
// (io_type input, hidden_type hidden, param_type params) -> (io_type, hidden_type)
//
// which can apply the cell over a sequence of inputs, and produce both a new set
// of hidden states, as well as a concatenated output of each step.
template<typename output_type, typename hidden_type>
struct LayerOutput {
output_type outputs;
hidden_type final_hidden;
};
template<typename io_type, typename hidden_type, typename param_type>
struct Layer {
using output_type = LayerOutput<io_type, hidden_type>;
virtual ~Layer() = default; // This is really dumb, but enables projects with
// -Wnon-virtual-dtor to compile...
virtual output_type operator()(
const io_type& input,
const hidden_type& input_hidden,
const param_type& params) const = 0;
};
template<typename hidden_type, typename cell_params>
struct FullLayer : Layer<Tensor, hidden_type, cell_params> {
using output_type =
typename Layer<Tensor, hidden_type, cell_params>::output_type;
using unstacked_output_type = LayerOutput<std::vector<Tensor>, hidden_type>;
FullLayer(Cell<hidden_type, cell_params>& cell)
: cell_(cell) {};
unstacked_output_type operator()(
const std::vector<Tensor>& step_inputs,
const hidden_type& input_hidden,
const cell_params& params,
bool pre_compute_input = false) const {
std::vector<Tensor> step_outputs;
auto hidden = input_hidden;
for (const auto& input : step_inputs) {
hidden = cell_(input, hidden, params, pre_compute_input);
step_outputs.emplace_back(hidden_as_output(hidden));
}
return {step_outputs, hidden};
}
output_type operator()(
const Tensor& inputs,
const hidden_type& input_hidden,
const cell_params& params) const override {
if (inputs.device().is_cpu()) {
const auto inputs_w = params.linear_ih(inputs);
auto unstacked_output =
(*this)(inputs_w.unbind(0), input_hidden, params, true);
TORCH_CHECK(unstacked_output.outputs.size()>0, "Expected sequence length to be larger than 0 in RNN");
return {at::stack(unstacked_output.outputs, 0),
unstacked_output.final_hidden};
}
auto unstacked_output = (*this)(inputs.unbind(0), input_hidden, params);
TORCH_CHECK(unstacked_output.outputs.size()>0, "Expected sequence length to be larger than 0 in RNN");
return {at::stack(unstacked_output.outputs, 0),
unstacked_output.final_hidden};
}
Cell<hidden_type, cell_params>& cell_;
};
template <typename dir_hidden_type, typename cell_params>
struct FullBidirectionalLayer
: Layer<Tensor, pair_of<dir_hidden_type>, pair_of<cell_params>> {
using hidden_type = pair_of<dir_hidden_type>;
using param_type = pair_of<cell_params>;
using output_type = typename Layer<Tensor, hidden_type, param_type>::output_type;
FullBidirectionalLayer(Cell<dir_hidden_type, cell_params>& cell)
: layer_(cell) {};
output_type operator()(
const Tensor& input,
const hidden_type& input_hidden,
const param_type& params) const override {
std::vector<Tensor> step_inputs;
if (input.device().is_cpu()) {
auto input_w = params.first.linear_ih(input);
step_inputs = input_w.unbind(0);
auto fw_result = layer_(
step_inputs, input_hidden.first, params.first, true);
TORCH_CHECK(fw_result.outputs.size() > 0, "Expected sequence length to be larger than 0 in RNN");
auto fw_output = at::stack(fw_result.outputs, 0);
input_w = params.second.linear_ih(input);
step_inputs = input_w.unbind(0);
auto rev_step_inputs = reverse(std::move(step_inputs));
auto rev_result =
layer_(rev_step_inputs, input_hidden.second, params.second, true);
std::reverse(rev_result.outputs.begin(), rev_result.outputs.end());
auto rev_output = at::stack(rev_result.outputs, 0);
return {at::cat({fw_output, rev_output}, fw_output.dim() - 1),
std::make_pair(fw_result.final_hidden, rev_result.final_hidden)};
}
step_inputs = input.unbind(0);
auto fw_result = layer_(step_inputs, input_hidden.first, params.first);
TORCH_CHECK(fw_result.outputs.size() > 0, "Expected sequence length to be larger than 0 in RNN");
auto fw_output = at::stack(fw_result.outputs, 0);
auto rev_step_inputs = reverse(std::move(step_inputs));
auto rev_result =
layer_(rev_step_inputs, input_hidden.second, params.second);
std::reverse(rev_result.outputs.begin(), rev_result.outputs.end());
auto rev_output = at::stack(rev_result.outputs, 0);
return {at::cat({fw_output, rev_output}, fw_output.dim() - 1),
std::make_pair(fw_result.final_hidden, rev_result.final_hidden)};
}
std::vector<Tensor> reverse(std::vector<Tensor>&& x) const {
std::reverse(x.begin(), x.end());
return std::move(x);
}
FullLayer<dir_hidden_type, cell_params> layer_;
};
template<typename hidden_type, typename cell_params>
struct PackedLayer : Layer<PackedSequence, hidden_type, cell_params> {
using output_type =
typename Layer<PackedSequence, hidden_type, cell_params>::output_type;
PackedLayer(Cell<hidden_type, cell_params>& cell)
: cell_(cell) {};
output_type operator()(
const PackedSequence& input,
const hidden_type& input_hidden,
const cell_params& params) const override {
std::vector<at::Tensor> step_outputs;
std::vector<hidden_type> hiddens;
int64_t input_offset = 0;
int64_t num_steps = input.batch_sizes.size(0);
int64_t* batch_sizes = input.batch_sizes.data_ptr<int64_t>();
int64_t last_batch_size = batch_sizes[0];
const Tensor* input_ptr = &input.data;
bool pre_compute_input = false;
Tensor input_w;
if (input.data.device().is_cpu()) {
input_w = params.linear_ih(input.data);
input_ptr = &input_w;
pre_compute_input = true;
}
// Batch sizes is a sequence of decreasing lengths, which are offsets
// into a 1D list of inputs. At every step we slice out batch_size elements,
// and possibly account for the decrease in the batch size since the last step,
// which requires us to slice the hidden state (since some sequences
// are completed now). The sliced parts are also saved, because we will need
// to return a tensor of final hidden state.
auto hidden = input_hidden;
for (const auto i : c10::irange(num_steps)) {
const int64_t batch_size = batch_sizes[i];
auto step_input = input_ptr->narrow(0, input_offset, batch_size);
input_offset += batch_size;
const int64_t dec = last_batch_size - batch_size;
if (dec > 0) {
hiddens.emplace_back(
hidden_slice(hidden, last_batch_size - dec, last_batch_size));
hidden = hidden_slice(hidden, 0, last_batch_size - dec);
}
last_batch_size = batch_size;
hidden = cell_(step_input, hidden, params, pre_compute_input);
step_outputs.push_back(hidden_as_output(hidden));
}
hiddens.emplace_back(hidden);
std::reverse(hiddens.begin(), hiddens.end());
return {PackedSequence{at::cat(step_outputs, 0), input.batch_sizes},
hidden_concat(hiddens)};
}
Cell<hidden_type, cell_params>& cell_;
};
template<typename hidden_type, typename cell_params>
struct ReversedPackedLayer : Layer<PackedSequence, hidden_type, cell_params> {
using output_type =
typename Layer<PackedSequence, hidden_type, cell_params>::output_type;
ReversedPackedLayer(Cell<hidden_type, cell_params>& cell)
: cell_(cell) {};
output_type operator()(
const PackedSequence& input,
const hidden_type& input_hidden,
const cell_params& params) const override {
std::vector<at::Tensor> step_outputs;
int64_t input_offset = input.data.size(0);
int64_t num_steps = input.batch_sizes.size(0);
int64_t* batch_sizes = input.batch_sizes.data_ptr<int64_t>();
int64_t last_batch_size = batch_sizes[num_steps - 1];
const Tensor* input_ptr = &input.data;
bool pre_compute_input = false;
Tensor input_w;
if (input.data.device().is_cpu()) {
input_w = params.linear_ih(input.data);
input_ptr = &input_w;
pre_compute_input = true;
}
// Here the situation is similar to that above, except we start out with
// the smallest batch size (and a small set of hidden states we actually use),
// and progressively expand the hidden states, as we move backwards over the
// 1D list of inputs.
auto hidden = hidden_slice(input_hidden, 0, batch_sizes[num_steps - 1]);
for (int64_t i = num_steps - 1; i >= 0; --i) {
const int64_t batch_size = batch_sizes[i];
const int64_t inc = batch_size - last_batch_size;
if (inc > 0) {
hidden = hidden_concat(ArrayRef<hidden_type>{
hidden, hidden_slice(input_hidden, last_batch_size, batch_size)});
}
auto step_input =
input_ptr->narrow(0, input_offset - batch_size, batch_size);
input_offset -= batch_size;
last_batch_size = batch_size;
hidden = cell_(step_input, hidden, params, pre_compute_input);
step_outputs.emplace_back(hidden_as_output(hidden));
}
std::reverse(step_outputs.begin(), step_outputs.end());
return {PackedSequence{at::cat(step_outputs, 0), input.batch_sizes},
hidden};
}
Cell<hidden_type, cell_params>& cell_;
};
template <typename dir_hidden_type, typename cell_params>
struct PackedBidirectionalLayer
: Layer<PackedSequence, pair_of<dir_hidden_type>, pair_of<cell_params>> {
using hidden_type = pair_of<dir_hidden_type>;
using param_type = pair_of<cell_params>;
using output_type =
typename Layer<PackedSequence, hidden_type, param_type>::output_type;
PackedBidirectionalLayer(Cell<dir_hidden_type, cell_params>& cell)
: layer_(cell), rev_layer_(cell) {};
output_type operator()(
const PackedSequence& input,
const hidden_type& input_hidden,
const param_type& params) const override {
auto fw_result = layer_(input, input_hidden.first, params.first);
auto rev_result = rev_layer_(input, input_hidden.second, params.second);
PackedSequence output{
at::cat({fw_result.outputs.data, rev_result.outputs.data}, -1),
input.batch_sizes};
return {output,
std::make_pair(fw_result.final_hidden, rev_result.final_hidden)};
}
PackedLayer<dir_hidden_type, cell_params> layer_;
ReversedPackedLayer<dir_hidden_type, cell_params> rev_layer_;
};
////////////////////////////////////////////////////////////////////////////////
// apply_layer_stack
//
// layers are convenient, but in reality we often want to stack them. this little
// helper manages slicing of all inputs and parameters, and repeatedly feeds them
// into the given layer. returns the last layer's outputs, and a vector of final
// hidden states produced at each level.
Tensor dropout(const Tensor& input, double p) {
return at::dropout(input, p, /*train=*/true);
}
PackedSequence dropout(const PackedSequence& input, double p) {
return {at::dropout(input.data, p, /*train=*/true), input.batch_sizes};
}
template<typename io_type, typename hidden_type, typename weight_type>
LayerOutput<io_type, std::vector<hidden_type>>
apply_layer_stack(const Layer<io_type, hidden_type, weight_type>& layer, const io_type& input,
const std::vector<hidden_type>& hiddens, const std::vector<weight_type>& weights,
int64_t num_layers, double dropout_p, bool train) {
TORCH_CHECK(num_layers == (int64_t)hiddens.size(), "Expected more hidden states in stacked_rnn");
TORCH_CHECK(num_layers == (int64_t)weights.size(), "Expected more weights in stacked_rnn");
auto layer_input = input;
auto hidden_it = hiddens.begin();
auto weight_it = weights.begin();
std::vector<hidden_type> final_hiddens;
for (const auto l : c10::irange(num_layers)) {
auto layer_output = layer(layer_input, *(hidden_it++), *(weight_it++));
final_hiddens.push_back(layer_output.final_hidden);
layer_input = layer_output.outputs;
if (dropout_p != 0 && train && l < num_layers - 1) {
layer_input = dropout(layer_input, dropout_p);
}
}
return {layer_input, final_hiddens};
}
////////////////////////////////////////////////////////////////////////////////
// HELPERS SIMPLIFYING DISPATCH TO FUNCTIONS ABOVE
////////////////////////////////////////////////////////////////////////////////
template<typename CellType, template<typename,typename> class LayerT, template<typename,typename> class BidirLayerT, typename cell_params, typename io_type>
LayerOutput<io_type, std::vector<typename CellType::hidden_type>> _rnn_impl(
const io_type& input,
const std::vector<cell_params>& params,
const std::vector<typename CellType::hidden_type>& hiddens,
int64_t num_layers, double dropout_p, bool train, bool bidirectional) {
using hidden_type = typename CellType::hidden_type;
CellType cell;
if (bidirectional) {
using BidirLayer = BidirLayerT<hidden_type, cell_params>;
auto bidir_result = apply_layer_stack(BidirLayer{cell}, input, pair_vec(hiddens), pair_vec(params), num_layers, dropout_p, train);
return {bidir_result.outputs, unpair_vec(std::move(bidir_result.final_hidden))};
} else {
return apply_layer_stack(LayerT<hidden_type,cell_params>{cell}, input, hiddens, params, num_layers, dropout_p, train);
}
}
template<typename CellType, template<typename,typename> class LayerT, template<typename,typename> class BidirLayerT, typename cell_params, typename io_type>
std::tuple<io_type, Tensor> _rnn_impl_with_concat(
const io_type& input,
const std::vector<cell_params>& params,
const std::vector<typename CellType::hidden_type>& hiddens,
int64_t num_layers, double dropout_p, bool train, bool bidirectional) {
auto result = _rnn_impl<CellType, LayerT, BidirLayerT>(input, params, hiddens, num_layers, dropout_p, train, bidirectional);
return std::make_tuple(std::move(result.outputs), at::stack(result.final_hidden, 0));
}
template<template<typename,typename> class LayerT, template<typename,typename> class BidirLayerT, typename cell_params, typename io_type>
std::tuple<io_type, Tensor, Tensor> _lstm_impl(
const io_type& input,
const std::vector<cell_params>& params, const Tensor& hx, const Tensor& cx,
int64_t num_layers, double dropout_p, bool train, bool bidirectional) {
// It's much more useful for us to work on lists of pairs of hx and cx for each layer, so we need
// to transpose a pair of those tensors.
auto layer_hx = hx.unbind(0);
auto layer_cx = cx.unbind(0);
int64_t total_layers = layer_hx.size();
std::vector<typename LSTMCell<cell_params>::hidden_type> hiddens;
hiddens.reserve(total_layers);
for (const auto i : c10::irange(total_layers)) {
hiddens.emplace_back(std::move(layer_hx[i]), std::move(layer_cx[i]));
}
auto result = _rnn_impl<LSTMCell<cell_params>, LayerT, BidirLayerT>(input, params, hiddens, num_layers, dropout_p, train, bidirectional);
// Now, we need to reverse the transposed we performed above.
std::vector<Tensor> hy, cy;
hy.reserve(total_layers); cy.reserve(total_layers);
for (auto & hidden : result.final_hidden) {
hy.push_back(std::move(std::get<0>(hidden)));
cy.push_back(std::move(std::get<1>(hidden)));
}
return std::make_tuple(std::move(result.outputs), at::stack(hy, 0), at::stack(cy, 0));
}
} // anonymous namespace
bool _use_cudnn_rnn_flatten_weight() {
return detail::getCUDAHooks().compiledWithCuDNN();
}
////////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
////////////////////////////////////////////////////////////////////////////////
#define ONE_HIDDEN_RNN(NAME, CELL) \
DEFINE_DISPATCH(NAME##_cudnn_stub); \
DEFINE_DISPATCH(NAME##_miopen_stub); \
DEFINE_DISPATCH(NAME##_packed_cudnn_stub); \
DEFINE_DISPATCH(NAME##_packed_miopen_stub); \
REGISTER_NO_CPU_DISPATCH(NAME##_cudnn_stub, rnn_fn); \
REGISTER_NO_CPU_DISPATCH(NAME##_miopen_stub, rnn_fn); \
REGISTER_NO_CPU_DISPATCH(NAME##_packed_cudnn_stub, rnn_packed_fn); \
REGISTER_NO_CPU_DISPATCH(NAME##_packed_miopen_stub, rnn_packed_fn); \
\
std::tuple<Tensor, Tensor> NAME( \
const Tensor& _input, \
const Tensor& hx, \
TensorList _params, \
bool has_biases, \
int64_t num_layers, \
double dropout_p, \
bool train, \
bool bidirectional, \
bool batch_first) { \
if (at::cudnn_is_acceptable(_input)) { \
Tensor output, hy; \
NAME##_cudnn_stub( \
_input.device().type(), \
output, \
hy, \
_input, \
hx, \
_params, \
has_biases, \
num_layers, \
dropout_p, \
train, \
bidirectional, \
batch_first); \
return std::make_tuple(std::move(output), std::move(hy)); \
} \
if (use_miopen(_input, dropout_p)) { \
Tensor output, hy; \
NAME##_miopen_stub( \
_input.device().type(), \
output, \
hy, \
_input, \
hx, \
_params, \
has_biases, \
num_layers, \
dropout_p, \
train, \
bidirectional, \
batch_first); \
return std::make_tuple(std::move(output), std::move(hy)); \
} \
check_attributes(_input, _params, hx); \
auto input = batch_first ? _input.transpose(0, 1) : _input; \
auto params = gather_params(_params, has_biases); \
auto results = \
_rnn_impl_with_concat<CELL, FullLayer, FullBidirectionalLayer>( \
input, \
params, \
hx.unbind(0), \
num_layers, \
dropout_p, \
train, \
bidirectional); \
if (batch_first) { \
std::get<0>(results).transpose_(0, 1); \
} \
return results; \
} \
\
std::tuple<Tensor, Tensor> NAME( \
const Tensor& data, \
const Tensor& batch_sizes, \
const Tensor& hx, \
TensorList _params, \
bool has_biases, \
int64_t num_layers, \
double dropout_p, \
bool train, \
bool bidirectional) { \
if (at::cudnn_is_acceptable(data)) { \
Tensor output, hy; \
NAME##_packed_cudnn_stub( \
data.device().type(), \
output, \
hy, \
data, \
batch_sizes, \
hx, \
_params, \
has_biases, \
num_layers, \
dropout_p, \
train, \
bidirectional); \
return std::make_tuple(std::move(output), std::move(hy)); \
} \
if (use_miopen(data, dropout_p)) { \
Tensor output, hy; \
NAME##_packed_miopen_stub( \
data.device().type(), \
output, \
hy, \
data, \
batch_sizes, \
hx, \
_params, \
has_biases, \
num_layers, \
dropout_p, \
train, \
bidirectional); \
return std::make_tuple(std::move(output), std::move(hy)); \
} \
PackedSequence input{data, batch_sizes}; \
auto params = gather_params(_params, has_biases); \
auto result = \
_rnn_impl_with_concat<CELL, PackedLayer, PackedBidirectionalLayer>( \
input, \
params, \
hx.unbind(0), \
num_layers, \
dropout_p, \
train, \
bidirectional); \
auto& packed_output = std::get<0>(result); \
return std::make_tuple( \
std::move(packed_output.data), std::move(std::get<1>(result))); \
}
#define ONE_HIDDEN_QRNN(NAME, CELL) \
std::tuple<Tensor, Tensor> NAME##_input( \
const Tensor& _input, \
const Tensor& hx, \
c10::List<c10::intrusive_ptr<CellParamsBase>> _params, \
bool has_biases, \
int64_t num_layers, \
double dropout_p, \
bool train, \
bool bidirectional, \
bool batch_first) { \
std::vector<QRNNCellParamsWrapper> params; \
for (c10::intrusive_ptr<CellParamsBase> x : _params) { \
params.emplace_back(std::move(x)); \
} \
auto input = batch_first ? _input.transpose(0, 1) : _input; \
auto results = \
_rnn_impl_with_concat<CELL, FullLayer, FullBidirectionalLayer>( \
input, \
params, \
hx.unbind(0), \
num_layers, \
dropout_p, \
train, \
bidirectional); \
if (batch_first) { \
std::get<0>(results).transpose_(0, 1); \
} \
return results; \
} \
\
std::tuple<Tensor, Tensor> NAME##_data( \
const Tensor& data, \
const Tensor& batch_sizes, \
const Tensor& hx, \
c10::List<c10::intrusive_ptr<CellParamsBase>> _params, \
bool has_biases, \
int64_t num_layers, \
double dropout_p, \
bool train, \
bool bidirectional) { \
std::vector<QRNNCellParamsWrapper> params; \
for (c10::intrusive_ptr<CellParamsBase> x : _params) { \
params.emplace_back(std::move(x)); \
} \
PackedSequence input{data, batch_sizes}; \
auto result = \
_rnn_impl_with_concat<CELL, PackedLayer, PackedBidirectionalLayer>( \
input, \
params, \
hx.unbind(0), \
num_layers, \
dropout_p, \
train, \
bidirectional); \
auto& packed_output = std::get<0>(result); \
return std::make_tuple( \
std::move(packed_output.data), std::move(std::get<1>(result))); \
}
ONE_HIDDEN_RNN(gru, GRUCell<CellParams>)
ONE_HIDDEN_QRNN(quantized_gru, GRUCell<QRNNCellParamsWrapper>)
// BC wrappers for quantized_gru
std::tuple<Tensor, Tensor> quantized_gru_input_legacy(
const Tensor& _input,
const Tensor& hx,
c10::List<at::Tensor> _params,
bool has_biases,
int64_t num_layers,
double dropout_p,
bool train,
bool bidirectional,
bool batch_first) {
TORCH_WARN_ONCE(
"torch.quantized_gru with List[Tensor] for parameters is "
"deprecated and may be removed! Please re-export your model "
"using the newer definitions in torch.jit.quantized");
auto params = gather_quantized_params(std::move(_params));
return quantized_gru_input(
_input,
hx,
std::move(params),
has_biases,
num_layers,
dropout_p,
train,
bidirectional,
batch_first);
}
std::tuple<Tensor, Tensor> quantized_gru_data_legacy(
const Tensor& data,
const Tensor& batch_sizes,
const Tensor& hx,
c10::List<at::Tensor> _params,
bool has_biases,
int64_t num_layers,
double dropout_p,
bool train,
bool bidirectional) {
TORCH_WARN_ONCE(
"torch.quantized_gru with List[Tensor] for parameters is "
"deprecated and may be removed! Please re-export your model "
"using the newer definitions in torch.jit.quantized");
auto params = gather_quantized_params(std::move(_params));
return quantized_gru_data(
data,
batch_sizes,
hx,
std::move(params),
has_biases,
num_layers,
dropout_p,
train,
bidirectional);
}
using tanf_cell_type = SimpleCell<tanh_f, CellParams>;
ONE_HIDDEN_RNN(rnn_tanh, tanf_cell_type)
using relu_cell_type = SimpleCell<relu_f, CellParams>;
ONE_HIDDEN_RNN(rnn_relu, relu_cell_type);
DEFINE_DISPATCH(lstm_cudnn_stub);
DEFINE_DISPATCH(lstm_packed_cudnn_stub);
DEFINE_DISPATCH(lstm_miopen_stub);
DEFINE_DISPATCH(lstm_packed_miopen_stub);
REGISTER_NO_CPU_DISPATCH(lstm_cudnn_stub, lstm_fn);
REGISTER_NO_CPU_DISPATCH(lstm_packed_cudnn_stub, lstm_packed_fn);
REGISTER_NO_CPU_DISPATCH(lstm_miopen_stub, lstm_fn);
REGISTER_NO_CPU_DISPATCH(lstm_packed_miopen_stub, lstm_packed_fn);
std::tuple<Tensor, Tensor, Tensor> lstm(
const Tensor& _input, TensorList hx,
TensorList _params, bool has_biases,
int64_t num_layers, double dropout_p, bool train, bool bidirectional, bool batch_first) {
TORCH_CHECK(hx.size() == 2, "lstm expects two hidden states");
if (at::cudnn_is_acceptable(_input)) {
Tensor output, hy, cy;
lstm_cudnn_stub(_input.device().type(), output, hy, cy, _input, hx, _params, has_biases,
num_layers, dropout_p, train, bidirectional, batch_first);
return std::make_tuple(std::move(output), std::move(hy), std::move(cy));
}
// if cells are of different size, that means projections are used
bool has_projections = (hx[0].size(2) != hx[1].size(2));
if (use_miopen(_input, dropout_p)) {
if (!has_projections) {
Tensor output, hy, cy;
lstm_miopen_stub(_input.device().type(), output, hy, cy, _input, hx, _params, has_biases,
num_layers, dropout_p, train, bidirectional, batch_first);
return std::make_tuple(std::move(output), std::move(hy), std::move(cy));
} else {
TORCH_WARN_ONCE(
"LSTM with projections is not supported with MIOpen. Using default implementation.");
}
}
check_attributes(_input, _params, hx);
auto input = batch_first ? _input.transpose(0, 1) : _input;
auto params = gather_params(_params, has_biases, has_projections);
auto results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers, dropout_p, train, bidirectional);
if (batch_first) {
std::get<0>(results) = std::get<0>(results).transpose(0, 1);
}
return results;
}
std::tuple<Tensor, Tensor, Tensor> lstm(
const Tensor& data, const Tensor& batch_sizes, TensorList hx,
TensorList _params, bool has_biases,
int64_t num_layers, double dropout_p, bool train, bool bidirectional) {
TORCH_CHECK(hx.size() == 2, "lstm expects two hidden states");
if (at::cudnn_is_acceptable(data)) {
Tensor output, hy, cy;
lstm_packed_cudnn_stub(data.device().type(), output, hy, cy, data, batch_sizes, hx,
_params, has_biases, num_layers, dropout_p, train, bidirectional);
return std::make_tuple(std::move(output), std::move(hy), std::move(cy));
}
// if cells are of different size, that means projections are used
bool has_projections = (hx[0].size(2) != hx[1].size(2));
if (use_miopen(data, dropout_p)) {
if (!has_projections) {
Tensor output, hy, cy;
lstm_packed_miopen_stub(data.device().type(), output, hy, cy, data, batch_sizes, hx,
_params, has_biases, num_layers, dropout_p, train, bidirectional);
return std::make_tuple(std::move(output), std::move(hy), std::move(cy));
} else {
TORCH_WARN_ONCE(
"LSTM with projections is not supported with MIOpen. Using default implementation.");
}
}
PackedSequence input { data, batch_sizes };
auto params = gather_params(_params, has_biases, has_projections);
auto result = _lstm_impl<PackedLayer, PackedBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers, dropout_p, train, bidirectional);
auto & packed_output = std::get<0>(result);
return std::make_tuple(std::move(packed_output.data),
std::move(std::get<1>(result)),
std::move(std::get<2>(result)));
}
std::tuple<Tensor, Tensor> lstm_cell(
const Tensor& input, TensorList hx,
const Tensor& w_ih, const Tensor& w_hh, const c10::optional<Tensor>& b_ih_opt, const c10::optional<Tensor>& b_hh_opt) {
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> b_ih_maybe_owned = at::borrow_from_optional_tensor(b_ih_opt);
const Tensor& b_ih = *b_ih_maybe_owned;
const Tensor& b_hh = c10::value_or_else(b_hh_opt, [] {return Tensor();});
TORCH_CHECK(hx.size() == 2, "lstm_cell expects two hidden states");
check_rnn_cell_forward_input(input, w_ih.size(1));
auto hidden_size = w_hh.size(1);
check_rnn_cell_forward_hidden(input, hx[0], hidden_size, 0);
check_rnn_cell_forward_hidden(input, hx[1], hidden_size, 0);
static at::Tensor undefined;
return LSTMCell<CellParams>{}(input, std::make_tuple(hx[0], hx[1]), CellParams{w_ih, w_hh, b_ih, b_hh, undefined});
}
std::tuple<Tensor, Tensor, Tensor, Tensor, Tensor>
_thnn_differentiable_lstm_cell_backward( const c10::optional<Tensor>& grad_hy_opt, const c10::optional<Tensor>& grad_cy_opt,
const Tensor& input_gates,
const Tensor& hidden_gates, const c10::optional<Tensor>& input_bias_opt, const c10::optional<Tensor>& hidden_bias_opt,
const Tensor& cx,
const Tensor& cy) {
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> grad_hy_maybe_owned = at::borrow_from_optional_tensor(grad_hy_opt);
const Tensor& grad_hy = *grad_hy_maybe_owned;
const Tensor& grad_cy = c10::value_or_else(grad_cy_opt, [] {return Tensor();});
const Tensor& input_bias = c10::value_or_else(input_bias_opt, [] {return Tensor();});
const Tensor& hidden_bias = c10::value_or_else(hidden_bias_opt, [] {return Tensor();});
if (!grad_hy.defined() && !grad_cy.defined()) {
return std::tuple<Tensor, Tensor, Tensor, Tensor, Tensor>();
}
Tensor gates = input_gates + hidden_gates;
if (input_bias.defined()) {
gates = gates + input_bias;
}
if (hidden_bias.defined()) {
gates = gates + hidden_bias;
}
auto chunked_gates = gates.unsafe_chunk(4, 1);
Tensor i = chunked_gates[0].sigmoid();
Tensor f = chunked_gates[1].sigmoid();
Tensor c = chunked_gates[2].tanh();
Tensor o = chunked_gates[3].sigmoid();
Tensor gcx = cy.tanh();
Tensor gog;
TORCH_INTERNAL_ASSERT((grad_hy.defined() || grad_cy.defined()),"either gradient with respect to hy or cy should be defined");
if (grad_hy.defined()) {
gog = grad_hy * gcx;
gog = at::sigmoid_backward(gog, o);
gcx = at::tanh_backward(grad_hy * o, gcx);
if (grad_cy.defined()) {
gcx = gcx + grad_cy;
}
} else if (grad_cy.defined()) {
gog = at::zeros_like(cx, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
gcx = grad_cy;
}
Tensor gig = gcx * c;
Tensor gfg = gcx * cx;
Tensor gcg = gcx * i;
gcx = gcx * f;
gig = at::sigmoid_backward(gig, i);
gfg = at::sigmoid_backward(gfg, f);
gcg = at::tanh_backward(gcg, c);
Tensor grad_gates = at::cat({gig, gfg, gcg, gog}, 1);
Tensor grad_bias = input_bias.defined() ? grad_gates.sum(0, /*keepdim=*/false) : at::Tensor{};
return std::make_tuple(grad_gates, grad_gates, std::move(gcx), grad_bias, grad_bias);
}
std::tuple<Tensor, Tensor, Tensor, Tensor, Tensor> _thnn_differentiable_gru_cell_backward(
const Tensor& grad_hy,
const Tensor& input_gates,
const Tensor& hidden_gates,
const Tensor& hx, const c10::optional<Tensor>& input_bias_opt, const c10::optional<Tensor>& hidden_bias_opt){
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> input_bias_maybe_owned = at::borrow_from_optional_tensor(input_bias_opt);
const Tensor& input_bias = *input_bias_maybe_owned;
const Tensor& hidden_bias = c10::value_or_else(hidden_bias_opt, [] {return Tensor();});
Tensor in_g = input_gates;
Tensor h_g = hidden_gates;
if (input_bias.defined()){
in_g = in_g+input_bias;
}
if (hidden_bias.defined()){
h_g = h_g + hidden_bias;
}
auto chunked_input_gates = in_g.unsafe_chunk(3, 1);
Tensor ir = chunked_input_gates[0];
Tensor ii = chunked_input_gates[1];
Tensor in = chunked_input_gates[2];
auto chunked_hidden_gates = h_g.unsafe_chunk(3, 1);
Tensor hr = chunked_hidden_gates[0];
Tensor hi = chunked_hidden_gates[1];
Tensor hn = chunked_hidden_gates[2];
Tensor rg = (ir + hr).sigmoid();
Tensor ig = (ii + hi).sigmoid();
Tensor grad_hx = grad_hy * ig;
Tensor ng = (in+rg*hn).tanh();
Tensor gig = at::sigmoid_backward(grad_hy * (hx - ng), ig);
Tensor gin = at::tanh_backward(grad_hy * (1 - ig), ng);
Tensor ghn = gin * rg;
Tensor grg = at::sigmoid_backward(gin * hn, rg);
Tensor grad_input_gates = at::cat({grg,gig,gin}, 1);
Tensor grad_hidden_gates = at::cat({grg,gig,ghn}, 1);
Tensor grad_input_bias = input_bias.defined() ? grad_input_gates.sum(0, /*keepdim=*/false) : at::Tensor{};
Tensor grad_hidden_bias = input_bias.defined() ? grad_hidden_gates.sum(0, /*keepdim=*/false) : at::Tensor{};
return std::make_tuple(std::move(grad_input_gates), std::move(grad_hidden_gates),
std::move(grad_hx), std::move(grad_input_bias), std::move(grad_hidden_bias));
}
Tensor gru_cell(
const Tensor& input, const Tensor& hx,
const Tensor& w_ih, const Tensor& w_hh, const c10::optional<Tensor>& b_ih_opt, const c10::optional<Tensor>& b_hh_opt) {
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> b_ih_maybe_owned = at::borrow_from_optional_tensor(b_ih_opt);
const Tensor& b_ih = *b_ih_maybe_owned;
const Tensor& b_hh = c10::value_or_else(b_hh_opt, [] {return Tensor();});
check_rnn_cell_forward_input(input, w_ih.size(1));
check_rnn_cell_forward_hidden(input, hx, w_hh.size(1), 0);
static at::Tensor undefined;
return GRUCell<CellParams>{}(input, hx, CellParams{w_ih, w_hh, b_ih, b_hh, undefined});
}
Tensor rnn_tanh_cell(
const Tensor& input, const Tensor& hx,
const Tensor& w_ih, const Tensor& w_hh, const c10::optional<Tensor>& b_ih_opt, const c10::optional<Tensor>& b_hh_opt) {
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> b_ih_maybe_owned = at::borrow_from_optional_tensor(b_ih_opt);
const Tensor& b_ih = *b_ih_maybe_owned;
const Tensor& b_hh = c10::value_or_else(b_hh_opt, [] {return Tensor();});
static at::Tensor undefined;
check_rnn_cell_forward_input(input, w_ih.size(1));
check_rnn_cell_forward_hidden(input, hx, w_hh.size(1), 0);
return SimpleCell<tanh_f, CellParams>{}(input, hx, CellParams{w_ih, w_hh, b_ih, b_hh, undefined});
}
Tensor rnn_relu_cell(
const Tensor& input, const Tensor& hx,
const Tensor& w_ih, const Tensor& w_hh, const c10::optional<Tensor>& b_ih_opt, const c10::optional<Tensor>& b_hh_opt) {
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> b_ih_maybe_owned = at::borrow_from_optional_tensor(b_ih_opt);
const Tensor& b_ih = *b_ih_maybe_owned;
const Tensor& b_hh = c10::value_or_else(b_hh_opt, [] {return Tensor();});
static at::Tensor undefined;
check_rnn_cell_forward_input(input, w_ih.size(1));
check_rnn_cell_forward_hidden(input, hx, w_hh.size(1), 0);
return SimpleCell<relu_f, CellParams>{}(input, hx, CellParams{w_ih, w_hh, b_ih, b_hh, undefined});
}
// Quantized implementations
//
// These implementations use FBGEMM to do the i2h and h2h linear layers with
// an int8 or float16 quantized weight. This is advantageous in small-batch-size
// scenarios where runtime is dominated by memory fetches of the weight matrix.
std::tuple<Tensor, Tensor, Tensor> quantized_lstm_input(
const Tensor& _input,
c10::List<at::Tensor> hx_,
c10::List<c10::intrusive_ptr<CellParamsBase>> _params_,
bool has_biases,
int64_t num_layers,
double dropout_p,
bool train,
bool bidirectional,
bool batch_first,
c10::optional<ScalarType> dtype,
bool use_dynamic) {
auto hx = hx_.vec();
std::vector<QRNNCellParamsWrapper> params;
params.reserve(_params_.size());
for (const auto& param : _params_) {
params.emplace_back(static_cast<c10::intrusive_ptr<CellParamsBase>>(param));
}
TORCH_CHECK(hx.size() == 2, "lstm expects two hidden states");
TORCH_CHECK(hx[0].size(2) == hx[1].size(2), "quantized LSTM with projections is not supported");
auto result_dtype = dtype.has_value() ? dtype.value() : at::kChar;
auto input = batch_first ? _input.transpose(0, 1) : _input;
TORCH_CHECK(has_biases, "quantized LSTM requires biases");
TORCH_CHECK(
result_dtype == at::kChar || result_dtype == at::kQInt8 ||
result_dtype == at::kHalf,
"dtype is not supported");
std::tuple<Tensor, Tensor, Tensor> results;
if (result_dtype == at::kChar || result_dtype == at::kQInt8) {
// NOLINTNEXTLINE(bugprone-branch-clone)
if (use_dynamic) {
results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers,
dropout_p, train, bidirectional);
} else {
results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers,
dropout_p, train, bidirectional);
}
} else {
results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers,
dropout_p, train, bidirectional);
}
if (batch_first) {
std::get<0>(results) = std::get<0>(results).transpose(0, 1);
}
return results;
}
// BC wrappers for quantized_lstm
std::tuple<Tensor, Tensor, Tensor> quantized_lstm_input_legacy(
const Tensor& _input,
c10::List<at::Tensor> hx_,
c10::List<at::Tensor> _params_,
bool has_biases,
int64_t num_layers,
double dropout_p,
bool train,
bool bidirectional,
bool batch_first,
c10::optional<ScalarType> dtype,
bool use_dynamic) {
TORCH_WARN_ONCE(
"torch.quantized_lstm with List[Tensor] for parameters is "
"deprecated and may be removed! Please re-export your model "
"using the newer definitions in torch.jit.quantized");
c10::List<c10::intrusive_ptr<CellParamsBase>> params;
auto result_dtype = dtype.has_value() ? dtype.value() : at::kChar;
if (result_dtype == at::kChar || result_dtype == at::kQInt8) {
if (use_dynamic) {
params = gather_quantized_params_dynamic(std::move(_params_));
} else {
params = gather_quantized_params(std::move(_params_));
}
} else {
params = gather_quantized_params_fp16(std::move(_params_));
}
return quantized_lstm_input(
_input,
std::move(hx_),
std::move(params),
has_biases,
num_layers,
dropout_p,
train,
bidirectional,
batch_first,
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(dtype),
use_dynamic);
}
std::tuple<Tensor, Tensor, Tensor> quantized_lstm_data(
const Tensor& data,
const Tensor& batch_sizes,
c10::List<at::Tensor> hx_,
c10::List<c10::intrusive_ptr<CellParamsBase>> _params_,
bool has_biases,
int64_t num_layers,
double dropout_p,
bool train,
bool bidirectional,
c10::optional<ScalarType> dtype,
bool use_dynamic) {
auto hx = hx_.vec();
std::vector<QRNNCellParamsWrapper> params;
params.reserve(_params_.size());
for (const auto& param : _params_) {
params.emplace_back(static_cast<c10::intrusive_ptr<CellParamsBase>>(param));
}
TORCH_CHECK(hx.size() == 2, "lstm expects two hidden states");
TORCH_CHECK(hx[0].size(2) == hx[1].size(2), "quantized LSTM with projections is not supported");
auto result_dtype = dtype.has_value() ? dtype.value() : at::kChar;
PackedSequence input { data, batch_sizes };
std::tuple<PackedSequence, Tensor, Tensor> results;
if (result_dtype == at::kChar || result_dtype == at::kQInt8) {
// NOLINTNEXTLINE(bugprone-branch-clone)
if (use_dynamic) {
results = _lstm_impl<PackedLayer, PackedBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers,
dropout_p, train, bidirectional);
} else {
results = _lstm_impl<PackedLayer, PackedBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers,
dropout_p, train, bidirectional);
}
} else {
results = _lstm_impl<PackedLayer, PackedBidirectionalLayer>(
input, params, hx[0], hx[1], num_layers,
dropout_p, train, bidirectional);
}
auto & packed_output = std::get<0>(results);
return std::make_tuple(std::move(packed_output.data),
std::move(std::get<1>(results)),
std::move(std::get<2>(results)));
}
std::tuple<Tensor, Tensor, Tensor> quantized_lstm_data_legacy(
const Tensor& data,
const Tensor& batch_sizes,
c10::List<at::Tensor> hx_,
c10::List<at::Tensor> _params_,
bool has_biases,
int64_t num_layers,
double dropout_p,
bool train,
bool bidirectional,
c10::optional<ScalarType> dtype,
bool use_dynamic) {
TORCH_WARN_ONCE(
"torch.quantized_lstm with List[Tensor] for parameters is "
"deprecated and may be removed! Please re-export your model "
"using the newer definitions in torch.jit.quantized");
c10::List<c10::intrusive_ptr<CellParamsBase>> params;
auto result_dtype = dtype.has_value() ? dtype.value() : at::kChar;
if (result_dtype == at::kChar || result_dtype == at::kQInt8) {
if (use_dynamic) {
params = gather_quantized_params_dynamic(std::move(_params_));
} else {
params = gather_quantized_params(std::move(_params_));
}
} else {
params = gather_quantized_params_fp16(std::move(_params_));
}
return quantized_lstm_data(
data,
batch_sizes,
std::move(hx_),
std::move(params),
has_biases,
num_layers,
dropout_p,
train,
bidirectional,
// NOLINTNEXTLINE(performance-move-const-arg)
std::move(dtype),
use_dynamic);
}
#define DEFINE_QUANTIZED_RNN_CELL(name, hx_type, cell_type, return_type, prepare_hx_fn) \
return_type name( \
const Tensor& input, \
hx_type hx, \
const Tensor& w_ih, \
const Tensor& w_hh, \
const Tensor& b_ih, \
const Tensor& b_hh, \
const Tensor& packed_ih, \
const Tensor& packed_hh, \
const Tensor& col_offsets_ih, \
const Tensor& col_offsets_hh, \
const Scalar& scale_ih, \
const Scalar& scale_hh, \
const Scalar& zero_point_ih, \
const Scalar& zero_point_hh) { \
QuantizedCellParams params( \
w_ih, \
w_hh, \
b_ih, \
b_hh, \
packed_ih, \
packed_hh, \
col_offsets_ih, \
col_offsets_hh, \
scale_ih, \
scale_hh, \
zero_point_ih, \
zero_point_hh); \
return cell_type{}( \
input, prepare_hx_fn(hx), params); \
}
// Set reduced range to be True for all RNN Cells by default. This flag is used only for FBGEMM kernels
// QNNPACK does not reduce range for activations
#define DEFINE_QUANTIZED_RNN_CELL_DYNAMIC(name, hx_type, cell_type, return_type, prepare_hx_fn) \
return_type name( \
const Tensor& input, \
hx_type hx, \
c10::intrusive_ptr<LinearPackedParamsBase> _packed_w_ih, \
c10::intrusive_ptr<LinearPackedParamsBase> _packed_w_hh, \
const Tensor& b_ih, \
const Tensor& b_hh \
) { \
QuantizedCellParamsDynamic params( \
_packed_w_ih, \
_packed_w_hh, \
b_ih, \
b_hh,\
true); \
return cell_type{}( \
input, prepare_hx_fn(hx), params); \
}
// Quantized LSTM cell
using quantized_lstm_cell_type = LSTMCell<QuantizedCellParams>;
using quantized_lstm_return_type = std::tuple<Tensor, Tensor>;
std::tuple<Tensor, Tensor> prepare_quantized_lstm_hx(TensorList hx) {
return std::make_tuple(hx[0], hx[1]);
}
// Quantized LSTM cell
using quantized_lstm_cell_dynamic_type = LSTMCell<QuantizedCellParamsDynamic>;
DEFINE_QUANTIZED_RNN_CELL(quantized_lstm_cell, TensorList, quantized_lstm_cell_type, quantized_lstm_return_type, prepare_quantized_lstm_hx);
DEFINE_QUANTIZED_RNN_CELL_DYNAMIC(quantized_lstm_cell_dynamic, TensorList, quantized_lstm_cell_dynamic_type, quantized_lstm_return_type, prepare_quantized_lstm_hx);
// Helpers for simpler cells
using simple_hx_type = const Tensor&;
simple_hx_type prepare_quantized_hx(simple_hx_type hx) {
return hx;
}
// Quantized GRU cell
using quantized_gru_cell_type = GRUCell<QuantizedCellParams>;
using quantized_gru_cell_dynamic_type = GRUCell<QuantizedCellParamsDynamic>;
DEFINE_QUANTIZED_RNN_CELL(quantized_gru_cell, simple_hx_type, quantized_gru_cell_type, Tensor, prepare_quantized_hx);
DEFINE_QUANTIZED_RNN_CELL_DYNAMIC(quantized_gru_cell_dynamic, simple_hx_type, quantized_gru_cell_dynamic_type, Tensor, prepare_quantized_hx);
// Quantized RNN w/ ReLU cell
using quantized_rnn_relu_cell_type = SimpleCell<relu_f, QuantizedCellParams>;
DEFINE_QUANTIZED_RNN_CELL(quantized_rnn_relu_cell, simple_hx_type, quantized_rnn_relu_cell_type, Tensor, prepare_quantized_hx);
using quantized_rnn_relu_cell_dynamic_type = SimpleCell<relu_f, QuantizedCellParamsDynamic>;
DEFINE_QUANTIZED_RNN_CELL_DYNAMIC(quantized_rnn_relu_cell_dynamic, simple_hx_type, quantized_rnn_relu_cell_dynamic_type, Tensor, prepare_quantized_hx);
// Quantized RNN w/ tanh cell
using quantized_rnn_tanh_cell_type = SimpleCell<tanh_f, QuantizedCellParams>;
DEFINE_QUANTIZED_RNN_CELL(quantized_rnn_tanh_cell, simple_hx_type, quantized_rnn_tanh_cell_type, Tensor, prepare_quantized_hx);
using quantized_rnn_tanh_cell_dynamic_type = SimpleCell<tanh_f, QuantizedCellParamsDynamic>;
DEFINE_QUANTIZED_RNN_CELL_DYNAMIC(quantized_rnn_tanh_cell_dynamic, simple_hx_type, quantized_rnn_tanh_cell_dynamic_type, Tensor, prepare_quantized_hx);
namespace {
static auto ensure_linear_params_registered = register_linear_params();
static auto cell_params_base_registry =
torch::selective_class_<CellParamsBase>("rnn", TORCH_SELECTIVE_CLASS("CellParamsBase"))
.def_pickle(
[](const c10::intrusive_ptr<CellParamsBase>& self)
-> CellParamsSerializationType { return self->__getstate__(); },
[](CellParamsSerializationType state)
-> c10::intrusive_ptr<CellParamsBase> {
std::string type = std::get<0>(state);
TORCH_INTERNAL_ASSERT(cell_params_deserializers.count(type));
return cell_params_deserializers[type](std::move(state));
});
TORCH_LIBRARY_FRAGMENT(aten, m) {
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_lstm.input(Tensor input, Tensor[] hx, __torch__.torch.classes.rnn.CellParamsBase[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, __torch__.torch.classes.rnn.CellParamsBase[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_lstm.input_legacy(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_lstm.data_legacy(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_gru.input(Tensor input, Tensor hx, __torch__.torch.classes.rnn.CellParamsBase[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_gru.data(Tensor data, Tensor batch_sizes, Tensor hx, __torch__.torch.classes.rnn.CellParamsBase[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_gru.input_legacy(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)"));
m.def(
TORCH_SELECTIVE_SCHEMA("aten::quantized_gru.data_legacy(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)"));
}
TORCH_LIBRARY_FRAGMENT(quantized, m) {
m.def(TORCH_SELECTIVE_SCHEMA("quantized::make_quantized_cell_params_dynamic(__torch__.torch.classes.quantized.LinearPackedParamsBase w_ih, __torch__.torch.classes.quantized.LinearPackedParamsBase w_hh, Tensor bias_ih, Tensor bias_hh, bool reduce_range=False) -> __torch__.torch.classes.rnn.CellParamsBase"));
m.def(TORCH_SELECTIVE_SCHEMA("quantized::make_quantized_cell_params_fp16(__torch__.torch.classes.quantized.LinearPackedParamsBase w_ih, __torch__.torch.classes.quantized.LinearPackedParamsBase w_hh) -> __torch__.torch.classes.rnn.CellParamsBase"));
m.def(TORCH_SELECTIVE_SCHEMA("quantized::make_quantized_cell_params(Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh) -> __torch__.torch.classes.rnn.CellParamsBase"));
m.def(TORCH_SELECTIVE_SCHEMA("quantized::quantized_lstm_cell_dynamic(Tensor input, Tensor[] hx, __torch__.torch.classes.quantized.LinearPackedParamsBase w_ih, __torch__.torch.classes.quantized.LinearPackedParamsBase w_hh, Tensor bias_ih, Tensor bias_hh) -> (Tensor, Tensor)"));
m.def(TORCH_SELECTIVE_SCHEMA("quantized::quantized_gru_cell_dynamic(Tensor input, Tensor hx, __torch__.torch.classes.quantized.LinearPackedParamsBase w_ih, __torch__.torch.classes.quantized.LinearPackedParamsBase w_hh, Tensor b_ih, Tensor b_hh) -> Tensor"));
m.def(TORCH_SELECTIVE_SCHEMA("quantized::quantized_rnn_relu_cell_dynamic(Tensor input, Tensor hx, __torch__.torch.classes.quantized.LinearPackedParamsBase w_ih, __torch__.torch.classes.quantized.LinearPackedParamsBase w_hh, Tensor b_ih, Tensor b_hh) -> Tensor"));
m.def(TORCH_SELECTIVE_SCHEMA("quantized::quantized_rnn_tanh_cell_dynamic(Tensor input, Tensor hx, __torch__.torch.classes.quantized.LinearPackedParamsBase w_ih, __torch__.torch.classes.quantized.LinearPackedParamsBase w_hh, Tensor b_ih, Tensor b_hh) -> Tensor"));
}
TORCH_LIBRARY_IMPL(aten, CPU, m) {
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_lstm.input"), TORCH_FN(quantized_lstm_input));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_lstm.data"), TORCH_FN(quantized_lstm_data));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_lstm.input_legacy"), TORCH_FN(quantized_lstm_input_legacy));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_lstm.data_legacy"), TORCH_FN(quantized_lstm_data_legacy));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_gru.input"), TORCH_FN(quantized_gru_input));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_gru.data"), TORCH_FN(quantized_gru_data));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_gru.input_legacy"), TORCH_FN(quantized_gru_input_legacy));
m.impl(TORCH_SELECTIVE_NAME("aten::quantized_gru.data_legacy"), TORCH_FN(quantized_gru_data_legacy));
}
TORCH_LIBRARY_IMPL(quantized, CPU, m) {
m.impl(TORCH_SELECTIVE_NAME("quantized::make_quantized_cell_params_dynamic"), TORCH_FN(make_quantized_cell_params_dynamic));
m.impl(TORCH_SELECTIVE_NAME("quantized::make_quantized_cell_params"), TORCH_FN(make_quantized_cell_params));
m.impl(TORCH_SELECTIVE_NAME("quantized::quantized_lstm_cell_dynamic"), TORCH_FN(quantized_lstm_cell_dynamic));
m.impl(TORCH_SELECTIVE_NAME("quantized::quantized_gru_cell_dynamic"), TORCH_FN(quantized_gru_cell_dynamic));
m.impl(TORCH_SELECTIVE_NAME("quantized::quantized_rnn_relu_cell_dynamic"), TORCH_FN(quantized_rnn_relu_cell_dynamic));
m.impl(TORCH_SELECTIVE_NAME("quantized::quantized_rnn_tanh_cell_dynamic"), TORCH_FN(quantized_rnn_tanh_cell_dynamic));
}
TORCH_LIBRARY_IMPL(quantized, CatchAll, m) {
m.impl(TORCH_SELECTIVE_NAME("quantized::make_quantized_cell_params_fp16"), TORCH_FN(make_quantized_cell_params_fp16));
}
} // namespace
}} // namespace at::native
| 44.947907 | 317 | 0.624644 | [
"vector",
"model",
"transform"
] |
f6c336844b6341710d6fcc7894ba0dd4493db472 | 14,139 | cpp | C++ | pcl__/surface/src/3rdparty/opennurbs/opennurbs_arc.cpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | 4 | 2016-11-17T02:10:04.000Z | 2019-09-05T22:53:23.000Z | software/SLAM/ygz_slam_ros/Thirdparty/PCL/surface/src/3rdparty/opennurbs/opennurbs_arc.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | null | null | null | software/SLAM/ygz_slam_ros/Thirdparty/PCL/surface/src/3rdparty/opennurbs/opennurbs_arc.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | 1 | 2021-12-20T06:54:41.000Z | 2021-12-20T06:54:41.000Z | /* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#include "pcl/surface/3rdparty/opennurbs/opennurbs.h"
ON_Arc::ON_Arc() : m_angle(0.0,2.0*ON_PI)
{
radius=1.0;
}
ON_Arc::ON_Arc( const ON_Circle& c, double angle_in_radians )
: m_angle(0.0,2.0*ON_PI)
{
Create( c, angle_in_radians );
}
ON_Arc::ON_Arc( const ON_Circle& c, ON_Interval angle_interval_in_radians )
: m_angle(0.0,2.0*ON_PI)
{
Create( c, angle_interval_in_radians );
}
ON_Arc::ON_Arc( const ON_Plane& p, double r, double angle_in_radians )
: m_angle(0.0,2.0*ON_PI)
{
Create( p, r, angle_in_radians );
}
ON_Arc::ON_Arc( const ON_3dPoint& C, double r, double angle_in_radians )
: m_angle(0.0,2.0*ON_PI)
{
Create( C, r, angle_in_radians );
}
ON_Arc::ON_Arc( const ON_Plane& pln, const ON_3dPoint& C, double r, double angle_in_radians )
: m_angle(0.0,2.0*ON_PI)
{
Create( pln, C, r, angle_in_radians );
}
ON_Arc::ON_Arc( const ON_2dPoint& P, const ON_2dPoint& Q, const ON_2dPoint& R )
: m_angle(0.0,2.0*ON_PI)
{
Create( P, Q, R );
}
ON_Arc::ON_Arc( const ON_3dPoint& P, const ON_3dPoint& Q, const ON_3dPoint& R )
: m_angle(0.0,2.0*ON_PI)
{
Create( P, Q, R );
}
ON_Arc& ON_Arc::operator=( const ON_Circle& c )
{
#if defined(ON_COMPILER_IRIX)
plane = c.plane;
radius = c.radius;
#else
ON_Circle::operator=(c);
#endif
m_angle.Set(0.0,2.0*ON_PI);
return *this;
}
bool ON_Arc::Create(
const ON_Circle& circle,
double angle_radians // angle in radians
)
{
return Create( circle, ON_Interval( 0.0, angle_radians ) );
}
bool ON_Arc::Create(
const ON_Circle& circle,
ON_Interval angle_interval_in_radians
)
{
bool rc = true;
plane = circle.plane;
plane.UpdateEquation();
radius = circle.radius;
m_angle = angle_interval_in_radians;
if ( m_angle.IsDecreasing() )
{
rc = false; // bogus input
// m_angle must never be decreasing
m_angle.Swap();
Reverse();
}
if ( m_angle.Length() > 2.0*ON_PI )
{
rc = false; // bogus input
m_angle.m_t[1] = m_angle.m_t[0] + 2.0*ON_PI;
}
if ( rc )
rc = IsValid();
return rc;
}
bool ON_Arc::Create(
const ON_Plane& pl, // circle is in this plane with center at m_origin
double r, // radius
double angle_radians // angle in radians
)
{
return Create( ON_Circle(pl,r), ON_Interval( 0.0, angle_radians ) );
}
bool ON_Arc::Create( // arc is parallel to XY plane
const ON_3dPoint& center, // center
double r, // radius
double angle_radians // angle in radians
)
{
ON_Plane p;
p.CreateFromNormal( center, ON_zaxis );
return Create( ON_Circle(p,r), ON_Interval( 0.0, angle_radians ) );
}
bool ON_Arc::Create( // arc parallel to a plane
const ON_Plane& pl, // circle will be parallel to this plane
const ON_3dPoint& center, // center
double r, // radius
double angle_radians // angle in radians
)
{
ON_Plane p = pl;
p.origin = center;
p.UpdateEquation();
return Create( ON_Circle( p, r), ON_Interval( 0.0, angle_radians ) );
}
bool ON_Arc::Create( // arc through 3 2d points
const ON_2dPoint& P, // point P
const ON_2dPoint& Q, // point Q
const ON_2dPoint& R // point R
)
{
ON_Circle c(P,Q,R);
double a = 0.0;
c.ClosestPointTo( R, &a );
return Create( c, ON_Interval(0.0,a) );
}
bool ON_Arc::Create( // arc through 3 3d points
const ON_3dPoint& P, // point P
const ON_3dPoint& Q, // point Q
const ON_3dPoint& R // point R
)
{
ON_Circle c;
double a = 0.0;
for (;;)
{
if ( !c.Create(P,Q,R) )
break;
if ( !c.ClosestPointTo( R, &a ) )
break;
if ( !(a > 0.0) )
break;
if ( !Create( c, ON_Interval(0.0,a) ) )
break;
return true;
}
plane = ON_Plane::World_xy;
radius = 0.0;
m_angle.Set(0.0,0.0);
return false;
}
//////////
// Create an arc from a 2d start point, 2d start direction, and 2d end point.
bool ON_Arc::Create(
const ON_2dPoint& P, // [IN] start point
const ON_2dVector& Pdir, // [IN] arc direction at start
const ON_2dPoint& Q // [IN] end point
)
{
return Create( ON_3dPoint(P), ON_3dVector(Pdir), ON_3dPoint(Q) );
}
//////////
// Create an arc from a 3d start point, 3d start direction, and 3d end point.
bool ON_Arc::Create(
const ON_3dPoint& P, // [IN] start point
const ON_3dVector& Pdir, // [IN] arc direction at start
const ON_3dPoint& Q // [IN] end point
)
{
double a=0.0;
bool rc = ON_Circle::Create(P,Pdir,Q);
if ( rc ) {
m_angle.m_t[0] = 0.0;
rc = ON_Circle::ClosestPointTo(Q,&a);
m_angle.m_t[1] = a;
if (a <= ON_ZERO_TOLERANCE || a >= 2.0*ON_PI-ON_ZERO_TOLERANCE )
rc = false;
}
return rc;
}
ON_Arc::~ON_Arc()
{}
void ON_Arc::Dump( ON_TextLog& dump ) const
{
dump.Print("Arc: normal = ");
dump.Print(plane.zaxis);
dump.Print(" center = ");
dump.Print(plane.origin);
dump.Print(" start = ");
dump.Print( StartPoint() );
dump.Print(" end = ");
dump.Print( EndPoint() );
dump.Print(" radius = ");
dump.Print(Radius());
dump.Print(" angle = [");
dump.Print(m_angle[0]);
dump.Print(",");
dump.Print(m_angle[1]);
dump.Print("]\n");
}
ON_3dPoint ON_Arc::StartPoint() const
{
return PointAt(m_angle[0]);
}
ON_3dPoint ON_Arc::MidPoint() const
{
return PointAt(m_angle.Mid());
}
ON_3dPoint ON_Arc::EndPoint() const
{
return PointAt(m_angle[1]);
}
bool ON_Arc::IsValid() const
{
return ( ON_Circle::IsValid()
&& m_angle.IsValid()
&& AngleRadians() > ON_ZERO_TOLERANCE
&& AngleRadians() <= 2.0*ON_PI+ON_ZERO_TOLERANCE)
? true : false;
}
ON_BoundingBox ON_Arc::BoundingBox() const
{
// TODO - compute tight arc bounding box
// Using these knot[] and cv[] arrays makes this function
// not use any heap memory.
double knot[10];
ON_4dPoint cv[9];
ON_NurbsCurve c;
c.m_knot = knot;
c.m_cv = &cv[0].x;
if ( GetNurbForm(c) )
return c.BoundingBox();
return ON_Circle::BoundingBox();
}
bool ON_Arc::GetBoundingBox(
ON_BoundingBox& bbox,
int bGrowBox
) const
{
if (bGrowBox)
{
ON_BoundingBox arc_bbox = BoundingBox();
bbox.Union(arc_bbox);
}
else
bbox = BoundingBox();
return bbox.IsValid();
}
bool ON_Arc::IsCircle() const
{
return (fabs(fabs(AngleRadians()) - 2.0*ON_PI) <= ON_ZERO_TOLERANCE)
? true : false;
}
double ON_Arc::AngleRadians() const
{
return m_angle[1]-m_angle[0];
}
double ON_Arc::AngleDegrees() const
{
return (AngleRadians()/ON_PI)*180.0;
}
ON_Interval ON_Arc::Domain() const
{
return m_angle;
}
ON_Interval ON_Arc::DomainRadians() const
{
return m_angle;
}
ON_Interval ON_Arc::DomainDegrees() const
{
const double rtd = 180.0/ON_PI;
ON_Interval ad = m_angle;
ad.m_t[0] *= rtd;
ad.m_t[1] *= rtd;
return ad;
}
bool ON_Arc::SetAngleRadians( double a )
{
if ( a < 0.0 )
{
double a0 = m_angle.m_t[0];
m_angle.Set(a0+a,a0);
Reverse();
}
else
{
m_angle.m_t[1] = m_angle.m_t[0] + a;
}
return ( fabs(m_angle.Length()) <= 2.0*ON_PI ) ? true : false;
}
bool ON_Arc::SetAngleIntervalRadians( ON_Interval angle_in_radians )
{
bool rc = angle_in_radians.IsIncreasing()
&& angle_in_radians.Length() < (1.0+ON_SQRT_EPSILON)*2.0*ON_PI;
if (rc)
{
m_angle = angle_in_radians;
}
return rc;
}
bool ON_Arc::SetAngleDegrees( double a )
{
return SetAngleRadians( (a/180.0)*ON_PI );
}
bool ON_Arc::Trim( ON_Interval domain)
{
bool ok = false;
if(domain[0]<domain[1] && domain[1]-domain[0]<=2.0 * ON_PI+ON_ZERO_TOLERANCE){
m_angle = domain;
if (m_angle.Length() > 2.0*ON_PI) m_angle[1] = m_angle[0] + 2.0*ON_PI;
ok = true;
}
return ok;
}
bool ON_ArcCurve::IsContinuous(
ON::continuity c,
double t,
int*, // hint - formal parameter intentionally ignored in this virtual function
double, // point_tolerance - formal parameter intentionally ignored in this virtual function
double, // d1_tolerance - formal parameter intentionally ignored in this virtual function
double, // d2_tolerance - formal parameter intentionally ignored in this virtual function
double, // cos_angle_tolerance - formal parameter intentionally ignored in this virtual function
double // curvature_tolerance - formal parameter intentionally ignored in this virtual function
) const
{
// 20 March 2003 Dale Lear
// Added this override of IsContinuous() to
// speed queries and support the
// locus favors of ON::continuity.
bool rc = true;
if ( !IsClosed() )
{
switch(c)
{
case ON::unknown_continuity:
case ON::C0_continuous:
case ON::C1_continuous:
case ON::C2_continuous:
case ON::G1_continuous:
case ON::G2_continuous:
case ON::Cinfinity_continuous:
case ON::Gsmooth_continuous:
// rc = true;
break;
case ON::C0_locus_continuous:
case ON::C1_locus_continuous:
case ON::C2_locus_continuous:
case ON::G1_locus_continuous:
case ON::G2_locus_continuous:
// open arc is locus discontinuous at end parameter.
// By convention (see ON::continuity comments) it
// is locus continuous at start parameter.
if ( t >= Domain()[1] )
rc = false;
break;
}
}
return rc;
}
bool ON_Arc::Reverse()
{
m_angle.Reverse();
plane.yaxis = -plane.yaxis;
plane.zaxis = -plane.zaxis;
plane.UpdateEquation();
return true;
}
double ON_Arc::Length() const
{
return fabs(AngleRadians()*radius);
}
double ON_Arc::SectorArea() const
{
return fabs(0.5*AngleRadians()*radius*radius);
}
ON_3dPoint ON_Arc::SectorAreaCentroid() const
{
double a = 0.5*fabs(AngleRadians());
double d = (a > 0.0) ? sin(a)/a : 0.0;
d *= 2.0*radius/3.0;
a = 0.5*(m_angle[1]+m_angle[0]);
return plane.PointAt(d*cos(a),d*sin(a));
}
double ON_Arc::SegmentArea() const
{
double a = fabs(AngleRadians());
return (0.5*(a - sin(a))*radius*radius);
}
ON_3dPoint ON_Arc::SegmentAreaCentroid() const
{
double a = fabs(AngleRadians());
double sin_halfa = sin(0.5*a);
double d = 3.0*(a - sin(a));
if ( d > 0.0 )
d = (sin_halfa*sin_halfa*sin_halfa)/d;
d *= 4.0*radius;
a = 0.5*(m_angle[1]+m_angle[0]);
return plane.PointAt(d*cos(a),d*sin(a));
}
/* moved to opennurbs_arccurve.cpp
int ON_Arc::GetNurbForm( ON_NurbsCurve& nurbscurve ) const
{
int rc = 0;
if ( IsValid() ) {
if ( IsCircle() )
rc = ON_Circle::GetNurbForm( nurbscurve );
else {
double a, b, c, t, dt, angle;
int span_count, i;
angle = m_angle.Length();
if (angle <= 0.5*ON_PI + ON_ZERO_TOLERANCE) {
span_count = 1;
dt = 0.5;
}
else if (angle <= ON_PI + ON_ZERO_TOLERANCE) {
span_count = 2;
angle *= 0.5;
dt = 0.25;
}
else if (angle <= 1.5*ON_PI + ON_ZERO_TOLERANCE) {
span_count = 3;
angle /= 3.0;
dt = 1.0/6.0;
}
else {
span_count = 4;
angle *= 0.25;
dt = 0.125;
}
nurbscurve.Create( 3, true, 3, 2*span_count+1 );
ON_4dPoint* CV = (ON_4dPoint*)nurbscurve.m_cv;
t = m_angle[0];
for ( i = 0; i < span_count; i++ ) {
nurbscurve.m_knot[2*i] = t;
nurbscurve.m_knot[2*i+1] = t;
CV[2*i] = PointAt(m_angle.ParameterAt(t));
t += dt;
CV[2*i+1] = PointAt(m_angle.ParameterAt(t));
t += dt;
}
span_count *= 2;
t = m_angle[1];
CV[span_count] = PointAt(t);
nurbscurve.m_knot[span_count] = t;
nurbscurve.m_knot[span_count+1] = t;
a = cos(0.5*angle);
b = a - 1.0;
c = radius*angle;
for (i = 1; i < span_count; i += 2) {
CV[i].x += b * plane.origin.x;
CV[i].y += b * plane.origin.y;
CV[i].z += b * plane.origin.z;
CV[i].w = a;
}
//for ( i = 1; i < span_count; i += 2 ) {
// t = CV[i].w;
// c = 1.0/t;
// a = CV[i].x*c; b = ArcDeFuzz(a); if ( a != b ) CV[i].x = b*t;
// a = CV[i].y*c; b = ArcDeFuzz(a); if ( a != b ) CV[i].y = b*t;
// a = CV[i].z*c; b = ArcDeFuzz(a); if ( a != b ) CV[i].z = b*t;
//}
}
rc = 2;
}
return rc;
}
*/
// returns parameters of point on arc that is closest to given point
bool ON_Arc::ClosestPointTo(
const ON_3dPoint& pt,
double* t
) const
{
/*
double tt, a;
if ( !t )
t =&tt;
ON_BOOL32 rc = ON_Circle::ClosestPointTo(pt,t);
if (rc) {
if ( *t < m_angle[0] ) {
a = 0.5*(m_angle[0] + m_angle[1] - 2.0*ON_PI);
if ( *t < a )
*t = m_angle[1];
else
*t = m_angle[0];
}
else if ( *t > m_angle[1] ) {
a = 0.5*(m_angle[0] + m_angle[1] + 2.0*ON_PI);
if ( *t > a )
*t = m_angle[0];
else
*t = m_angle[1];
}
}
*/
double s;
double twopi = 2.0*ON_PI;
bool rc = ON_Circle::ClosestPointTo(pt,&s);
if (rc){
s -= m_angle[0];
while (s < 0.0) s += twopi;
// Greg Arden April 14 2003. Changed test from ">" to ">=" this ensures that
// closest point to a circle at the seam will return the least parameter value.
while (s >= twopi) s -= twopi;
double s1 = m_angle.Length();
if (s < 0.0) s = 0.0;//shouldn't happen
if (s > s1){
if (s > 0.5*s1 + ON_PI)
s = 0.0;
else
s = s1;
}
if (t)
*t = m_angle[0] + s;
}
return rc;
}
// returns point on circle that is arc to given point
ON_3dPoint ON_Arc::ClosestPointTo(
const ON_3dPoint& pt
) const
{
double t = m_angle[0];
ClosestPointTo( pt, &t );
return PointAt(t);
}
| 22.658654 | 100 | 0.601033 | [
"3d"
] |
f6c4ca28f96dd0187f37b01ad6d52c3eb4314cc6 | 1,593 | cpp | C++ | src/third_party/swiftshader/src/D3D9/Unknown.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | src/third_party/swiftshader/src/D3D9/Unknown.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | src/third_party/swiftshader/src/D3D9/Unknown.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Unknown.hpp"
#include "Debug.hpp"
namespace D3D9
{
Unknown::Unknown()
{
referenceCount = 0;
bindCount = 0;
}
Unknown::~Unknown()
{
ASSERT(referenceCount == 0);
ASSERT(bindCount == 0);
}
long Unknown::QueryInterface(const IID &iid, void **object)
{
if(iid == IID_IUnknown)
{
AddRef();
*object = this;
return S_OK;
}
*object = 0;
return NOINTERFACE(iid);
}
unsigned long Unknown::AddRef()
{
return InterlockedIncrement(&referenceCount);
}
unsigned long Unknown::Release()
{
int current = referenceCount;
if(referenceCount > 0)
{
current = InterlockedDecrement(&referenceCount);
}
if(referenceCount == 0 && bindCount == 0)
{
delete this;
}
return current;
}
void Unknown::bind()
{
InterlockedIncrement(&bindCount);
}
void Unknown::unbind()
{
ASSERT(bindCount > 0);
InterlockedDecrement(&bindCount);
if(referenceCount == 0 && bindCount == 0)
{
delete this;
}
}
} | 18.523256 | 75 | 0.680477 | [
"object"
] |
f6c7cc3c5a0cbc10d666df160ea963a6cd814cb3 | 3,413 | cpp | C++ | decompiler/IR2/LabelDB.cpp | ShadowLordAlpha/jak-project | 59265cdeae8151324703ce31ec318806e5312b4d | [
"0BSD"
] | 602 | 2020-08-23T22:52:42.000Z | 2022-02-07T23:36:14.000Z | decompiler/IR2/LabelDB.cpp | romatthe/jak-project | 35bdc9b1d3a0a89cff072deb57844aa0e73d15e7 | [
"ISC"
] | 970 | 2020-08-27T03:25:21.000Z | 2022-02-08T01:27:11.000Z | decompiler/IR2/LabelDB.cpp | romatthe/jak-project | 35bdc9b1d3a0a89cff072deb57844aa0e73d15e7 | [
"ISC"
] | 34 | 2020-08-26T03:23:50.000Z | 2022-02-03T18:49:06.000Z | #include "third-party/fmt/core.h"
#include "LabelDB.h"
namespace decompiler {
std::string LabelInfo::print() const {
if (!known) {
return fmt::format("{} unknown", name);
}
std::string result = fmt::format("{} {} ", name, result_type.print());
if (is_value) {
result += "value ";
} else {
result += "ref ";
}
if (from_user) {
result += "from-config ";
} else {
result += "auto-detected ";
}
if (array_size) {
result += fmt::format("sz: {}", *array_size);
}
return result;
}
LabelDB::LabelDB(const std::unordered_map<std::string, LabelConfigInfo>& config,
const std::vector<DecompilerLabel>& labels,
const DecompilerTypeSystem& dts) {
m_labels_by_offset_into_seg.resize(N_SEG);
// first, copy all labels.
for (size_t i = 0; i < labels.size(); i++) {
const auto& existing_info = labels[i];
LabelInfo info;
info.name = existing_info.name;
info.idx = (int)i;
m_info.push_back(info);
if (!m_labels_by_name.insert({info.name, i}).second) {
throw std::runtime_error(
fmt::format("Label {} appears multiple times, cannot build LabelDB.", info.name));
}
m_labels_by_offset_into_seg.at(existing_info.target_segment)[existing_info.offset] = (int)i;
}
assert(m_labels_by_name.size() == labels.size());
size_t total_from_offsets = 0;
for (int i = 0; i < N_SEG; i++) {
total_from_offsets += m_labels_by_offset_into_seg[i].size();
}
assert(total_from_offsets == labels.size());
// now config
for (const auto& config_it : config) {
const auto& info_it = m_labels_by_name.find(config_it.first);
if (info_it == m_labels_by_name.end()) {
throw std::runtime_error(
fmt::format("Config has an entry for label {}, but it does not exist.", config_it.first));
}
auto& info = m_info.at(info_it->second);
if (info.from_user) {
throw std::runtime_error(
fmt::format("Config has multiple entries for label {}.", config_it.first));
}
info.from_user = true;
info.known = true;
info.result_type = dts.parse_type_spec(config_it.second.type_name);
info.is_value = config_it.second.is_value;
info.array_size = config_it.second.array_size;
}
}
const LabelInfo& LabelDB::lookup(int idx) const {
return m_info.at(idx);
}
const LabelInfo& LabelDB::lookup(const std::string& name) const {
return lookup(m_labels_by_name.at(name));
}
LabelInfo LabelDB::set_and_get_previous(int idx,
const TypeSpec& type,
bool is_value,
std::optional<int> array_size) {
LabelInfo result = m_info.at(idx);
LabelInfo& mod = m_info.at(idx);
mod.result_type = type;
mod.is_value = is_value;
mod.array_size = array_size;
mod.from_user = false;
mod.known = true;
return result;
}
int LabelDB::get_index_by_offset(int seg, int offset) const {
return m_labels_by_offset_into_seg.at(seg).at(offset);
}
std::optional<int> LabelDB::try_get_index_by_offset(int seg, int offset) const {
auto it = m_labels_by_offset_into_seg.at(seg).find(offset);
if (it == m_labels_by_offset_into_seg.at(seg).end()) {
return {};
} else {
return it->second;
}
}
int LabelDB::get_index_by_name(const std::string& name) const {
return m_labels_by_name.at(name);
}
} // namespace decompiler | 29.17094 | 100 | 0.64225 | [
"vector"
] |
f6ced3090b61bcefcfb6f74c5f110979b1ed9895 | 24,149 | cpp | C++ | ESP32/TinyFairChildttgovga32/fairChild/libretro.cpp | rpsubc8/ESP32TinyFairChild | 467a9934bc9a6f6a89e757c69f49bf6b7fa8a867 | [
"WTFPL"
] | 2 | 2021-11-14T20:26:51.000Z | 2022-01-12T02:22:12.000Z | ESP32/TinyFairChildttgovga32/fairChild/libretro.cpp | rpsubc8/ESP32TinyFairChild | 467a9934bc9a6f6a89e757c69f49bf6b7fa8a867 | [
"WTFPL"
] | null | null | null | ESP32/TinyFairChildttgovga32/fairChild/libretro.cpp | rpsubc8/ESP32TinyFairChild | 467a9934bc9a6f6a89e757c69f49bf6b7fa8a867 | [
"WTFPL"
] | null | null | null |
// This file is part of FreeChaF.
//
// FreeChaF is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// FreeChaF 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 FreeChaF. If not, see http://www.gnu.org/licenses/
#include "gbConfig.h"
#include "gbGlobals.h"
#include <Arduino.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
//JJ #include "libretro.h"
//JJ #include <file/file_path.h>
//JJ #include <retro_miscellaneous.h>
//JJ #include <retro_endianness.h>
#include "memory.h"
#include "channelf.h"
#include "controller.h"
#include "audio.h"
#include "video.h"
#include "osd.h"
#include "ports.h"
#include "controller.h"
#include "f2102.h"
#include "channelf_hle.h"
#include "dataFlash/bios/gbRoms131253.h"
#include "dataFlash/bios/gbRomsl90025.h"
#include "dataFlash/bios/gbRoms131254.h"
//#include "dataFlash/cart/gbCartDemo.h"
//#include "dataFlash/cart/gbCartPacman.h"
#include "dataFlash/gbcart.h"
#define DefaultFPS 60
#define frameWidth 306
#define frameHeight 192
#define frameSize (framePitchPixel * frameHeight)
//JJ #ifdef PSP
//JJ // Workaround for a psp1 gfx driver.
//JJ #define framePitchPixel 320
//JJ #else
#define framePitchPixel frameWidth
//JJ #endif
//JJ pixel_t frame[frameSize]; //No lo necesito
//char *SystemPath; //No lo necesito
struct hle_state_s hle_state;
//**********************************
void retro_init(void)
{
// init buffers, structs
//JJ memset(frame, 0, frameSize*sizeof(pixel_t)); //No lo necesito
//init console
CHANNELF_init();
//CHANNELF_loadROM_libretro("sl90025.bin", 0);
//CHANNELF_loadROM_libretro("sl31253", 0)
//CHANNELF_loadROM_libretro("sl31254", 0x400)
//memcpy(&Memory[0],gb_rom_sl90025_bin,1024);
//if ((0+1024)>MEMORY_RAMStart)
// MEMORY_RAMStart = (0+1024);
//memcpy(&Memory[0x400],gb_rom_sl31253_bin,1024);
//if ((0x400+1024)>MEMORY_RAMStart)
// MEMORY_RAMStart = (0x400+1024);
//memcpy(&Memory[0x800],gb_cart_demo,2048);
//CHANNELF_loadROM("sl90025.bin",0);
//Funciona BEGIN disco
/*
unsigned char aux= CHANNELF_loadROM("sl31253.bin",0);
printf("ROM0 %d\n",aux);
aux= CHANNELF_loadROM("sl31254.bin",0x400);
printf("ROM1 %d\n",aux);
//aux= CHANNELF_loadROM_mem(gb_cart_demo, 2048, 0x800);
aux= CHANNELF_loadROM("AlienInvasion.chf", 0x800);
//aux= CHANNELF_loadROM("v:DragRace.chf", 0x800);
//aux= CHANNELF_loadROM("PacMan.chf", 0x800);
printf("CART %d\n",aux);
printf("RAMStart 0x%04X\n", MEMORY_RAMStart);
fflush(stdout);
*/
//Funciona END disco
//Funciona BEGIN memoria
unsigned char aux= CHANNELF_loadROM_mem(gb_rom_sl31253_bin, 1024, 0);
Serial.printf("ROM0 %d\n",aux);
aux= CHANNELF_loadROM_mem(gb_rom_sl31254_bin,1024,0x400);
Serial.printf("ROM1 %d\n",aux);
//aux= CHANNELF_loadROM_mem(gb_cart_demo, 2048, 0x800);
aux= CHANNELF_loadROM_mem(gb_list_cart_data[gb_id_cur_cart], gb_list_cart_size[gb_id_cur_cart], 0x800);
Serial.printf("CART %d\n",aux);
Serial.printf("RAMStart 0x%04X\n", MEMORY_RAMStart);
//fflush(stdout);
//Funciona END memoria
//PC0= 0x800;
/*
// load PSU 1 Update
fill_pathname_join(PSU_1_Update_Path, SystemPath, "sl90025.bin", PATH_MAX_LENGTH);
if(!CHANNELF_loadROM_libretro(PSU_1_Update_Path, 0))
{
fprintf(stderr, "[ERROR] [FREECHAF] Failed loading Channel F II BIOS(1) from: %s\n", PSU_1_Update_Path);
// load PSU 1 Original
fill_pathname_join(PSU_1_Path, SystemPath, "sl31253.bin", PATH_MAX_LENGTH);
if(!CHANNELF_loadROM_libretro(PSU_1_Path, 0))
{
fprintf(stderr, "[ERROR] [FREECHAF] Failed loading Channel F BIOS(1) from: %s\n", PSU_1_Path);
fprintf(stderr, "[ERROR] [FREECHAF] Switching to HLE for PSU1\n");
hle_state.psu1_hle = true;
}
}
// load PSU 2
fill_pathname_join(PSU_2_Path, SystemPath, "sl31254.bin", PATH_MAX_LENGTH);
if(!CHANNELF_loadROM_libretro(PSU_2_Path, 0x400))
{
fprintf(stderr, "[ERROR] [FREECHAF] Failed loading Channel F BIOS(2) from: %s\n", PSU_2_Path);
fprintf(stderr, "[ERROR] [FREECHAF] Switching to HLE for PSU2\n");
hle_state.psu2_hle = true;
}
if (hle_state.psu1_hle || hle_state.psu2_hle)
{
struct retro_message msg;
msg.msg = "Couldn't load BIOS. Using experimental HLE mode. In case of problem please use BIOS";
msg.frames = 600;
Environ(RETRO_ENVIRONMENT_SET_MESSAGE, &msg);
}*/
}
//******************************************
int is_hle()
{
if (hle_state.screen_clear_row)
return 1;
if (PC0 < 0x400 && hle_state.psu1_hle)
return 1;
if (PC0 >= 0x400 && PC0 < 0x800 && hle_state.psu2_hle)
{
return 1;
}
if (PC0 == 0xd0 && hle_state.fast_screen_clear && (R[3] == 0xc6 || R[3] == 0x21))
{
return 1;
}
return 0;
}
//******************************************
void retro_run()
{
//int i = 0;
//bool updated = false;
//Serial.printf("is_hle:%d\n",is_hle());
if(is_hle())
{
CHANNELF_HLE_run();
}
else
{
CHANNELF_run(); //El correcto
}
//JJ VIDEO_drawFrame();
}
/*
retro_environment_t Environ;
retro_video_refresh_t Video;
retro_audio_sample_t Audio;
retro_audio_sample_batch_t AudioBatch;
retro_input_poll_t InputPoll;
retro_input_state_t InputState;
struct retro_vfs_interface *vfs_interface;
void retro_set_environment(retro_environment_t fn)
{
Environ = fn;
struct retro_vfs_interface_info vfs_interface_info;
vfs_interface_info.required_interface_version = 1;
vfs_interface_info.iface = NULL;
if (fn(RETRO_ENVIRONMENT_GET_VFS_INTERFACE, &vfs_interface_info))
{
vfs_interface = vfs_interface_info.iface;
}
static struct retro_variable variables[] =
{
{
"freechaf_fast_scrclr",
"Clear screen in single frame; disabled|enabled",
},
{ NULL, NULL },
};
fn(RETRO_ENVIRONMENT_SET_VARIABLES, variables);
}
static void update_variables(void)
{
struct retro_variable var;
var.key = "freechaf_fast_scrclr";
var.value = NULL;
hle_state.fast_screen_clear = (Environ(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) && strcmp(var.value, "enabled") == 0;
}
static int CHANNELF_loadROM_libretro(const char* path, int address)
{
if (vfs_interface != NULL) // load rom using Libretro's vfs interface
{
struct retro_vfs_file_handle *h = vfs_interface->open(path, RETRO_VFS_FILE_ACCESS_READ, RETRO_VFS_FILE_ACCESS_HINT_NONE);
if (!h) // problem loading file
{
return 0;
}
ssize_t size = vfs_interface->size(h);
if (size <= 0) // problem loading file
{
return 0;
}
if (size > MEMORY_SIZE - address) // if too large to fit in memory...
{
size = MEMORY_SIZE - address;
}
size = vfs_interface->read(h, Memory + address, size);
vfs_interface->close(h);
if (size <= 0) // problem reading file
{
return 0;
}
if (address+size>MEMORY_RAMStart)
{
MEMORY_RAMStart = address+size;
}
return 1;
}
// If we can't use Libretro's vfs interface to load the rom, do things the old way ...
return CHANNELF_loadROM(path, address);
}
void retro_set_video_refresh(retro_video_refresh_t fn) { Video = fn; }
void retro_set_audio_sample(retro_audio_sample_t fn) { Audio = fn; }
void retro_set_audio_sample_batch(retro_audio_sample_batch_t fn) { AudioBatch = fn; }
void retro_set_input_poll(retro_input_poll_t fn) { InputPoll = fn; }
void retro_set_input_state(retro_input_state_t fn) { InputState = fn; }
struct retro_game_geometry Geometry;
int joypad0[26]; // joypad 0 state
int joypad1[26]; // joypad 1 state
int joypre0[26]; // joypad 0 previous state
int joypre1[26]; // joypad 1 previous state
bool console_input = false;
// at 44.1khz, read 735 samples (44100/60)
static const int audioSamples = 735;
void retro_init(void)
{
char PSU_1_Update_Path[PATH_MAX_LENGTH];
char PSU_1_Path[PATH_MAX_LENGTH];
char PSU_2_Path[PATH_MAX_LENGTH];
// init buffers, structs
memset(frame, 0, frameSize*sizeof(pixel_t));
OSD_setDisplay(frame, framePitchPixel, frameHeight);
// init console
CHANNELF_init();
// get paths
Environ(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &SystemPath);
// load PSU 1 Update
fill_pathname_join(PSU_1_Update_Path, SystemPath, "sl90025.bin", PATH_MAX_LENGTH);
if(!CHANNELF_loadROM_libretro(PSU_1_Update_Path, 0))
{
fprintf(stderr, "[ERROR] [FREECHAF] Failed loading Channel F II BIOS(1) from: %s\n", PSU_1_Update_Path);
// load PSU 1 Original
fill_pathname_join(PSU_1_Path, SystemPath, "sl31253.bin", PATH_MAX_LENGTH);
if(!CHANNELF_loadROM_libretro(PSU_1_Path, 0))
{
fprintf(stderr, "[ERROR] [FREECHAF] Failed loading Channel F BIOS(1) from: %s\n", PSU_1_Path);
fprintf(stderr, "[ERROR] [FREECHAF] Switching to HLE for PSU1\n");
hle_state.psu1_hle = true;
}
}
// load PSU 2
fill_pathname_join(PSU_2_Path, SystemPath, "sl31254.bin", PATH_MAX_LENGTH);
if(!CHANNELF_loadROM_libretro(PSU_2_Path, 0x400))
{
fprintf(stderr, "[ERROR] [FREECHAF] Failed loading Channel F BIOS(2) from: %s\n", PSU_2_Path);
fprintf(stderr, "[ERROR] [FREECHAF] Switching to HLE for PSU2\n");
hle_state.psu2_hle = true;
}
if (hle_state.psu1_hle || hle_state.psu2_hle)
{
struct retro_message msg;
msg.msg = "Couldn't load BIOS. Using experimental HLE mode. In case of problem please use BIOS";
msg.frames = 600;
Environ(RETRO_ENVIRONMENT_SET_MESSAGE, &msg);
}
}
static int is_hle(void)
{
if (hle_state.screen_clear_row)
return 1;
if (PC0 < 0x400 && hle_state.psu1_hle)
return 1;
if (PC0 >= 0x400 && PC0 < 0x800 && hle_state.psu2_hle)
{
return 1;
}
if (PC0 == 0xd0 && hle_state.fast_screen_clear && (R[3] == 0xc6 || R[3] == 0x21))
{
return 1;
}
return 0;
}
bool retro_load_game(const struct retro_game_info *info)
{
update_variables();
return CHANNELF_loadROM_mem(info->data, info->size, 0x800);
}
void retro_unload_game(void)
{
}
void retro_run(void)
{
int i = 0;
bool updated = false;
if (Environ(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
{
update_variables();
}
InputPoll();
for(i=0; i<18; i++) // Copy previous state
{
joypre0[i] = joypad0[i];
joypre1[i] = joypad1[i];
}
// JoyPad 0
joypad0[0] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP);
joypad0[1] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN);
joypad0[2] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT);
joypad0[3] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT);
joypad0[4] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A);
joypad0[5] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B);
joypad0[6] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X);
joypad0[7] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y);
joypad0[8] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START);
joypad0[9] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT);
joypad0[10] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L);
joypad0[11] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R);
joypad0[12] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2);
joypad0[13] = InputState(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2);
joypad0[14] = InputState(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X);
joypad0[15] = InputState(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y);
joypad0[16] = InputState(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X);
joypad0[17] = InputState(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y);
// JoyPad 1
joypad1[0] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP);
joypad1[1] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN);
joypad1[2] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT);
joypad1[3] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT);
joypad1[4] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A);
joypad1[5] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B);
joypad1[6] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X);
joypad1[7] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y);
joypad1[8] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START);
joypad1[9] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT);
joypad1[10] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L);
joypad1[11] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R);
joypad1[12] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2);
joypad1[13] = InputState(1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2);
joypad1[14] = InputState(1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X);
joypad1[15] = InputState(1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y);
joypad1[16] = InputState(1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X);
joypad1[17] = InputState(1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y);
// analog up, down, left, right
// left analog: 18,19,20,21
// right analog: 22,23,24,25
joypad1[18] = (joypad1[15]/4096) <-1; // ALeft UP
joypad1[19] = (joypad1[15]/4096) > 1; // ALeft DOWN
joypad1[20] = (joypad1[14]/4096) <-1; // ALeft LEFT
joypad1[21] = (joypad1[14]/4096) > 1; // ALeft RIGHT
joypad1[22] = (joypad1[17]/4096) <-1; // ARight UP
joypad1[23] = (joypad1[17]/4096) > 1; // ARight DOWN
joypad1[24] = (joypad1[16]/4096) <-1; // ARight LEFT
joypad1[25] = (joypad1[16]/4096) > 1; // ARight RIGHT
// swap console/controller input //
if((joypad0[8]==1 && joypre0[8]==0) || (joypad1[8]==1 && joypre1[8]==0))
{
console_input = !console_input;
}
// swap left/right controllers //
if((joypad0[9]==1 && joypre0[9]==0) || (joypad1[9]==1 && joypre1[9]==0))
{
CONTROLLER_swap();
}
if(console_input) // console input
{
if(((joypad0[2]==1 && joypre0[2]==0) || (joypad1[2]==1 && joypre1[2]==0)) || // left
((joypad0[20]==1 && joypre0[20]==0) || (joypad1[20]==1 && joypre1[20]==0))|| // left analog left
((joypad0[24]==1 && joypre0[24]==0) || (joypad1[24]==1 && joypre1[24]==0))) // right analog left
{
CONTROLLER_consoleInput(0, 1);
}
if(((joypad0[3]==1 && joypre0[3]==0) || (joypad1[3]==1 && joypre1[3]==0)) || // right
((joypad0[22]==1 && joypre0[22]==0) || (joypad1[22]==1 && joypre1[22]==0))|| // left analog right
((joypad0[25]==1 && joypre0[25]==0) || (joypad1[25]==1 && joypre1[25]==0))) // right analog right
{
CONTROLLER_consoleInput(1, 1);
}
for(i=4; i<8; i++)
{
if((joypad0[i]==1 && joypre0[i]==0) || (joypad1[i]==1 && joypre1[i]==0)) // a,b,x,y
{
CONTROLLER_consoleInput(2, 1);
}
if((joypad0[i]==0 && joypre0[i]==1) || (joypad1[i]==0 && joypre1[i]==1)) // a,b,x,y
{
CONTROLLER_consoleInput(2, 0);
}
}
}
else
{
// ordinary controller input
CONTROLLER_setInput(1,
((joypad0[5] | joypad0[23])<<7)| // push - B - ALeft Down -
((joypad0[6] | joypad0[22])<<6)| // pull - X - ALeft Up -
((joypad0[4] | joypad0[25] | joypad0[11])<<5)| // rotate right - A - ALeft Right - ShRight
((joypad0[7] | joypad0[24] | joypad0[10])<<4)| // rotate left - Y - ALeft rLeft - ShLeft
((joypad0[0] | joypad0[18])<<3)| // forward - Up - ARight Up -
((joypad0[1] | joypad0[19])<<2)| // back - Down - ARight Down -
((joypad0[2] | joypad0[20])<<1)| // left - Left - ARight Left -
((joypad0[3] | joypad0[21])) ); // right - Right- ARight Right-
CONTROLLER_setInput(2,
((joypad1[5] | joypad1[23])<<7)| // push - B - ALeft Down -
((joypad1[6] | joypad1[22])<<6)| // pull - X - ALeft Up -
((joypad1[4] | joypad1[25] | joypad1[11])<<5)| // rotate right - A - ALeft Right - ShRight
((joypad1[7] | joypad1[24] | joypad1[10])<<4)| // rotate left - Y - ALeft rLeft - ShLeft
((joypad1[0] | joypad1[18])<<3)| // forward - Up - ARight Up -
((joypad1[1] | joypad1[19])<<2)| // back - Down - ARight Down -
((joypad1[2] | joypad1[20])<<1)| // left - Left - ARight Left -
((joypad1[3] | joypad1[21])) ); // right - Right- ARight Right-
}
// grab frame
if(is_hle())
{
CHANNELF_HLE_run();
}
else
{
CHANNELF_run();
}
AudioBatch (AUDIO_Buffer, audioSamples);
AUDIO_frame(); // notify audio to start new audio frame
// send frame to libretro
VIDEO_drawFrame();
// 3x upscale (gives more resolution for OSD)
int offset = 0;
int color = 0;
int row;
int col;
for(row=0; row<64; row++)
{
offset = (row*3)*framePitchPixel;
for(col=0; col<102; col++)
{
color = VIDEO_Buffer_rgb[row*128+col+4];
frame[offset] = color;
frame[offset+1] = color;
frame[offset+2] = color;
frame[offset+framePitchPixel] = color;
frame[offset+framePitchPixel+1] = color;
frame[offset+framePitchPixel+2] = color;
frame[offset+2*framePitchPixel] = color;
frame[offset+2*framePitchPixel+1] = color;
frame[offset+2*framePitchPixel+2] = color;
offset+=3;
}
}
// OSD
if((joypad0[9]==1) || (joypad1[9]==1)) // Show Controller Swap State
{
if(CONTROLLER_swapped())
{
OSD_drawP1P2();
}
else
{
OSD_drawP2P1();
}
}
if(console_input) // Show Console Buttons
{
OSD_drawConsole(CONTROLLER_cursorPos(), CONTROLLER_cursorDown());
}
// Output video
Video(frame, frameWidth, frameHeight, sizeof(pixel_t) * framePitchPixel);
}
unsigned retro_get_region(void)
{
return RETRO_REGION_NTSC;
}
void retro_get_system_info(struct retro_system_info *info)
{
memset(info, 0, sizeof(*info));
info->library_name = "FreeChaF";
info->library_version = "1.0";
info->valid_extensions = "bin|rom|chf";
info->need_fullpath = false;
}
void retro_get_system_av_info(struct retro_system_av_info *info)
{
#ifdef USE_RGB565
int pixelformat = RETRO_PIXEL_FORMAT_RGB565;
#else
int pixelformat = RETRO_PIXEL_FORMAT_XRGB8888;
#endif
memset(info, 0, sizeof(*info));
info->geometry.base_width = frameWidth;
info->geometry.base_height = frameHeight;
info->geometry.max_width = frameWidth;
info->geometry.max_height = frameHeight;
info->geometry.aspect_ratio = ((float)frameWidth) / ((float)frameHeight);
info->timing.fps = DefaultFPS;
info->timing.sample_rate = 44100.0;
Environ(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &pixelformat);
}
void retro_deinit(void) { }
void retro_reset(void)
{
CHANNELF_reset();
}
struct serialized_state
{
unsigned int CPU_Ticks_Debt;
unsigned char Memory[MEMORY_SIZE];
unsigned char R[R_SIZE]; // 64 byte Scratchpad
unsigned char VIDEO_Buffer[8192];
unsigned char Ports[64];
unsigned short PC0; // Program Counter
unsigned short PC1; // Program Counter alternate
unsigned short DC0; // Data Counter
unsigned short DC1; // Data Counter alternate
unsigned char ISAR; // Indirect Scratchpad Address Register (6-bit)
unsigned char W; // Status Register (flags)
unsigned short f2102_state;
unsigned char f2102_memory[1024];
unsigned short f2102_address;
unsigned char f2102_rw;
unsigned char A; // Accumulator
unsigned char ARM, X, Y, Color;
unsigned char ControllerEnabled;
unsigned char ControllerSwapped;
unsigned char console_input;
unsigned char tone;
unsigned short amp;
struct hle_state_s hle_state;
};
size_t retro_serialize_size(void)
{
return sizeof (struct serialized_state);
}
bool retro_serialize(void *data, size_t size)
{
if (size < sizeof (struct serialized_state))
return false;
struct serialized_state *st = data;
memcpy(st->Memory, Memory, MEMORY_SIZE);
memcpy(st->R, R, R_SIZE);
memcpy(st->VIDEO_Buffer, VIDEO_Buffer_raw, sizeof(VIDEO_Buffer_raw));
memcpy(st->Ports, Ports, sizeof(Ports));
memcpy(st->f2102_memory, f2102_memory, sizeof(f2102_memory));
st->A = A;
st->ISAR = ISAR;
st->W = W;
st->PC0 = retro_cpu_to_be16(PC0);
st->PC1 = retro_cpu_to_be16(PC1);
st->DC0 = retro_cpu_to_be16(DC0);
st->DC1 = retro_cpu_to_be16(DC1);
st->X = X;
st->Y = Y;
st->Color = Color;
st->ARM = ARM;
st->f2102_rw = f2102_rw;
st->f2102_address = retro_cpu_to_be16(f2102_address);
st->f2102_state = retro_cpu_to_be16(f2102_state);
st->ControllerEnabled = ControllerEnabled;
st->ControllerSwapped = ControllerSwapped;
st->console_input = console_input;
st->tone = tone;
st->amp = retro_cpu_to_be16(amp);
st->hle_state = hle_state;
st->CPU_Ticks_Debt = retro_cpu_to_be32(CPU_Ticks_Debt);
return true;
}
bool retro_unserialize(const void *data, size_t size)
{
if (size < sizeof (struct serialized_state))
return false;
const struct serialized_state *st = data;
memcpy (Memory, st->Memory, MEMORY_SIZE);
memcpy (R, st->R, R_SIZE);
memcpy (VIDEO_Buffer_raw, st->VIDEO_Buffer, sizeof(VIDEO_Buffer_raw));
memcpy (Ports, st->Ports, sizeof(Ports));
memcpy (f2102_memory, st->f2102_memory, sizeof(f2102_memory));
A = st->A;
ISAR = st->ISAR;
W = st->W;
PC0 = retro_be_to_cpu16(st->PC0);
PC1 = retro_be_to_cpu16(st->PC1);
DC0 = retro_be_to_cpu16(st->DC0);
DC1 = retro_be_to_cpu16(st->DC1);
X = st->X;
Y = st->Y;
Color = st->Color;
ARM = st->ARM;
f2102_rw = st->f2102_rw;
f2102_address = retro_be_to_cpu16(st->f2102_address);
f2102_state = retro_be_to_cpu16(st->f2102_state);
ControllerEnabled = st->ControllerEnabled;
ControllerSwapped = st->ControllerSwapped;
console_input = st->console_input;
hle_state = st->hle_state;
tone = st->tone;
amp = retro_be_to_cpu16(st->amp);
CPU_Ticks_Debt = retro_be_to_cpu32(st->CPU_Ticks_Debt);
return true;
}
size_t retro_get_memory_size(unsigned id)
{
switch(id)
{
case RETRO_MEMORY_SYSTEM_RAM: // System Memory
return 0x10000; //65536
case RETRO_MEMORY_VIDEO_RAM: // Video Memory
return 0x2000; //8192
//case RETRO_MEMORY_SAVE_RAM: // SRAM / Regular save RAM
//case RETRO_MEMORY_RTC: // Real-time clock value
}
return 0;
}
void *retro_get_memory_data(unsigned id)
{
switch(id)
{
case RETRO_MEMORY_SYSTEM_RAM: // System Memory
return Memory;
case RETRO_MEMORY_VIDEO_RAM: // Video Memory
return VIDEO_Buffer_raw;
//case RETRO_MEMORY_SAVE_RAM: // SRAM / Regular save RAM
//case RETRO_MEMORY_RTC: // Real-time clock value
}
return 0;
}
// Stubs
unsigned int retro_api_version(void) { return RETRO_API_VERSION; }
void retro_cheat_reset(void) { }
void retro_cheat_set(unsigned index, bool enabled, const char *code) { }
bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info) { return false; }
void retro_set_controller_port_device(unsigned port, unsigned device) { }
*/
| 30.568354 | 130 | 0.67332 | [
"geometry"
] |
f6cf4780719c8ecbc45c67df23b1b7f7449597b2 | 8,950 | cc | C++ | shell/renderer/api/atom_api_renderer_ipc.cc | CezaryKulakowski/electron | eb6660f5341d6d7e2143be31eefec558fd866c84 | [
"MIT"
] | 4 | 2019-07-05T20:42:42.000Z | 2020-01-02T07:26:56.000Z | shell/renderer/api/atom_api_renderer_ipc.cc | CezaryKulakowski/electron | eb6660f5341d6d7e2143be31eefec558fd866c84 | [
"MIT"
] | 4 | 2021-03-11T05:19:38.000Z | 2022-03-28T01:24:48.000Z | shell/renderer/api/atom_api_renderer_ipc.cc | CezaryKulakowski/electron | eb6660f5341d6d7e2143be31eefec558fd866c84 | [
"MIT"
] | null | null | null | // Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include "base/task/post_task.h"
#include "base/values.h"
#include "content/public/renderer/render_frame.h"
#include "electron/shell/common/api/api.mojom.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "native_mate/object_template_builder.h"
#include "native_mate/wrappable.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/common/native_mate_converters/value_converter.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
#include "third_party/blink/public/web/web_local_frame.h"
using blink::WebLocalFrame;
using content::RenderFrame;
namespace {
RenderFrame* GetCurrentRenderFrame() {
WebLocalFrame* frame = WebLocalFrame::FrameForCurrentContext();
if (!frame)
return nullptr;
return RenderFrame::FromWebFrame(frame);
}
class IPCRenderer : public mate::Wrappable<IPCRenderer> {
public:
explicit IPCRenderer(v8::Isolate* isolate)
: task_runner_(base::CreateSingleThreadTaskRunnerWithTraits({})) {
Init(isolate);
RenderFrame* render_frame = GetCurrentRenderFrame();
DCHECK(render_frame);
// Bind the interface on the background runner. All accesses will be via
// the thread-safe pointer. This is to support our "fake-sync"
// MessageSync() hack; see the comment in IPCRenderer::SendSync.
electron::mojom::ElectronBrowserPtrInfo info;
render_frame->GetRemoteInterfaces()->GetInterface(mojo::MakeRequest(&info));
electron_browser_ptr_ =
electron::mojom::ThreadSafeElectronBrowserPtr::Create(std::move(info),
task_runner_);
}
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "IPCRenderer"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("send", &IPCRenderer::Send)
.SetMethod("sendSync", &IPCRenderer::SendSync)
.SetMethod("sendTo", &IPCRenderer::SendTo)
.SetMethod("sendToHost", &IPCRenderer::SendToHost)
.SetMethod("invoke", &IPCRenderer::Invoke);
}
static mate::Handle<IPCRenderer> Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new IPCRenderer(isolate));
}
void Send(bool internal,
const std::string& channel,
const base::ListValue& arguments) {
electron_browser_ptr_->get()->Message(internal, channel, arguments.Clone());
}
v8::Local<v8::Promise> Invoke(mate::Arguments* args,
const std::string& channel,
const base::Value& arguments) {
electron::util::Promise p(args->isolate());
auto handle = p.GetHandle();
electron_browser_ptr_->get()->Invoke(
channel, arguments.Clone(),
base::BindOnce([](electron::util::Promise p,
base::Value result) { p.Resolve(result); },
std::move(p)));
return handle;
}
void SendTo(bool internal,
bool send_to_all,
int32_t web_contents_id,
const std::string& channel,
const base::ListValue& arguments) {
electron_browser_ptr_->get()->MessageTo(
internal, send_to_all, web_contents_id, channel, arguments.Clone());
}
void SendToHost(const std::string& channel,
const base::ListValue& arguments) {
electron_browser_ptr_->get()->MessageHost(channel, arguments.Clone());
}
base::Value SendSync(bool internal,
const std::string& channel,
const base::ListValue& arguments) {
// We aren't using a true synchronous mojo call here. We're calling an
// asynchronous method and blocking on the result. The reason we're doing
// this is a little complicated, so buckle up.
//
// Mojo has a concept of synchronous calls. However, synchronous calls are
// dangerous. In particular, it's quite possible for two processes to call
// synchronous methods on each other and cause a deadlock. Mojo has a
// mechanism to avoid this kind of deadlock: if a process is waiting on the
// result of a synchronous call, and it receives an incoming call for a
// synchronous method, it will process that request immediately, even
// though it's currently blocking. However, if it receives an incoming
// request for an _asynchronous_ method, that can't cause a deadlock, so it
// stashes the request on a queue to be processed once the synchronous
// thing it's waiting on returns.
//
// This behavior is useful for preventing deadlocks, but it is inconvenient
// here because it can result in messages being reordered. If the main
// process is awaiting the result of a synchronous call (which it does only
// very rarely, since it's bad to block the main process), and we send
// first an asynchronous message to the main process, followed by a
// synchronous message, then the main process will process the synchronous
// one first.
//
// It turns out, Electron has some dependency on message ordering,
// especially during window shutdown, and getting messages out of order can
// result in, for example, remote objects disappearing unexpectedly. To
// avoid these issues and guarantee consistent message ordering, we send
// all messages to the main process as asynchronous messages. This causes
// them to always be queued and processed in the same order they were
// received, even if they were received while the main process was waiting
// on a synchronous call.
//
// However, in the calling process, we still need to block on the result,
// because the caller is expecting a result synchronously. So we do a bit
// of a trick: we pass the Mojo handle over to a worker thread, send the
// asynchronous message from that thread, and then block on the result.
// It's important that we pass the handle over to the worker thread,
// because that allows Mojo to process incoming messages (most importantly,
// the response to our request) on that thread. If we didn't pass it to a
// worker thread, and instead sent the call from the main thread, we would
// never receive a response because Mojo wouldn't be able to run its
// message handling code, because the main thread would be tied up blocking
// on the WaitableEvent.
//
// Phew. If you got this far, here's a gold star: ⭐️
base::Value result;
// A task is posted to a worker thread to execute the request so that
// this thread may block on a waitable event. It is safe to pass raw
// pointers to |result| and |response_received_event| as this stack frame
// will survive until the request is complete.
base::WaitableEvent response_received_event;
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&IPCRenderer::SendMessageSyncOnWorkerThread,
base::Unretained(this),
base::Unretained(&response_received_event),
base::Unretained(&result), internal, channel,
arguments.Clone()));
response_received_event.Wait();
return result;
}
private:
void SendMessageSyncOnWorkerThread(base::WaitableEvent* event,
base::Value* result,
bool internal,
const std::string& channel,
base::Value arguments) {
electron_browser_ptr_->get()->MessageSync(
internal, channel, std::move(arguments),
base::BindOnce(&IPCRenderer::ReturnSyncResponseToMainThread,
base::Unretained(event), base::Unretained(result)));
}
static void ReturnSyncResponseToMainThread(base::WaitableEvent* event,
base::Value* result,
base::Value response) {
*result = std::move(response);
event->Signal();
}
scoped_refptr<base::SequencedTaskRunner> task_runner_;
scoped_refptr<electron::mojom::ThreadSafeElectronBrowserPtr>
electron_browser_ptr_;
};
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.Set("ipc", IPCRenderer::Create(context->GetIsolate()));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_renderer_ipc, Initialize)
| 43.658537 | 80 | 0.663128 | [
"object"
] |
f6d310810a24e4c13ab808be5c8ade7114ec4d68 | 47,780 | cxx | C++ | VTK/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | VTK/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | VTK/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkImplicitCylinderRepresentation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImplicitCylinderRepresentation.h"
#include "vtkActor.h"
#include "vtkAssemblyNode.h"
#include "vtkAssemblyPath.h"
#include "vtkCallbackCommand.h"
#include "vtkCamera.h"
#include "vtkCellPicker.h"
#include "vtkConeSource.h"
#include "vtkFeatureEdges.h"
#include "vtkImageData.h"
#include "vtkLineSource.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkOutlineFilter.h"
#include "vtkPickingManager.h"
#include "vtkCylinder.h"
#include "vtkPlane.h"
#include "vtkPolyData.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkDoubleArray.h"
#include "vtkPointData.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSmartPointer.h"
#include "vtkSphereSource.h"
#include "vtkTransform.h"
#include "vtkTubeFilter.h"
#include "vtkInteractorObserver.h"
#include "vtkBox.h"
#include "vtkCommand.h"
#include "vtkWindow.h"
#include <algorithm>
#include <cfloat> //for FLT_EPSILON
vtkStandardNewMacro(vtkImplicitCylinderRepresentation);
//----------------------------------------------------------------------------
vtkImplicitCylinderRepresentation::vtkImplicitCylinderRepresentation()
{
this->AlongXAxis = 0;
this->AlongYAxis = 0;
this->AlongZAxis = 0;
// Handle size is in pixels for this widget
this->HandleSize = 5.0;
// Pushing operation
this->BumpDistance = 0.01;
// Build the representation of the widget
//
this->Cylinder = vtkCylinder::New();
this->Cylinder->SetAxis(0,0,1);
this->Cylinder->SetCenter(0,0,0);
this->Cylinder->SetRadius(0.5);
this->MinRadius = 0.01;
this->MaxRadius = 1.00;
this->Resolution = 128;
this->Box = vtkImageData::New();
this->Box->SetDimensions(2,2,2);
this->Outline = vtkOutlineFilter::New();
this->Outline->SetInputData(this->Box);
this->OutlineMapper = vtkPolyDataMapper::New();
this->OutlineMapper->SetInputConnection(
this->Outline->GetOutputPort());
this->OutlineActor = vtkActor::New();
this->OutlineActor->SetMapper(this->OutlineMapper);
this->OutlineTranslation = 1;
this->ScaleEnabled = 1;
this->OutsideBounds = 1;
this->ConstrainToWidgetBounds = 1;
this->Cyl = vtkPolyData::New();
vtkPoints *pts = vtkPoints::New();
pts->SetDataTypeToDouble();
this->Cyl->SetPoints(pts);
pts->Delete();
vtkCellArray *polys = vtkCellArray::New();
this->Cyl->SetPolys(polys);
polys->Delete();
vtkDoubleArray *normals = vtkDoubleArray::New();
normals->SetNumberOfComponents(3);
this->Cyl->GetPointData()->SetNormals(normals);
normals->Delete();
this->CylMapper = vtkPolyDataMapper::New();
this->CylMapper->SetInputData(this->Cyl);
this->CylActor = vtkActor::New();
this->CylActor->SetMapper(this->CylMapper);
this->DrawCylinder = 1;
this->Edges = vtkFeatureEdges::New();
this->Edges->SetInputData(this->Cyl);
this->EdgesTuber = vtkTubeFilter::New();
this->EdgesTuber->SetInputConnection(
this->Edges->GetOutputPort());
this->EdgesTuber->SetNumberOfSides(12);
this->EdgesMapper = vtkPolyDataMapper::New();
this->EdgesMapper->SetInputConnection(
this->EdgesTuber->GetOutputPort());
this->EdgesActor = vtkActor::New();
this->EdgesActor->SetMapper(this->EdgesMapper);
this->Tubing = 1; //control whether tubing is on
// Create the + cylinder axis
this->LineSource = vtkLineSource::New();
this->LineSource->SetResolution(1);
this->LineMapper = vtkPolyDataMapper::New();
this->LineMapper->SetInputConnection(
this->LineSource->GetOutputPort());
this->LineActor = vtkActor::New();
this->LineActor->SetMapper(this->LineMapper);
this->ConeSource = vtkConeSource::New();
this->ConeSource->SetResolution(12);
this->ConeSource->SetAngle(25.0);
this->ConeMapper = vtkPolyDataMapper::New();
this->ConeMapper->SetInputConnection(
this->ConeSource->GetOutputPort());
this->ConeActor = vtkActor::New();
this->ConeActor->SetMapper(this->ConeMapper);
// Create the - cylinder axis
this->LineSource2 = vtkLineSource::New();
this->LineSource2->SetResolution(1);
this->LineMapper2 = vtkPolyDataMapper::New();
this->LineMapper2->SetInputConnection(
this->LineSource2->GetOutputPort());
this->LineActor2 = vtkActor::New();
this->LineActor2->SetMapper(this->LineMapper2);
this->ConeSource2 = vtkConeSource::New();
this->ConeSource2->SetResolution(12);
this->ConeSource2->SetAngle(25.0);
this->ConeMapper2 = vtkPolyDataMapper::New();
this->ConeMapper2->SetInputConnection(
this->ConeSource2->GetOutputPort());
this->ConeActor2 = vtkActor::New();
this->ConeActor2->SetMapper(this->ConeMapper2);
// Create the center handle
this->Sphere = vtkSphereSource::New();
this->Sphere->SetThetaResolution(16);
this->Sphere->SetPhiResolution(8);
this->SphereMapper = vtkPolyDataMapper::New();
this->SphereMapper->SetInputConnection(
this->Sphere->GetOutputPort());
this->SphereActor = vtkActor::New();
this->SphereActor->SetMapper(this->SphereMapper);
this->Transform = vtkTransform::New();
// Define the point coordinates
double bounds[6];
bounds[0] = -0.5;
bounds[1] = 0.5;
bounds[2] = -0.5;
bounds[3] = 0.5;
bounds[4] = -0.5;
bounds[5] = 0.5;
// Initial creation of the widget, serves to initialize it
this->PlaceWidget(bounds);
//Manage the picking stuff
this->Picker = vtkCellPicker::New();
this->Picker->SetTolerance(0.005);
this->Picker->AddPickList(this->LineActor);
this->Picker->AddPickList(this->ConeActor);
this->Picker->AddPickList(this->LineActor2);
this->Picker->AddPickList(this->ConeActor2);
this->Picker->AddPickList(this->SphereActor);
this->Picker->AddPickList(this->OutlineActor);
this->Picker->PickFromListOn();
this->CylPicker = vtkCellPicker::New();
this->CylPicker->SetTolerance(0.005);
this->CylPicker->AddPickList(this->CylActor);
this->CylPicker->AddPickList(this->EdgesActor);
this->CylPicker->PickFromListOn();
// Set up the initial properties
this->CreateDefaultProperties();
// Pass the initial properties to the actors.
this->LineActor->SetProperty(this->AxisProperty);
this->ConeActor->SetProperty(this->AxisProperty);
this->LineActor2->SetProperty(this->AxisProperty);
this->ConeActor2->SetProperty(this->AxisProperty);
this->SphereActor->SetProperty(this->AxisProperty);
this->CylActor->SetProperty(this->CylinderProperty);
this->OutlineActor->SetProperty(this->OutlineProperty);
// The bounding box
this->BoundingBox = vtkBox::New();
this->RepresentationState = vtkImplicitCylinderRepresentation::Outside;
}
//----------------------------------------------------------------------------
vtkImplicitCylinderRepresentation::~vtkImplicitCylinderRepresentation()
{
this->Cylinder->Delete();
this->Box->Delete();
this->Outline->Delete();
this->OutlineMapper->Delete();
this->OutlineActor->Delete();
this->Cyl->Delete();
this->CylMapper->Delete();
this->CylActor->Delete();
this->Edges->Delete();
this->EdgesTuber->Delete();
this->EdgesMapper->Delete();
this->EdgesActor->Delete();
this->LineSource->Delete();
this->LineMapper->Delete();
this->LineActor->Delete();
this->ConeSource->Delete();
this->ConeMapper->Delete();
this->ConeActor->Delete();
this->LineSource2->Delete();
this->LineMapper2->Delete();
this->LineActor2->Delete();
this->ConeSource2->Delete();
this->ConeMapper2->Delete();
this->ConeActor2->Delete();
this->Sphere->Delete();
this->SphereMapper->Delete();
this->SphereActor->Delete();
this->Transform->Delete();
this->Picker->Delete();
this->CylPicker->Delete();
this->AxisProperty->Delete();
this->SelectedAxisProperty->Delete();
this->CylinderProperty->Delete();
this->SelectedCylinderProperty->Delete();
this->OutlineProperty->Delete();
this->SelectedOutlineProperty->Delete();
this->EdgesProperty->Delete();
this->BoundingBox->Delete();
}
//----------------------------------------------------------------------------
int vtkImplicitCylinderRepresentation::ComputeInteractionState(int X, int Y,
int vtkNotUsed(modify))
{
// See if anything has been selected
vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->Picker);
// The second picker may need to be called. This is done because the cylinder
// wraps around things that can be picked; thus the cylinder is the selection
// of last resort.
if ( path == nullptr )
{
this->CylPicker->Pick(X, Y, 0., this->Renderer);
path = this->CylPicker->GetPath();
}
if ( path == nullptr ) // Nothing picked
{
this->SetRepresentationState(vtkImplicitCylinderRepresentation::Outside);
this->InteractionState = vtkImplicitCylinderRepresentation::Outside;
return this->InteractionState;
}
// Something picked, continue
this->ValidPick = 1;
// Depending on the interaction state (set by the widget) we modify
// this state based on what is picked.
if ( this->InteractionState == vtkImplicitCylinderRepresentation::Moving )
{
vtkProp *prop = path->GetFirstNode()->GetViewProp();
if ( prop == this->ConeActor || prop == this->LineActor ||
prop == this->ConeActor2 || prop == this->LineActor2 )
{
this->InteractionState = vtkImplicitCylinderRepresentation::RotatingAxis;
this->SetRepresentationState(vtkImplicitCylinderRepresentation::RotatingAxis);
}
else if ( prop == this->CylActor || prop == EdgesActor )
{
this->InteractionState = vtkImplicitCylinderRepresentation::AdjustingRadius;
this->SetRepresentationState(vtkImplicitCylinderRepresentation::AdjustingRadius);
}
else if ( prop == this->SphereActor )
{
this->InteractionState = vtkImplicitCylinderRepresentation::MovingCenter;
this->SetRepresentationState(vtkImplicitCylinderRepresentation::MovingCenter);
}
else
{
if ( this->OutlineTranslation )
{
this->InteractionState = vtkImplicitCylinderRepresentation::MovingOutline;
this->SetRepresentationState(vtkImplicitCylinderRepresentation::MovingOutline);
}
else
{
this->InteractionState = vtkImplicitCylinderRepresentation::Outside;
this->SetRepresentationState(vtkImplicitCylinderRepresentation::Outside);
}
}
}
// We may add a condition to allow the camera to work IO scaling
else if ( this->InteractionState != vtkImplicitCylinderRepresentation::Scaling )
{
this->InteractionState = vtkImplicitCylinderRepresentation::Outside;
}
return this->InteractionState;
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetRepresentationState(int state)
{
if (this->RepresentationState == state)
{
return;
}
// Clamp the state
state = (state < vtkImplicitCylinderRepresentation::Outside ?
vtkImplicitCylinderRepresentation::Outside :
(state > vtkImplicitCylinderRepresentation::Scaling ?
vtkImplicitCylinderRepresentation::Scaling : state));
this->RepresentationState = state;
this->Modified();
if ( state == vtkImplicitCylinderRepresentation::RotatingAxis )
{
this->HighlightNormal(1);
this->HighlightCylinder(1);
}
else if ( state == vtkImplicitCylinderRepresentation::AdjustingRadius )
{
this->HighlightCylinder(1);
}
else if ( state == vtkImplicitCylinderRepresentation::MovingCenter )
{
this->HighlightNormal(1);
}
else if ( state == vtkImplicitCylinderRepresentation::MovingOutline )
{
this->HighlightOutline(1);
}
else if ( state == vtkImplicitCylinderRepresentation::Scaling &&
this->ScaleEnabled )
{
this->HighlightNormal(1);
this->HighlightCylinder(1);
this->HighlightOutline(1);
}
else if ( state == vtkImplicitCylinderRepresentation::TranslatingCenter )
{
this->HighlightNormal(1);
}
else
{
this->HighlightNormal(0);
this->HighlightCylinder(0);
this->HighlightOutline(0);
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::StartWidgetInteraction(double e[2])
{
this->StartEventPosition[0] = e[0];
this->StartEventPosition[1] = e[1];
this->StartEventPosition[2] = 0.0;
this->LastEventPosition[0] = e[0];
this->LastEventPosition[1] = e[1];
this->LastEventPosition[2] = 0.0;
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::WidgetInteraction(double e[2])
{
// Do different things depending on state
// Calculations everybody does
double focalPoint[4], pickPoint[4], prevPickPoint[4];
double z, vpn[3];
vtkCamera *camera = this->Renderer->GetActiveCamera();
if ( !camera )
{
return;
}
// Compute the two points defining the motion vector
double pos[3];
this->Picker->GetPickPosition(pos);
vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer, pos[0], pos[1], pos[2],
focalPoint);
z = focalPoint[2];
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,this->LastEventPosition[0],
this->LastEventPosition[1], z, prevPickPoint);
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer, e[0], e[1], z, pickPoint);
// Process the motion
if ( this->InteractionState == vtkImplicitCylinderRepresentation::MovingOutline )
{
this->TranslateOutline(prevPickPoint, pickPoint);
}
else if ( this->InteractionState == vtkImplicitCylinderRepresentation::MovingCenter )
{
this->TranslateCenter(prevPickPoint, pickPoint);
}
else if ( this->InteractionState == vtkImplicitCylinderRepresentation::TranslatingCenter )
{
this->TranslateCenterOnAxis(prevPickPoint, pickPoint);
}
else if ( this->InteractionState == vtkImplicitCylinderRepresentation::AdjustingRadius )
{
this->AdjustRadius(e[0], e[1], prevPickPoint, pickPoint);
}
else if ( this->InteractionState == vtkImplicitCylinderRepresentation::Scaling &&
this->ScaleEnabled )
{
this->Scale(prevPickPoint, pickPoint, e[0], e[1]);
}
else if ( this->InteractionState == vtkImplicitCylinderRepresentation::RotatingAxis )
{
camera->GetViewPlaneNormal(vpn);
this->Rotate(e[0], e[1], prevPickPoint, pickPoint, vpn);
}
this->LastEventPosition[0] = e[0];
this->LastEventPosition[1] = e[1];
this->LastEventPosition[2] = 0.0;
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::EndWidgetInteraction(double vtkNotUsed(e)[2])
{
this->SetRepresentationState(vtkImplicitCylinderRepresentation::Outside);
}
//----------------------------------------------------------------------
double *vtkImplicitCylinderRepresentation::GetBounds()
{
this->BuildRepresentation();
this->BoundingBox->SetBounds(this->OutlineActor->GetBounds());
this->BoundingBox->AddBounds(this->CylActor->GetBounds());
this->BoundingBox->AddBounds(this->EdgesActor->GetBounds());
this->BoundingBox->AddBounds(this->ConeActor->GetBounds());
this->BoundingBox->AddBounds(this->LineActor->GetBounds());
this->BoundingBox->AddBounds(this->ConeActor2->GetBounds());
this->BoundingBox->AddBounds(this->LineActor2->GetBounds());
this->BoundingBox->AddBounds(this->SphereActor->GetBounds());
return this->BoundingBox->GetBounds();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::GetActors(vtkPropCollection *pc)
{
this->OutlineActor->GetActors(pc);
this->CylActor->GetActors(pc);
this->EdgesActor->GetActors(pc);
this->ConeActor->GetActors(pc);
this->LineActor->GetActors(pc);
this->ConeActor2->GetActors(pc);
this->LineActor2->GetActors(pc);
this->SphereActor->GetActors(pc);
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::ReleaseGraphicsResources(vtkWindow *w)
{
this->OutlineActor->ReleaseGraphicsResources(w);
this->CylActor->ReleaseGraphicsResources(w);
this->EdgesActor->ReleaseGraphicsResources(w);
this->ConeActor->ReleaseGraphicsResources(w);
this->LineActor->ReleaseGraphicsResources(w);
this->ConeActor2->ReleaseGraphicsResources(w);
this->LineActor2->ReleaseGraphicsResources(w);
this->SphereActor->ReleaseGraphicsResources(w);
}
//----------------------------------------------------------------------------
int vtkImplicitCylinderRepresentation::RenderOpaqueGeometry(vtkViewport *v)
{
int count=0;
this->BuildRepresentation();
count += this->OutlineActor->RenderOpaqueGeometry(v);
count += this->EdgesActor->RenderOpaqueGeometry(v);
count += this->ConeActor->RenderOpaqueGeometry(v);
count += this->LineActor->RenderOpaqueGeometry(v);
count += this->ConeActor2->RenderOpaqueGeometry(v);
count += this->LineActor2->RenderOpaqueGeometry(v);
count += this->SphereActor->RenderOpaqueGeometry(v);
if ( this->DrawCylinder )
{
count += this->CylActor->RenderOpaqueGeometry(v);
}
return count;
}
//-----------------------------------------------------------------------------
int vtkImplicitCylinderRepresentation::RenderTranslucentPolygonalGeometry(
vtkViewport *v)
{
int count=0;
this->BuildRepresentation();
count += this->OutlineActor->RenderTranslucentPolygonalGeometry(v);
count += this->EdgesActor->RenderTranslucentPolygonalGeometry(v);
count += this->ConeActor->RenderTranslucentPolygonalGeometry(v);
count += this->LineActor->RenderTranslucentPolygonalGeometry(v);
count += this->ConeActor2->RenderTranslucentPolygonalGeometry(v);
count += this->LineActor2->RenderTranslucentPolygonalGeometry(v);
count += this->SphereActor->RenderTranslucentPolygonalGeometry(v);
if ( this->DrawCylinder )
{
count += this->CylActor->RenderTranslucentPolygonalGeometry(v);
}
return count;
}
//-----------------------------------------------------------------------------
int vtkImplicitCylinderRepresentation::HasTranslucentPolygonalGeometry()
{
int result=0;
result |= this->OutlineActor->HasTranslucentPolygonalGeometry();
result |= this->EdgesActor->HasTranslucentPolygonalGeometry();
result |= this->ConeActor->HasTranslucentPolygonalGeometry();
result |= this->LineActor->HasTranslucentPolygonalGeometry();
result |= this->ConeActor2->HasTranslucentPolygonalGeometry();
result |= this->LineActor2->HasTranslucentPolygonalGeometry();
result |= this->SphereActor->HasTranslucentPolygonalGeometry();
if ( this->DrawCylinder )
{
result |= this->CylActor->HasTranslucentPolygonalGeometry();
}
return result;
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Min Radius: " << this->MinRadius << "\n";
os << indent << "Max Radius: " << this->MaxRadius << "\n";
os << indent << "Resolution: " << this->Resolution << "\n";
if ( this->AxisProperty )
{
os << indent << "Axis Property: " << this->AxisProperty << "\n";
}
else
{
os << indent << "Axis Property: (none)\n";
}
if ( this->SelectedAxisProperty )
{
os << indent << "Selected Axis Property: "
<< this->SelectedAxisProperty << "\n";
}
else
{
os << indent << "Selected Axis Property: (none)\n";
}
if ( this->CylinderProperty )
{
os << indent << "Cylinder Property: " << this->CylinderProperty << "\n";
}
else
{
os << indent << "Cylinder Property: (none)\n";
}
if ( this->SelectedCylinderProperty )
{
os << indent << "Selected Cylinder Property: "
<< this->SelectedCylinderProperty << "\n";
}
else
{
os << indent << "Selected Cylinder Property: (none)\n";
}
if ( this->OutlineProperty )
{
os << indent << "Outline Property: " << this->OutlineProperty << "\n";
}
else
{
os << indent << "Outline Property: (none)\n";
}
if ( this->SelectedOutlineProperty )
{
os << indent << "Selected Outline Property: "
<< this->SelectedOutlineProperty << "\n";
}
else
{
os << indent << "Selected Outline Property: (none)\n";
}
if ( this->EdgesProperty )
{
os << indent << "Edges Property: " << this->EdgesProperty << "\n";
}
else
{
os << indent << "Edges Property: (none)\n";
}
os << indent << "Along X Axis: "
<< (this->AlongXAxis ? "On" : "Off") << "\n";
os << indent << "Along Y Axis: "
<< (this->AlongYAxis ? "On" : "Off") << "\n";
os << indent << "ALong Z Axis: "
<< (this->AlongZAxis ? "On" : "Off") << "\n";
os << indent << "Widget Bounds: " << this->WidgetBounds[0] << ", "
<< this->WidgetBounds[1] << ", "
<< this->WidgetBounds[2] << ", "
<< this->WidgetBounds[3] << ", "
<< this->WidgetBounds[4] << ", "
<< this->WidgetBounds[5] << "\n";
os << indent << "Tubing: " << (this->Tubing ? "On" : "Off") << "\n";
os << indent << "Outline Translation: "
<< (this->OutlineTranslation ? "On" : "Off") << "\n";
os << indent << "Outside Bounds: "
<< (this->OutsideBounds ? "On" : "Off") << "\n";
os << indent << "Constrain to Widget Bounds: "
<< (this->ConstrainToWidgetBounds ? "On" : "Off") << "\n";
os << indent << "Scale Enabled: "
<< (this->ScaleEnabled ? "On" : "Off") << "\n";
os << indent << "Draw Cylinder: " << (this->DrawCylinder ? "On" : "Off") << "\n";
os << indent << "Bump Distance: " << this->BumpDistance << "\n";
os << indent << "Representation State: ";
switch ( this->RepresentationState )
{
case Outside:
os << "Outside\n";
break;
case Moving:
os << "Moving\n";
break;
case MovingOutline:
os << "MovingOutline\n";
break;
case MovingCenter:
os << "MovingCenter\n";
break;
case RotatingAxis:
os << "RotatingAxis\n";
break;
case AdjustingRadius:
os << "AdjustingRadius\n";
break;
case Scaling:
os << "Scaling\n";
break;
case TranslatingCenter:
os << "TranslatingCenter\n";
break;
}
// this->InteractionState is printed in superclass
// this is commented to avoid PrintSelf errors
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::HighlightNormal(int highlight)
{
if ( highlight )
{
this->LineActor->SetProperty(this->SelectedAxisProperty);
this->ConeActor->SetProperty(this->SelectedAxisProperty);
this->LineActor2->SetProperty(this->SelectedAxisProperty);
this->ConeActor2->SetProperty(this->SelectedAxisProperty);
this->SphereActor->SetProperty(this->SelectedAxisProperty);
}
else
{
this->LineActor->SetProperty(this->AxisProperty);
this->ConeActor->SetProperty(this->AxisProperty);
this->LineActor2->SetProperty(this->AxisProperty);
this->ConeActor2->SetProperty(this->AxisProperty);
this->SphereActor->SetProperty(this->AxisProperty);
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::HighlightCylinder(int highlight)
{
if ( highlight )
{
this->CylActor->SetProperty(this->SelectedCylinderProperty);
}
else
{
this->CylActor->SetProperty(this->CylinderProperty);
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::HighlightOutline(int highlight)
{
if ( highlight )
{
this->OutlineActor->SetProperty(this->SelectedOutlineProperty);
}
else
{
this->OutlineActor->SetProperty(this->OutlineProperty);
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::Rotate(double X, double Y,
double *p1, double *p2, double *vpn)
{
double v[3]; //vector of motion
double axis[3]; //axis of rotation
double theta; //rotation angle
// mouse motion vector in world space
v[0] = p2[0] - p1[0];
v[1] = p2[1] - p1[1];
v[2] = p2[2] - p1[2];
double *center = this->Cylinder->GetCenter();
double *cylAxis = this->Cylinder->GetAxis();
// Create axis of rotation and angle of rotation
vtkMath::Cross(vpn,v,axis);
if ( vtkMath::Normalize(axis) == 0.0 )
{
return;
}
int *size = this->Renderer->GetSize();
double l2 = (X-this->LastEventPosition[0])*(X-this->LastEventPosition[0]) +
(Y-this->LastEventPosition[1])*(Y-this->LastEventPosition[1]);
theta = 360.0 * sqrt(l2/(size[0]*size[0]+size[1]*size[1]));
// Manipulate the transform to reflect the rotation
this->Transform->Identity();
this->Transform->Translate(center[0],center[1],center[2]);
this->Transform->RotateWXYZ(theta,axis);
this->Transform->Translate(-center[0],-center[1],-center[2]);
//Set the new normal
double aNew[3];
this->Transform->TransformNormal(cylAxis,aNew);
this->SetAxis(aNew);
}
//----------------------------------------------------------------------------
// Loop through all points and translate them
void vtkImplicitCylinderRepresentation::TranslateOutline(double *p1, double *p2)
{
//Get the motion vector
double v[3];
v[0] = p2[0] - p1[0];
v[1] = p2[1] - p1[1];
v[2] = p2[2] - p1[2];
//Translate the bounding box
double *origin = this->Box->GetOrigin();
double oNew[3];
oNew[0] = origin[0] + v[0];
oNew[1] = origin[1] + v[1];
oNew[2] = origin[2] + v[2];
this->Box->SetOrigin(oNew);
this->Box->GetBounds(this->WidgetBounds);
//Translate the cylinder
origin = this->Cylinder->GetCenter();
oNew[0] = origin[0] + v[0];
oNew[1] = origin[1] + v[1];
oNew[2] = origin[2] + v[2];
this->Cylinder->SetCenter(oNew);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
// Loop through all points and translate them
void vtkImplicitCylinderRepresentation::TranslateCenter(double *p1, double *p2)
{
//Get the motion vector
double v[3];
v[0] = p2[0] - p1[0];
v[1] = p2[1] - p1[1];
v[2] = p2[2] - p1[2];
//Add to the current point, project back down onto plane
double *c = this->Cylinder->GetCenter();
double *a = this->Cylinder->GetAxis();
double newCenter[3];
newCenter[0] = c[0] + v[0];
newCenter[1] = c[1] + v[1];
newCenter[2] = c[2] + v[2];
vtkPlane::ProjectPoint(newCenter,c,a,newCenter);
this->SetCenter(newCenter[0],newCenter[1],newCenter[2]);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
// Translate the center on the axis
void vtkImplicitCylinderRepresentation::TranslateCenterOnAxis(double *p1, double *p2)
{
// Get the motion vector
double v[3];
v[0] = p2[0] - p1[0];
v[1] = p2[1] - p1[1];
v[2] = p2[2] - p1[2];
// Add to the current point, project back down onto plane
double *c = this->Cylinder->GetCenter();
double *a = this->Cylinder->GetAxis();
double newCenter[3];
newCenter[0] = c[0] + v[0];
newCenter[1] = c[1] + v[1];
newCenter[2] = c[2] + v[2];
// Normalize the axis vector
const double imag = 1. /
std::max(1.0e-100, sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]));
double an[3];
an[0] = a[0] * imag;
an[1] = a[1] * imag;
an[2] = a[2] * imag;
// Project the point on the axis vector
double u[3];
u[0] = newCenter[0] - c[0];
u[1] = newCenter[1] - c[1];
u[2] = newCenter[2] - c[2];
double dot = an[0] * u[0] + an[1] * u[1] + an[2] * u[2];
newCenter[0] = c[0] + an[0] * dot;
newCenter[1] = c[1] + an[1] * dot;
newCenter[2] = c[2] + an[2] * dot;
this->SetCenter(newCenter[0],newCenter[1],newCenter[2]);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::Scale(double *p1, double *p2,
double vtkNotUsed(X), double Y)
{
//Get the motion vector
double v[3];
v[0] = p2[0] - p1[0];
v[1] = p2[1] - p1[1];
v[2] = p2[2] - p1[2];
double *o = this->Cylinder->GetCenter();
// Compute the scale factor
double sf = vtkMath::Norm(v) / this->Outline->GetOutput()->GetLength();
if ( Y > this->LastEventPosition[1] )
{
sf = 1.0 + sf;
}
else
{
sf = 1.0 - sf;
}
this->Transform->Identity();
this->Transform->Translate(o[0],o[1],o[2]);
this->Transform->Scale(sf,sf,sf);
this->Transform->Translate(-o[0],-o[1],-o[2]);
double *origin = this->Box->GetOrigin();
double *spacing = this->Box->GetSpacing();
double oNew[3], p[3], pNew[3];
p[0] = origin[0] + spacing[0];
p[1] = origin[1] + spacing[1];
p[2] = origin[2] + spacing[2];
this->Transform->TransformPoint(origin,oNew);
this->Transform->TransformPoint(p,pNew);
this->Box->SetOrigin(oNew);
this->Box->SetSpacing( (pNew[0]-oNew[0]),
(pNew[1]-oNew[1]),
(pNew[2]-oNew[2]) );
this->Box->GetBounds(this->WidgetBounds);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::
AdjustRadius(double vtkNotUsed(X), double Y, double *p1, double *p2)
{
if ( Y == this->LastEventPosition[1] )
{
return;
}
double dr, radius = this->Cylinder->GetRadius();
double v[3]; //vector of motion
v[0] = p2[0] - p1[0];
v[1] = p2[1] - p1[1];
v[2] = p2[2] - p1[2];
double l = sqrt( vtkMath::Dot(v,v) );
dr = l / 4;
if ( Y < this->LastEventPosition[1] )
{
dr *= -1.0;
}
this->SetRadius(radius + dr);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::CreateDefaultProperties()
{
// Cylinder properties
this->CylinderProperty = vtkProperty::New();
this->CylinderProperty->SetAmbient(1.0);
this->CylinderProperty->SetAmbientColor(1.0,1.0,1.0);
this->CylinderProperty->SetOpacity(0.5);
this->CylActor->SetProperty(this->CylinderProperty);
this->SelectedCylinderProperty = vtkProperty::New();
this->SelectedCylinderProperty->SetAmbient(1.0);
this->SelectedCylinderProperty->SetAmbientColor(0.0,1.0,0.0);
this->SelectedCylinderProperty->SetOpacity(0.25);
// Cylinder axis properties
this->AxisProperty = vtkProperty::New();
this->AxisProperty->SetColor(1,1,1);
this->AxisProperty->SetLineWidth(2);
this->SelectedAxisProperty = vtkProperty::New();
this->SelectedAxisProperty->SetColor(1,0,0);
this->SelectedAxisProperty->SetLineWidth(2);
// Outline properties
this->OutlineProperty = vtkProperty::New();
this->OutlineProperty->SetAmbient(1.0);
this->OutlineProperty->SetAmbientColor(1.0,1.0,1.0);
this->SelectedOutlineProperty = vtkProperty::New();
this->SelectedOutlineProperty->SetAmbient(1.0);
this->SelectedOutlineProperty->SetAmbientColor(0.0,1.0,0.0);
// Edge property
this->EdgesProperty = vtkProperty::New();
this->EdgesProperty->SetAmbient(1.0);
this->EdgesProperty->SetAmbientColor(1.0,1.0,1.0);
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetEdgeColor(vtkLookupTable* lut)
{
this->EdgesMapper->SetLookupTable(lut);
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetEdgeColor(double r, double g, double b)
{
vtkSmartPointer<vtkLookupTable> lookupTable =
vtkSmartPointer<vtkLookupTable>::New();
lookupTable->SetTableRange(0.0, 1.0);
lookupTable->SetNumberOfTableValues(1);
lookupTable->SetTableValue(0, r, g, b);
lookupTable->Build();
this->SetEdgeColor(lookupTable);
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetEdgeColor(double c[3])
{
this->SetEdgeColor(c[0], c[1], c[2]);
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::PlaceWidget(double bds[6])
{
int i;
double bounds[6], origin[3];
this->AdjustBounds(bds, bounds, origin);
// Set up the bounding box
this->Box->SetOrigin(bounds[0],bounds[2],bounds[4]);
this->Box->SetSpacing((bounds[1]-bounds[0]),(bounds[3]-bounds[2]),
(bounds[5]-bounds[4]));
this->Outline->Update();
this->LineSource->SetPoint1(this->Cylinder->GetCenter());
if ( this->AlongYAxis )
{
this->Cylinder->SetAxis(0,1,0);
this->LineSource->SetPoint2(0,1,0);
}
else if ( this->AlongZAxis )
{
this->Cylinder->SetAxis(0,0,1);
this->LineSource->SetPoint2(0,0,1);
}
else //default or x-normal
{
this->Cylinder->SetAxis(1,0,0);
this->LineSource->SetPoint2(1,0,0);
}
for (i=0; i<6; i++)
{
this->InitialBounds[i] = bounds[i];
this->WidgetBounds[i] = bounds[i];
}
this->InitialLength = sqrt((bounds[1]-bounds[0])*(bounds[1]-bounds[0]) +
(bounds[3]-bounds[2])*(bounds[3]-bounds[2]) +
(bounds[5]-bounds[4])*(bounds[5]-bounds[4]));
this->ValidPick = 1; // since we have positioned the widget successfully
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
// Set the center of the cylinder.
void vtkImplicitCylinderRepresentation::SetCenter(double x, double y, double z)
{
double center[3];
center[0] = x;
center[1] = y;
center[2] = z;
this->SetCenter(center);
}
//----------------------------------------------------------------------------
// Set the center of the cylinder. Note that the center is clamped slightly inside
// the bounding box or the cylinder tends to disappear as it hits the boundary.
void vtkImplicitCylinderRepresentation::SetCenter(double x[3])
{
this->Cylinder->SetCenter(x);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
// Get the center of the cylinder.
double* vtkImplicitCylinderRepresentation::GetCenter()
{
return this->Cylinder->GetCenter();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::GetCenter(double xyz[3])
{
return this->Cylinder->GetCenter(xyz);
}
//----------------------------------------------------------------------------
// Set the axis of the cylinder.
void vtkImplicitCylinderRepresentation::SetAxis(double x, double y, double z)
{
double n[3], n2[3];
n[0] = x;
n[1] = y;
n[2] = z;
vtkMath::Normalize(n);
this->Cylinder->GetAxis(n2);
if ( n[0] != n2[0] || n[1] != n2[1] || n[2] != n2[2] )
{
this->Cylinder->SetAxis(n);
this->Modified();
}
}
//----------------------------------------------------------------------------
// Set the axis the cylinder.
void vtkImplicitCylinderRepresentation::SetAxis(double n[3])
{
this->SetAxis(n[0], n[1], n[2]);
}
//----------------------------------------------------------------------------
// Get the axis of the cylinder.
double* vtkImplicitCylinderRepresentation::GetAxis()
{
return this->Cylinder->GetAxis();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::GetAxis(double xyz[3])
{
return this->Cylinder->GetAxis(xyz);
}
//----------------------------------------------------------------------------
// Set the radius the cylinder. The radius must be a positive number.
void vtkImplicitCylinderRepresentation::SetRadius(double radius)
{
if (this->ConstrainToWidgetBounds)
{
double minRadius = this->Outline->GetOutput()->GetLength() * this->MinRadius;
double maxRadius = this->Outline->GetOutput()->GetLength() * this->MaxRadius;
radius = std::min(maxRadius, std::max(minRadius, radius));
}
this->Cylinder->SetRadius(radius);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
// Get the radius the cylinder.
double vtkImplicitCylinderRepresentation::GetRadius()
{
return this->Cylinder->GetRadius();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetDrawCylinder(vtkTypeBool drawCyl)
{
if ( drawCyl == this->DrawCylinder )
{
return;
}
this->Modified();
this->DrawCylinder = drawCyl;
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetAlongXAxis (vtkTypeBool var)
{
if (this->AlongXAxis != var)
{
this->AlongXAxis = var;
this->Modified();
}
if (var)
{
this->AlongYAxisOff();
this->AlongZAxisOff();
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetAlongYAxis (vtkTypeBool var)
{
if (this->AlongYAxis != var)
{
this->AlongYAxis = var;
this->Modified();
}
if (var)
{
this->AlongXAxisOff();
this->AlongZAxisOff();
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SetAlongZAxis (vtkTypeBool var)
{
if (this->AlongZAxis != var)
{
this->AlongZAxis = var;
this->Modified();
}
if (var)
{
this->AlongXAxisOff();
this->AlongYAxisOff();
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::GetPolyData(vtkPolyData *pd)
{
pd->ShallowCopy(this->Cyl);
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::GetCylinder(vtkCylinder *cyl)
{
if ( cyl == nullptr )
{
return;
}
cyl->SetAxis(this->Cylinder->GetAxis());
cyl->SetCenter(this->Cylinder->GetCenter());
cyl->SetRadius(this->Cylinder->GetRadius());
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::UpdatePlacement()
{
this->BuildRepresentation();
this->Outline->Update();
this->Edges->Update();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::BumpCylinder(int dir, double factor)
{
// Compute the distance
double d = this->InitialLength * this->BumpDistance * factor;
// Push the cylinder
this->PushCylinder( (dir > 0 ? d : -d) );
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::PushCylinder(double d)
{
vtkCamera *camera = this->Renderer->GetActiveCamera();
if ( !camera )
{
return;
}
double vpn[3], center[3];
camera->GetViewPlaneNormal(vpn);
this->Cylinder->GetCenter(center);
center[0] += d*vpn[0];
center[1] += d*vpn[1];
center[2] += d*vpn[2];
this->Cylinder->SetCenter(center);
this->BuildRepresentation();
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::BuildRepresentation()
{
if ( !this->Renderer || !this->Renderer->GetRenderWindow() )
{
return;
}
vtkInformation *info = this->GetPropertyKeys();
this->OutlineActor->SetPropertyKeys(info);
this->CylActor->SetPropertyKeys(info);
this->EdgesActor->SetPropertyKeys(info);
this->ConeActor->SetPropertyKeys(info);
this->LineActor->SetPropertyKeys(info);
this->ConeActor2->SetPropertyKeys(info);
this->LineActor2->SetPropertyKeys(info);
this->SphereActor->SetPropertyKeys(info);
if ( this->GetMTime() > this->BuildTime ||
this->Cylinder->GetMTime() > this->BuildTime ||
this->Renderer->GetRenderWindow()->GetMTime() > this->BuildTime)
{
double *center = this->Cylinder->GetCenter();
double *axis = this->Cylinder->GetAxis();
double bounds[6];
std::copy(this->WidgetBounds, this->WidgetBounds + 6, bounds);
double p2[3];
if ( !this->OutsideBounds )
{
// restrict the center inside InitialBounds
double *ibounds = this->InitialBounds;
for (int i=0; i<3; i++)
{
if ( center[i] < ibounds[2*i] )
{
center[i] = ibounds[2*i];
}
else if ( center[i] > ibounds[2*i+1] )
{
center[i] = ibounds[2*i+1];
}
}
}
if ( this->ConstrainToWidgetBounds )
{
if ( !this->OutsideBounds )
{
// center cannot move outside InitialBounds. Therefore, restrict
// movement of the Box.
double v[3] = { 0.0, 0.0, 0.0 };
for (int i = 0; i < 3; ++i)
{
if (center[i] <= bounds[2*i])
{
v[i] = center[i] - bounds[2*i] - FLT_EPSILON;
}
else if (center[i] >= bounds[2*i + 1])
{
v[i] = center[i] - bounds[2*i + 1] + FLT_EPSILON;
}
bounds[2*i] += v[i];
bounds[2*i + 1] += v[i];
}
}
// restrict center inside bounds
for (int i = 0; i < 3; ++i)
{
if (center[i] <= bounds[2*i])
{
center[i] = bounds[2*i] + FLT_EPSILON;
}
if (center[i] >= bounds[2*i + 1])
{
center[i] = bounds[2*i + 1] - FLT_EPSILON;
}
}
}
else // cylinder can move freely, adjust the bounds to change with it
{
double offset = this->Cylinder->GetRadius() * 1.2;
for (int i = 0; i < 3; ++i)
{
bounds[2*i] = vtkMath::Min(center[i] - offset, this->WidgetBounds[2*i]);
bounds[2*i + 1] = vtkMath::Max(center[i] + offset, this->WidgetBounds[2*i + 1]);
}
}
this->Box->SetOrigin(bounds[0],bounds[2],bounds[4]);
this->Box->SetSpacing((bounds[1]-bounds[0]),(bounds[3]-bounds[2]),
(bounds[5]-bounds[4]));
this->Outline->Update();
// Setup the cylinder axis
double d = this->Outline->GetOutput()->GetLength();
p2[0] = center[0] + 0.30 * d * axis[0];
p2[1] = center[1] + 0.30 * d * axis[1];
p2[2] = center[2] + 0.30 * d * axis[2];
this->LineSource->SetPoint1(center);
this->LineSource->SetPoint2(p2);
this->ConeSource->SetCenter(p2);
this->ConeSource->SetDirection(axis);
p2[0] = center[0] - 0.30 * d * axis[0];
p2[1] = center[1] - 0.30 * d * axis[1];
p2[2] = center[2] - 0.30 * d * axis[2];
this->LineSource2->SetPoint1(center[0],center[1],center[2]);
this->LineSource2->SetPoint2(p2);
this->ConeSource2->SetCenter(p2);
this->ConeSource2->SetDirection(axis[0],axis[1],axis[2]);
// Set up the position handle
this->Sphere->SetCenter(center[0],center[1],center[2]);
// Control the look of the edges
if ( this->Tubing )
{
this->EdgesMapper->SetInputConnection(
this->EdgesTuber->GetOutputPort());
}
else
{
this->EdgesMapper->SetInputConnection(
this->Edges->GetOutputPort());
}
// Construct intersected cylinder
this->BuildCylinder();
this->SizeHandles();
this->BuildTime.Modified();
}
}
//----------------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::SizeHandles()
{
double radius =
this->vtkWidgetRepresentation::SizeHandlesInPixels(1.5,this->Sphere->GetCenter());
this->ConeSource->SetHeight(2.0*radius);
this->ConeSource->SetRadius(radius);
this->ConeSource2->SetHeight(2.0*radius);
this->ConeSource2->SetRadius(radius);
this->Sphere->SetRadius(radius);
this->EdgesTuber->SetRadius(0.25*radius);
}
//----------------------------------------------------------------------
// Create cylinder polydata. Basically build an oriented cylinder of
// specified resolution. Trim cylinder facets by performing
// intersection tests. Note that some facets may be outside the
// bounding box, in which cases they are discarded.
void vtkImplicitCylinderRepresentation::BuildCylinder()
{
// Initialize the polydata
this->Cyl->Reset();
vtkPoints *pts = this->Cyl->GetPoints();
vtkDataArray *normals = this->Cyl->GetPointData()->GetNormals();
vtkCellArray *polys = this->Cyl->GetPolys();
// Retrieve relevant parameters
double *center = this->Cylinder->GetCenter();
double *axis = this->Cylinder->GetAxis();
double radius = this->Cylinder->GetRadius();
int res = this->Resolution;
double d = this->Outline->GetOutput()->GetLength();
// We're gonna need a local coordinate system. Find a normal to the
// cylinder axis. Then use cross product to find a third orthogonal
// axis.
int i;
double n1[3], n2[3];
for (i=0; i<3; i++)
{
// a little trick to find an othogonal normal
if ( axis[i] != 0.0 )
{
n1[(i+2)%3] = 0.0;
n1[(i+1)%3] = 1.0;
n1[i] = -axis[(i+1)%3]/axis[i];
break;
}
}
vtkMath::Normalize(n1);
vtkMath::Cross(axis,n1,n2);
// Now create Resolution line segments. Initially the line segments
// are made a little long to extend outside of the bounding
// box. Later on we'll trim them to the bounding box.
pts->SetNumberOfPoints(2*res);
normals->SetNumberOfTuples(2*res);
vtkIdType pid;
double x[3], n[3], theta;
double v[3]; v[0] = d*axis[0]; v[1] = d*axis[1]; v[2] = d*axis[2];
for (pid=0; pid < res; ++pid)
{
theta = static_cast<double>(pid)/static_cast<double>(res) * 2.0*vtkMath::Pi();
for (i=0; i<3; ++i)
{
n[i] = n1[i]*cos(theta) + n2[i]*sin(theta);
x[i] = center[i] + radius*n[i] + v[i];
}
pts->SetPoint(pid,x);
normals->SetTuple(pid,n);
for (i=0; i<3; ++i)
{
x[i] = center[i] + radius*n[i] - v[i];
}
pts->SetPoint(res+pid,x);
normals->SetTuple(res+pid,n);
}
// Now trim the cylinder against the bounding box. Mark edges that do not
// intersect the bounding box.
bool edgeInside[VTK_MAX_CYL_RESOLUTION];
double x1[3], x2[3], p1[3], p2[3], t1, t2;
const double *bounds = this->Outline->GetOutput()->GetBounds();
int plane1, plane2;
for (pid=0; pid < res; ++pid)
{
pts->GetPoint(pid,x1);
pts->GetPoint(pid+res,x2);
if ( ! vtkBox::IntersectWithLine(bounds,x1,x2,t1,t2,p1,p2,plane1,plane2) )
{
edgeInside[pid] = false;
}
else
{
edgeInside[pid] = true;
pts->SetPoint(pid,p1);
pts->SetPoint(pid+res,p2);
}
}
// Create polygons around cylinder. Make sure the edges of the polygon
// are inside the widget's bounding box.
vtkIdType ptIds[4];
for (pid=0; pid < res; ++pid)
{
if ( edgeInside[pid] && edgeInside[(pid+1)%res] )
{
ptIds[0] = pid;
ptIds[3] = (pid + 1) % res;
ptIds[1] = ptIds[0] + res;
ptIds[2] = ptIds[3] + res;
polys->InsertNextCell(4,ptIds);
}
}
polys->Modified();
}
//----------------------------------------------------------------------
void vtkImplicitCylinderRepresentation::RegisterPickers()
{
vtkPickingManager* pm = this->GetPickingManager();
if (!pm)
{
return;
}
pm->AddPicker(this->Picker, this);
}
| 30.608584 | 93 | 0.601779 | [
"vector",
"transform"
] |
f6d57a0a1d90c7d2ad1edb654b264f8f90cbaf00 | 19,393 | cc | C++ | src/connectivity/bluetooth/core/bt-host/fidl/gatt2_remote_service_server.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-12-29T10:11:08.000Z | 2022-01-04T15:37:09.000Z | src/connectivity/bluetooth/core/bt-host/fidl/gatt2_remote_service_server.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | src/connectivity/bluetooth/core/bt-host/fidl/gatt2_remote_service_server.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gatt2_remote_service_server.h"
#include <measure_tape/hlcpp/hlcpp_measure_tape_for_read_by_type_result.h>
#include "src/connectivity/bluetooth/core/bt-host/att/att.h"
#include "src/connectivity/bluetooth/core/bt-host/common/identifier.h"
#include "src/connectivity/bluetooth/core/bt-host/fidl/helpers.h"
namespace fbg = fuchsia::bluetooth::gatt2;
namespace measure_fbg = measure_tape::fuchsia::bluetooth::gatt2;
namespace bthost {
namespace {
bt::att::StatusCallback MakeStatusCallback(
bt::PeerId peer_id, const char* request_name, fbg::Handle fidl_handle,
fit::function<void(fpromise::result<void, fbg::Error>)> callback) {
return
[peer_id, fidl_handle, callback = std::move(callback), request_name](bt::att::Status status) {
if (bt_is_error(status, INFO, "fidl", "%s: error (peer: %s, handle: 0x%lX)", request_name,
bt_str(peer_id), fidl_handle.value)) {
callback(fpromise::error(fidl_helpers::AttStatusToGattFidlError(status)));
return;
}
callback(fpromise::ok());
};
}
fbg::Characteristic CharacteristicToFidl(
const bt::gatt::CharacteristicData& characteristic,
const std::map<bt::gatt::DescriptorHandle, bt::gatt::DescriptorData>& descriptors) {
fbg::Characteristic fidl_char;
fidl_char.set_handle(fbg::Handle{characteristic.value_handle});
fidl_char.set_type(fuchsia::bluetooth::Uuid{characteristic.type.value()});
// The FIDL property bitfield combines the properties and extended properties bits.
// We mask away the kExtendedProperties property.
constexpr uint8_t kRemoveExtendedPropertiesMask = 0x7F;
uint16_t fidl_properties =
static_cast<uint16_t>(characteristic.properties & kRemoveExtendedPropertiesMask);
if (characteristic.extended_properties) {
if (*characteristic.extended_properties & bt::gatt::ExtendedProperty::kReliableWrite) {
fidl_properties |= static_cast<uint16_t>(fbg::CharacteristicPropertyBits::RELIABLE_WRITE);
}
if (*characteristic.extended_properties & bt::gatt::ExtendedProperty::kWritableAuxiliaries) {
fidl_properties |=
static_cast<uint16_t>(fbg::CharacteristicPropertyBits::WRITABLE_AUXILIARIES);
}
}
fidl_char.set_properties(static_cast<uint32_t>(fidl_properties));
if (!descriptors.empty()) {
std::vector<fbg::Descriptor> fidl_descriptors;
for (const auto& [handle, data] : descriptors) {
fbg::Descriptor fidl_descriptor;
fidl_descriptor.set_handle(fbg::Handle{handle.value});
fidl_descriptor.set_type(fuchsia::bluetooth::Uuid{data.type.value()});
fidl_descriptors.push_back(std::move(fidl_descriptor));
}
fidl_char.set_descriptors(std::move(fidl_descriptors));
}
return fidl_char;
}
// Returned result is supposed to match Read{Characteristic, Descriptor}Callback (result type is
// converted by FIDL move constructor).
[[nodiscard]] fpromise::result<::fuchsia::bluetooth::gatt2::ReadValue,
::fuchsia::bluetooth::gatt2::Error>
ReadResultToFidl(bt::PeerId peer_id, fbg::Handle handle, bt::att::Status status,
const bt::ByteBuffer& value, bool maybe_truncated, const char* request) {
if (bt_is_error(status, INFO, "fidl", "%s: error (peer: %s, handle: 0x%lX)", request,
bt_str(peer_id), handle.value)) {
return fpromise::error(fidl_helpers::AttStatusToGattFidlError(status));
}
fbg::ReadValue fidl_value;
fidl_value.set_handle(handle);
fidl_value.set_value(value.ToVector());
fidl_value.set_maybe_truncated(maybe_truncated);
return fpromise::ok(std::move(fidl_value));
}
void FillInReadOptionsDefaults(fbg::ReadOptions& options) {
if (options.is_short_read()) {
return;
}
if (!options.long_read().has_offset()) {
options.long_read().set_offset(0);
}
if (!options.long_read().has_max_bytes()) {
options.long_read().set_max_bytes(fbg::MAX_VALUE_LENGTH);
}
}
void FillInDefaultWriteOptions(fbg::WriteOptions& options) {
if (!options.has_write_mode()) {
*options.mutable_write_mode() = fbg::WriteMode::DEFAULT;
}
if (!options.has_offset()) {
*options.mutable_offset() = 0;
}
}
bt::gatt::ReliableMode ReliableModeFromFidl(const fbg::WriteMode& mode) {
return mode == fbg::WriteMode::RELIABLE ? bt::gatt::ReliableMode::kEnabled
: bt::gatt::ReliableMode::kDisabled;
}
} // namespace
Gatt2RemoteServiceServer::Gatt2RemoteServiceServer(
fbl::RefPtr<bt::gatt::RemoteService> service, fxl::WeakPtr<bt::gatt::GATT> gatt,
bt::PeerId peer_id, fidl::InterfaceRequest<fuchsia::bluetooth::gatt2::RemoteService> request)
: GattServerBase(gatt, this, std::move(request)),
service_(std::move(service)),
peer_id_(peer_id),
weak_ptr_factory_(this) {}
Gatt2RemoteServiceServer::~Gatt2RemoteServiceServer() {
// Disable all notifications to prevent leaks.
for (auto& [_, notifier] : characteristic_notifiers_) {
service_->DisableNotifications(notifier.characteristic_handle, notifier.handler_id,
/*status_callback=*/[](auto /*status*/) {});
}
characteristic_notifiers_.clear();
}
void Gatt2RemoteServiceServer::Close(zx_status_t status) { binding()->Close(status); }
void Gatt2RemoteServiceServer::DiscoverCharacteristics(DiscoverCharacteristicsCallback callback) {
auto res_cb = [callback = std::move(callback)](
bt::att::Status status, const bt::gatt::CharacteristicMap& characteristics) {
if (!status) {
callback({});
return;
}
std::vector<fbg::Characteristic> fidl_characteristics;
for (const auto& [_, characteristic] : characteristics) {
const auto& [data, descriptors] = characteristic;
fidl_characteristics.push_back(CharacteristicToFidl(data, descriptors));
}
callback(std::move(fidl_characteristics));
};
service_->DiscoverCharacteristics(std::move(res_cb));
}
void Gatt2RemoteServiceServer::ReadByType(::fuchsia::bluetooth::Uuid uuid,
ReadByTypeCallback callback) {
service_->ReadByType(
fidl_helpers::UuidFromFidl(uuid),
[self = weak_ptr_factory_.GetWeakPtr(), cb = std::move(callback), func = __FUNCTION__](
bt::att::Status status, std::vector<bt::gatt::RemoteService::ReadByTypeResult> results) {
if (!self) {
return;
}
switch (status.error()) {
case bt::HostError::kNoError:
break;
case bt::HostError::kInvalidParameters:
bt_log(WARN, "fidl", "%s: called with invalid parameters (peer: %s)", func,
bt_str(self->peer_id_));
cb(fpromise::error(fbg::Error::INVALID_PARAMETERS));
return;
default:
cb(fpromise::error(fbg::Error::UNLIKELY_ERROR));
return;
}
const size_t kVectorOverhead = sizeof(fidl_message_header_t) + sizeof(fidl_vector_t);
const size_t kMaxBytes = ZX_CHANNEL_MAX_MSG_BYTES - kVectorOverhead;
size_t bytes_used = 0;
std::vector<fuchsia::bluetooth::gatt2::ReadByTypeResult> fidl_results;
fidl_results.reserve(results.size());
for (const bt::gatt::RemoteService::ReadByTypeResult& result : results) {
fuchsia::bluetooth::gatt2::ReadByTypeResult fidl_result;
fidl_result.set_handle(fbg::Handle{result.handle.value});
if (result.result.is_ok()) {
fbg::ReadValue read_value;
read_value.set_handle(fbg::Handle{result.handle.value});
read_value.set_value(result.result.value()->ToVector());
read_value.set_maybe_truncated(result.maybe_truncated);
fidl_result.set_value(std::move(read_value));
} else {
fidl_result.set_error(
fidl_helpers::AttStatusToGattFidlError(bt::att::Status(result.result.error())));
}
measure_fbg::Size result_size = measure_fbg::Measure(fidl_result);
ZX_ASSERT(result_size.num_handles == 0);
bytes_used += result_size.num_bytes;
if (bytes_used > kMaxBytes) {
cb(fpromise::error(fuchsia::bluetooth::gatt2::Error::TOO_MANY_RESULTS));
return;
}
fidl_results.push_back(std::move(fidl_result));
}
cb(fpromise::ok(std::move(fidl_results)));
});
}
void Gatt2RemoteServiceServer::ReadCharacteristic(fbg::Handle fidl_handle, fbg::ReadOptions options,
ReadCharacteristicCallback callback) {
if (!fidl_helpers::IsFidlGattHandleValid(fidl_handle)) {
callback(fpromise::error(fbg::Error::INVALID_HANDLE));
return;
}
bt::gatt::CharacteristicHandle handle(static_cast<bt::att::Handle>(fidl_handle.value));
FillInReadOptionsDefaults(options);
const char* kRequestName = __FUNCTION__;
bt::gatt::RemoteService::ReadValueCallback read_cb =
[peer_id = peer_id_, fidl_handle, kRequestName, callback = std::move(callback)](
bt::att::Status status, const bt::ByteBuffer& value, bool maybe_truncated) {
callback(
ReadResultToFidl(peer_id, fidl_handle, status, value, maybe_truncated, kRequestName));
};
if (options.is_short_read()) {
service_->ReadCharacteristic(handle, std::move(read_cb));
return;
}
service_->ReadLongCharacteristic(handle, options.long_read().offset(),
options.long_read().max_bytes(), std::move(read_cb));
}
void Gatt2RemoteServiceServer::WriteCharacteristic(fbg::Handle fidl_handle,
std::vector<uint8_t> value,
fbg::WriteOptions options,
WriteCharacteristicCallback callback) {
if (!fidl_helpers::IsFidlGattHandleValid(fidl_handle)) {
callback(fpromise::error(fbg::Error::INVALID_HANDLE));
return;
}
bt::gatt::CharacteristicHandle handle(static_cast<bt::att::Handle>(fidl_handle.value));
FillInDefaultWriteOptions(options);
bt::att::StatusCallback write_cb =
MakeStatusCallback(peer_id_, __FUNCTION__, fidl_handle, std::move(callback));
if (options.write_mode() == fbg::WriteMode::WITHOUT_RESPONSE) {
if (options.offset() != 0) {
write_cb(bt::att::Status(bt::HostError::kInvalidParameters));
return;
}
service_->WriteCharacteristicWithoutResponse(handle, std::move(value), std::move(write_cb));
return;
}
const uint16_t kMaxShortWriteValueLength =
service_->att_mtu() - sizeof(bt::att::OpCode) - sizeof(bt::att::WriteRequestParams);
if (options.offset() == 0 && options.write_mode() == fbg::WriteMode::DEFAULT &&
value.size() <= kMaxShortWriteValueLength) {
service_->WriteCharacteristic(handle, std::move(value), std::move(write_cb));
return;
}
service_->WriteLongCharacteristic(handle, options.offset(), std::move(value),
ReliableModeFromFidl(options.write_mode()),
std::move(write_cb));
}
void Gatt2RemoteServiceServer::ReadDescriptor(::fuchsia::bluetooth::gatt2::Handle fidl_handle,
::fuchsia::bluetooth::gatt2::ReadOptions options,
ReadDescriptorCallback callback) {
if (!fidl_helpers::IsFidlGattHandleValid(fidl_handle)) {
callback(fpromise::error(fbg::Error::INVALID_HANDLE));
return;
}
bt::gatt::DescriptorHandle handle(static_cast<bt::att::Handle>(fidl_handle.value));
FillInReadOptionsDefaults(options);
const char* kRequestName = __FUNCTION__;
bt::gatt::RemoteService::ReadValueCallback read_cb =
[peer_id = peer_id_, fidl_handle, kRequestName, callback = std::move(callback)](
bt::att::Status status, const bt::ByteBuffer& value, bool maybe_truncated) {
callback(
ReadResultToFidl(peer_id, fidl_handle, status, value, maybe_truncated, kRequestName));
};
if (options.is_short_read()) {
service_->ReadDescriptor(handle, std::move(read_cb));
return;
}
service_->ReadLongDescriptor(handle, options.long_read().offset(),
options.long_read().max_bytes(), std::move(read_cb));
}
void Gatt2RemoteServiceServer::WriteDescriptor(fbg::Handle fidl_handle, std::vector<uint8_t> value,
fbg::WriteOptions options,
WriteDescriptorCallback callback) {
if (!fidl_helpers::IsFidlGattHandleValid(fidl_handle)) {
callback(fpromise::error(fbg::Error::INVALID_HANDLE));
return;
}
bt::gatt::DescriptorHandle handle(static_cast<bt::att::Handle>(fidl_handle.value));
FillInDefaultWriteOptions(options);
bt::att::StatusCallback write_cb =
MakeStatusCallback(peer_id_, __FUNCTION__, fidl_handle, std::move(callback));
// WITHOUT_RESPONSE and RELIABLE write modes are not supported for descriptors.
if (options.write_mode() == fbg::WriteMode::WITHOUT_RESPONSE ||
options.write_mode() == fbg::WriteMode::RELIABLE) {
write_cb(bt::att::Status(bt::HostError::kInvalidParameters));
return;
}
const uint16_t kMaxShortWriteValueLength =
service_->att_mtu() - sizeof(bt::att::OpCode) - sizeof(bt::att::WriteRequestParams);
if (options.offset() == 0 && value.size() <= kMaxShortWriteValueLength) {
service_->WriteDescriptor(handle, std::move(value), std::move(write_cb));
return;
}
service_->WriteLongDescriptor(handle, options.offset(), std::move(value), std::move(write_cb));
}
void Gatt2RemoteServiceServer::RegisterCharacteristicNotifier(
fbg::Handle fidl_handle, fidl::InterfaceHandle<fbg::CharacteristicNotifier> notifier_handle,
RegisterCharacteristicNotifierCallback callback) {
bt::gatt::CharacteristicHandle char_handle(static_cast<bt::att::Handle>(fidl_handle.value));
NotifierId notifier_id = next_notifier_id_++;
auto self = weak_ptr_factory_.GetWeakPtr();
auto value_cb = [self, notifier_id, fidl_handle](const bt::ByteBuffer& value,
bool maybe_truncated) {
if (!self) {
return;
}
auto notifier_iter = self->characteristic_notifiers_.find(notifier_id);
// The lower layers guarantee that the status callback is always invoked before sending
// notifications. Notifiers are only removed during destruction (addressed by previous `self`
// check) and in the `DisableNotifications` completion callback in
// `OnCharacteristicNotifierError`, so no notifications should be received after removing a
// notifier.
ZX_ASSERT_MSG(notifier_iter != self->characteristic_notifiers_.end(),
"characteristic notification value received after notifier unregistered"
"(peer: %s, characteristic: 0x%lX) ",
bt_str(self->peer_id_), fidl_handle.value);
CharacteristicNotifier& notifier = notifier_iter->second;
// The `- 1` is needed because there is one unacked notification that we've already sent to the
// client aside from the values in the queue.
if (notifier.queued_values.size() == kMaxPendingNotifierValues - 1) {
bt_log(WARN, "fidl",
"GATT CharacteristicNotifier pending values limit reached, closing protocol (peer: "
"%s, characteristic: %#.2x)",
bt_str(self->peer_id_), notifier.characteristic_handle.value);
self->OnCharacteristicNotifierError(notifier_id, notifier.characteristic_handle,
notifier.handler_id);
return;
}
fbg::ReadValue fidl_value;
fidl_value.set_handle(fidl_handle);
fidl_value.set_value(value.ToVector());
fidl_value.set_maybe_truncated(maybe_truncated);
bt_log(TRACE, "fidl", "Queueing GATT notification value (characteristic: %#.2x)",
notifier.characteristic_handle.value);
notifier.queued_values.push(std::move(fidl_value));
self->MaybeNotifyNextValue(notifier_id);
};
auto status_cb = [self, service = service_, char_handle, notifier_id,
notifier_handle = std::move(notifier_handle), callback = std::move(callback)](
bt::att::Status status, bt::gatt::IdType handler_id) mutable {
if (!self) {
if (status) {
// Disable this handler so it doesn't leak.
service->DisableNotifications(char_handle, handler_id, [](auto /*status*/) {
// There is no notifier to clean up because the server has been destroyed.
});
}
return;
}
if (!status.is_success()) {
callback(fpromise::error(fidl_helpers::AttStatusToGattFidlError(status)));
return;
}
CharacteristicNotifier notifier{.handler_id = handler_id,
.characteristic_handle = char_handle,
.notifier = notifier_handle.Bind()};
auto [notifier_iter, emplaced] =
self->characteristic_notifiers_.emplace(notifier_id, std::move(notifier));
ZX_ASSERT(emplaced);
// When the client closes the protocol, unregister the notifier.
notifier_iter->second.notifier.set_error_handler(
[self, char_handle, handler_id, notifier_id](auto /*status*/) {
self->OnCharacteristicNotifierError(notifier_id, char_handle, handler_id);
});
callback(fpromise::ok());
};
service_->EnableNotifications(char_handle, std::move(value_cb), std::move(status_cb));
}
void Gatt2RemoteServiceServer::MaybeNotifyNextValue(NotifierId notifier_id) {
auto notifier_iter = characteristic_notifiers_.find(notifier_id);
if (notifier_iter == characteristic_notifiers_.end()) {
return;
}
CharacteristicNotifier& notifier = notifier_iter->second;
if (notifier.queued_values.empty()) {
return;
}
if (!notifier.last_value_ack) {
return;
}
notifier.last_value_ack = false;
fbg::ReadValue value = std::move(notifier.queued_values.front());
notifier.queued_values.pop();
bt_log(DEBUG, "fidl", "Sending GATT notification value (handle: 0x%lX)", value.handle().value);
auto self = weak_ptr_factory_.GetWeakPtr();
notifier.notifier->OnNotification(std::move(value), [self, notifier_id]() {
if (!self) {
return;
}
auto notifier_iter = self->characteristic_notifiers_.find(notifier_id);
if (notifier_iter == self->characteristic_notifiers_.end()) {
return;
}
notifier_iter->second.last_value_ack = true;
self->MaybeNotifyNextValue(notifier_id);
});
}
void Gatt2RemoteServiceServer::OnCharacteristicNotifierError(
NotifierId notifier_id, bt::gatt::CharacteristicHandle char_handle,
bt::gatt::IdType handler_id) {
auto self = weak_ptr_factory_.GetWeakPtr();
service_->DisableNotifications(char_handle, handler_id, [self, notifier_id](auto /*status*/) {
if (!self) {
return;
}
// Clear the notifier regardless of status. Wait until this callback is called in order to
// prevent the value callback from being called for an erased notifier.
self->characteristic_notifiers_.erase(notifier_id);
});
}
} // namespace bthost
| 40.913502 | 100 | 0.676069 | [
"vector"
] |
f6d96c02857bd2f88fd76543708083d857f5da8b | 23,059 | cpp | C++ | inetcore/setup/active/basectl/ctlview.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/setup/active/basectl/ctlview.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/setup/active/basectl/ctlview.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //=--------------------------------------------------------------------------=
// CtlView.Cpp
//=--------------------------------------------------------------------------=
// Copyright 1995-1996 Microsoft Corporation. All Rights Reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//=--------------------------------------------------------------------------=
//
// implementation of the IViewObjectEx interface, which is a moderately
// non-trivial bunch of code.
//
#include "IPServer.H"
#include "CtrlObj.H"
#include "Globals.H"
#include "Util.H"
// for ASSERT and FAIL
//
SZTHISFILE
// local functions we're going to find useful
//
HDC _CreateOleDC(DVTARGETDEVICE *ptd);
//=--------------------------------------------------------------------------=
// COleControl::Draw [IViewObject2]
//=--------------------------------------------------------------------------=
// Draws a representation of an object onto the specified device context.
//
// Parameters:
// DWORD - [in] draw aspect
// LONG - [in] part of object to draw [not relevant]
// void * - NULL
// DVTARGETDEVICE * - [in] specifies the target device
// HDC - [in] information context for target device
// HDC - [in] target device context
// LPCRECTL - [in] rectangle in which the object is drawn
// LPCRECTL - [in] window extent and origin for metafiles
// BOOL (*)(DWORD) - [in] callback for continuing or cancelling drawing
// DWORD - [in] parameter to pass to callback.
//
// Output:
// HRESULT
//
// Notes:
// - we support the following OCX 96 extensions
// a. flicker free drawing [multi-pass drawing]
// b. pvAspect != NULL for optimized DC handling
// c. prcBounds == NULL for windowless inplace active objects
//
STDMETHODIMP COleControl::Draw
(
DWORD dwDrawAspect,
LONG lIndex,
void *pvAspect,
DVTARGETDEVICE *ptd,
HDC hicTargetDevice,
HDC hdcDraw,
LPCRECTL prcBounds,
LPCRECTL prcWBounds,
BOOL (__stdcall *pfnContinue)(ULONG_PTR dwContinue),
ULONG_PTR dwContinue
)
{
HRESULT hr;
RECTL rc;
POINT pVp, pW;
BOOL fOptimize = FALSE;
int iMode;
BYTE fMetafile = FALSE;
BYTE fDeleteDC = FALSE;
// support the aspects required for multi-pass drawing
//
switch (dwDrawAspect) {
case DVASPECT_CONTENT:
case DVASPECT_OPAQUE:
case DVASPECT_TRANSPARENT:
break;
default:
return DV_E_DVASPECT;
}
// first, have to do a little bit to support printing.
//
if (GetDeviceCaps(hdcDraw, TECHNOLOGY) == DT_METAFILE) {
// We are dealing with a metafile.
//
fMetafile = TRUE;
// If attributes DC is NULL, create one, based on ptd.
//
if (!hicTargetDevice) {
// Does _CreateOleDC have to return an hDC
// or can it be flagged to return an hIC
// for this particular case?
//
hicTargetDevice = _CreateOleDC(ptd);
fDeleteDC = TRUE;
}
}
// check to see if we have any flags passed in the pvAspect parameter.
//
if (pvAspect && ((DVASPECTINFO *)pvAspect)->cb == sizeof(DVASPECTINFO))
fOptimize = (((DVASPECTINFO *)pvAspect)->dwFlags & DVASPECTINFOFLAG_CANOPTIMIZE) ? TRUE : FALSE;
// if we are windowless, then we just pass this on to the end control code.
//
if (m_fInPlaceActive) {
// give them a rectangle with which to draw
//
//ASSERT(!m_fInPlaceActive || !prcBounds, "Inplace active and somebody passed in prcBounds!!!");
if (prcBounds)
memcpy(&rc, prcBounds, sizeof(rc));
else
memcpy(&rc, &m_rcLocation, sizeof(rc));
} else {
// first -- convert the DC back to MM_TEXT mapping mode so that the
// window proc and OnDraw can share the same painting code. save
// some information on it, so we can restore it later [without using
// a SaveDC/RestoreDC]
//
rc = *prcBounds;
// Don't do anything to hdcDraw if it's a metafile.
// The control's Draw method must make the appropriate
// accomodations for drawing to a metafile
//
if (!fMetafile) {
LPtoDP(hdcDraw, (POINT *)&rc, 2);
SetViewportOrgEx(hdcDraw, 0, 0, &pVp);
SetWindowOrgEx(hdcDraw, 0, 0, &pW);
iMode = SetMapMode(hdcDraw, MM_TEXT);
}
}
// prcWBounds is NULL and not used if we are not dealing with a metafile.
// For metafiles, we pass on rc as *prcBounds, we should also include
// prcWBounds
//
hr = OnDraw(dwDrawAspect, hdcDraw, &rc, prcWBounds, hicTargetDevice, fOptimize);
// clean up the DC when we're done with it, if appropriate.
//
if (!m_fInPlaceActive) {
SetViewportOrgEx(hdcDraw, pVp.x, pVp.y, NULL);
SetWindowOrgEx(hdcDraw, pW.x, pW.y, NULL);
SetMapMode(hdcDraw, iMode);
}
// if we created a dc, blow it away now
//
if (fDeleteDC) DeleteDC(hicTargetDevice);
return hr;
}
//=--------------------------------------------------------------------------=
// COleControl::DoSuperClassPaint
//=--------------------------------------------------------------------------=
// design time painting of a subclassed control.
//
// Parameters:
// HDC - [in] dc to work with
// LPCRECTL - [in] rectangle to paint to. should be in pixels
//
// Output:
// HRESULT
//
// Notes:
//
HRESULT COleControl::DoSuperClassPaint
(
HDC hdc,
LPCRECTL prcBounds
)
{
HWND hwnd;
RECT rcClient;
int iMapMode;
POINT ptWOrg, ptVOrg;
SIZE sWOrg, sVOrg;
// make sure we have a window.
//
hwnd = CreateInPlaceWindow(0,0, FALSE);
if (!hwnd)
return E_FAIL;
GetClientRect(hwnd, &rcClient);
// set up the DC for painting. this code largely taken from the MFC CDK
// DoSuperClassPaint() fn. doesn't always get things like command
// buttons quite right ...
//
// NOTE: there is a windows 95 problem in which the font instance manager
// will leak a bunch of bytes in the global GDI pool whenever you
// change your extents and have an active font. this code gets around
// this for on-screen cases, but not for printing [which shouldn't be
// too serious, because you're not often changing your control size and
// printing rapidly in succession]
//
if ((rcClient.right - rcClient.left != prcBounds->right - prcBounds->left)
&& (rcClient.bottom - rcClient.top != prcBounds->bottom - prcBounds->top)) {
iMapMode = SetMapMode(hdc, MM_ANISOTROPIC);
SetWindowExtEx(hdc, rcClient.right, rcClient.bottom, &sWOrg);
SetViewportExtEx(hdc, prcBounds->right - prcBounds->left, prcBounds->bottom - prcBounds->top, &sVOrg);
}
SetWindowOrgEx(hdc, 0, 0, &ptWOrg);
SetViewportOrgEx(hdc, prcBounds->left, prcBounds->top, &ptVOrg);
#if STRICT
CallWindowProc((WNDPROC)SUBCLASSWNDPROCOFCONTROL(m_ObjectType), hwnd, (g_fSysWin95Shell) ? WM_PRINT : WM_PAINT, (WPARAM)hdc, (LPARAM)(g_fSysWin95Shell ? PRF_CHILDREN | PRF_CLIENT : 0));
#else
CallWindowProc((FARPROC)SUBCLASSWNDPROCOFCONTROL(m_ObjectType), hwnd, (g_fSysWin95Shell) ? WM_PRINT : WM_PAINT, (WPARAM)hdc, (LPARAM)(g_fSysWin95Shell ? PRF_CHILDREN | PRF_CLIENT : 0));
#endif // STRICT
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::GetColorSet [IViewObject2]
//=--------------------------------------------------------------------------=
// Returns the logical palette that the control will use for drawing in its
// IViewObject::Draw method with the corresponding parameters.
//
// Parameters:
// DWORD - [in] how the object is to be represented
// LONG - [in] part of the object to draw [not relevant]
// void * - NULL
// DVTARGETDEVICE * - [in] specifies the target device
// HDC - [in] information context for the target device
// LOGPALETTE ** - [out] where to put palette
//
// Output:
// S_OK - Control has a palette, and returned it through the out param.
// S_FALSE - Control does not currently have a palette.
// E_NOTIMPL - Control will never have a palette so optimize handling of this control.
//
// Notes:
//
STDMETHODIMP COleControl::GetColorSet
(
DWORD dwDrawAspect,
LONG lindex,
void *IgnoreMe,
DVTARGETDEVICE *ptd,
HDC hicTargetDevice,
LOGPALETTE **ppColorSet
)
{
if (dwDrawAspect != DVASPECT_CONTENT)
return DV_E_DVASPECT;
*ppColorSet = NULL;
return (OnGetPalette(hicTargetDevice, ppColorSet)) ? ((*ppColorSet) ? S_OK : S_FALSE) : E_NOTIMPL;
}
//=--------------------------------------------------------------------------=
// COleControl::Freeze [IViewObject2]
//=--------------------------------------------------------------------------=
// Freezes a certain aspect of the object's presentation so that it does not
// change until the IViewObject::Unfreeze method is called.
//
// Parameters:
// DWORD - [in] aspect
// LONG - [in] part of object to draw
// void * - NULL
// DWORD * - [out] for Unfreeze
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::Freeze
(
DWORD dwDrawAspect,
LONG lIndex,
void *IgnoreMe,
DWORD *pdwFreeze
)
{
return E_NOTIMPL;
}
//=--------------------------------------------------------------------------=
// COleControl::Unfreeze [IVewObject2]
//=--------------------------------------------------------------------------=
// Releases a previously frozen drawing. The most common use of this method
// is for banded printing.
//
// Parameters:
// DWORD - [in] cookie from freeze
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::Unfreeze
(
DWORD dwFreeze
)
{
return E_NOTIMPL;
}
//=--------------------------------------------------------------------------=
// COleControl::SetAdvise [IViewObject2]
//=--------------------------------------------------------------------------=
// Sets up a connection between the control and an advise sink so that the
// advise sink can be notified about changes in the control's view.
//
// Parameters:
// DWORD - [in] aspect
// DWORD - [in] info about the sink
// IAdviseSink * - [in] the sink
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::SetAdvise
(
DWORD dwAspects,
DWORD dwAdviseFlags,
IAdviseSink *pAdviseSink
)
{
// if it's not a content aspect, we don't support it.
//
if (!(dwAspects & DVASPECT_CONTENT)) {
return DV_E_DVASPECT;
}
// set up some flags [we gotta stash for GetAdvise ...]
//
m_fViewAdvisePrimeFirst = (dwAdviseFlags & ADVF_PRIMEFIRST) ? TRUE : FALSE;
m_fViewAdviseOnlyOnce = (dwAdviseFlags & ADVF_ONLYONCE) ? TRUE : FALSE;
RELEASE_OBJECT(m_pViewAdviseSink);
m_pViewAdviseSink = pAdviseSink;
ADDREF_OBJECT(m_pViewAdviseSink);
// prime them if they want it [we need to store this so they can get flags later]
//
if (m_fViewAdvisePrimeFirst)
ViewChanged();
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::GetAdvise [IViewObject2]
//=--------------------------------------------------------------------------=
// Retrieves the existing advisory connection on the control if there is one.
// This method simply returns the parameters used in the most recent call to
// the IViewObject::SetAdvise method.
//
// Parameters:
// DWORD * - [out] aspects
// DWORD * - [out] advise flags
// IAdviseSink ** - [out] the sink
//
// Output:
// HRESULT
//
// Notes;
//
STDMETHODIMP COleControl::GetAdvise
(
DWORD *pdwAspects,
DWORD *pdwAdviseFlags,
IAdviseSink **ppAdviseSink
)
{
// if they want it, give it to them
//
if (pdwAspects)
*pdwAspects = DVASPECT_CONTENT;
if (pdwAdviseFlags) {
*pdwAdviseFlags = 0;
if (m_fViewAdviseOnlyOnce) *pdwAdviseFlags |= ADVF_ONLYONCE;
if (m_fViewAdvisePrimeFirst) *pdwAdviseFlags |= ADVF_PRIMEFIRST;
}
if (ppAdviseSink) {
*ppAdviseSink = m_pViewAdviseSink;
ADDREF_OBJECT(*ppAdviseSink);
}
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::GetExtent [IViewObject2]
//=--------------------------------------------------------------------------=
// Returns the size that the control will be drawn on the
// specified target device.
//
// Parameters:
// DWORD - [in] draw aspect
// LONG - [in] part of object to draw
// DVTARGETDEVICE * - [in] information about target device
// LPSIZEL - [out] where to put the size
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::GetExtent
(
DWORD dwDrawAspect,
LONG lindex,
DVTARGETDEVICE *ptd,
LPSIZEL psizel
)
{
// we already have an implementation of this [from IOleObject]
//
return GetExtent(dwDrawAspect, psizel);
}
//=--------------------------------------------------------------------------=
// COleControl::OnGetPalette [overridable]
//=--------------------------------------------------------------------------=
// called when the host wants palette information. ideally, people should use
// this sparingly and carefully.
//
// Parameters:
// HDC - [in] HIC for the target device
// LOGPALETTE ** - [out] where to put the palette
//
// Output:
// BOOL - TRUE means we processed it, false means nope.
//
// Notes:
//
BOOL COleControl::OnGetPalette
(
HDC hicTargetDevice,
LOGPALETTE **ppColorSet
)
{
return FALSE;
}
//=--------------------------------------------------------------------------=
// COleControl::GetRect [IViewObjectEx]
//=--------------------------------------------------------------------------=
// returns a rectnagle describing a given drawing aspect
//
// Parameters:
// DWORD - [in] aspect
// LPRECTL - [out] region rectangle
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::GetRect
(
DWORD dvAspect,
LPRECTL prcRect
)
{
RECTL rc;
BOOL f;
// call the user routine and let them return the size
//
f = OnGetRect(dvAspect, &rc);
if (!f) return DV_E_DVASPECT;
// transform these dudes.
//
PixelToHiMetric((LPSIZEL)&rc, (LPSIZEL)prcRect);
PixelToHiMetric((LPSIZEL)((LPBYTE)&rc + sizeof(SIZEL)), (LPSIZEL)((LPBYTE)prcRect + sizeof(SIZEL)));
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::GetViewStatus [IViewObjectEx]
//=--------------------------------------------------------------------------=
// returns information about the opactiy of the object and what drawing
// aspects are supported
//
// Parameters:
// DWORD * - [out] the status
//
/// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::GetViewStatus
(
DWORD *pdwStatus
)
{
// depending on the flag in the CONTROLOBJECTINFO structure, indicate our
// transparency vs opacity.
// OVERRIDE: controls that wish to support multi-pass drawing should
// override this routine and return, in addition to the flags indication
// opacity, flags indicating what sort of drawing aspects they support.
//
*pdwStatus = FCONTROLISOPAQUE(m_ObjectType) ? VIEWSTATUS_OPAQUE : 0;
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::QueryHitPoint [IViewObjectEx]
//=--------------------------------------------------------------------------=
// indicates whether a point is within a given aspect of an object.
//
// Parameters:
// DWORD - [in] aspect
// LPCRECT - [in] Bounds rectangle
// POINT - [in] hit location client coordinates
// LONG - [in] what the container considers close
// DWORD * - [out] info about the hit
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::QueryHitPoint
(
DWORD dvAspect,
LPCRECT prcBounds,
POINT ptLocation,
LONG lCloseHint,
DWORD *pdwHitResult
)
{
// OVERRIDE: override me if you want to provide additional [non-opaque]
// functionality
//
if (dvAspect != DVASPECT_CONTENT)
return DV_E_DVASPECT;
*pdwHitResult = PtInRect(prcBounds, ptLocation) ? HITRESULT_HIT : HITRESULT_OUTSIDE;
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::QueryHitRect [IViewObjectEx]
//=--------------------------------------------------------------------------=
// indicates wheter any point in a rectangle is within a given drawing aspect
// of an object.
//
// Parameters:
// DWORD - [in] aspect
// LPCRECT - [in] bounds
// LPCRECT - [in] location
// LONG - [in] what host considers close
// DWORD * - [out] hit result
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::QueryHitRect
(
DWORD dvAspect,
LPCRECT prcBounds,
LPCRECT prcLocation,
LONG lCloseHint,
DWORD *pdwHitResult
)
{
RECT rc;
// OVERRIDE: override this for additional behaviour
//
if (dvAspect != DVASPECT_CONTENT)
return DV_E_DVASPECT;
*pdwHitResult = IntersectRect(&rc, prcBounds, prcLocation) ? HITRESULT_HIT : HITRESULT_OUTSIDE;
return S_OK;
}
//=--------------------------------------------------------------------------=
// COleControl::GetNaturalExtent [IViewObjectEx]
//=--------------------------------------------------------------------------=
// supports two types of control sizing, content and integral.
//
// Parameters:
// DWORD - [in] aspect
// LONG - [in] index
// DVTARGETDEVICE * - [in] target device information
// HDC - [in] HIC
// DVEXTENTINFO * - [in] sizing data
// LPSIZEL - [out] sizing data retunred by control
//
// Output:
// HRESULT
//
// Notes:
//
STDMETHODIMP COleControl::GetNaturalExtent
(
DWORD dvAspect,
LONG lIndex,
DVTARGETDEVICE *ptd,
HDC hicTargetDevice,
DVEXTENTINFO *pExtentInfo,
LPSIZEL pSizel
)
{
return E_NOTIMPL;
}
//=--------------------------------------------------------------------------=
// COleControl::OnGetRect [overridable
//=--------------------------------------------------------------------------=
// returns our rectangle
//
// Parameters:
// DWORD - [in] aspect they want the rect for
// RECTL * - [out] the rectangle that matches this aspect
//
// Output:
// BOOL - false means we don't like the aspect
//
// Notes:
//
BOOL COleControl::OnGetRect
(
DWORD dvAspect,
RECTL *pRect
)
{
// by default, we only support content drawing.
//
if (dvAspect != DVASPECT_CONTENT)
return FALSE;
// just give them our bounding rectangle
//
*((LPRECT)pRect) = m_rcLocation;
return TRUE;
}
//=--------------------------------------------------------------------------=
// _CreateOleDC
//=--------------------------------------------------------------------------=
// creates an HDC given a DVTARGETDEVICE structure.
//
// Parameters:
// DVTARGETDEVICE * - [in] duh.
//
// Output:
// HDC
//
// Notes:
//
HDC _CreateOleDC
(
DVTARGETDEVICE *ptd
)
{
LPDEVMODEW pDevModeW;
DEVMODEA DevModeA, *pDevModeA;
LPOLESTR lpwszDriverName;
LPOLESTR lpwszDeviceName;
LPOLESTR lpwszPortName;
HDC hdc;
// return screen DC for NULL target device
//
if (!ptd)
return CreateDC("DISPLAY", NULL, NULL, NULL);
if (ptd->tdExtDevmodeOffset == 0)
pDevModeW = NULL;
else
pDevModeW = (LPDEVMODEW)((LPSTR)ptd + ptd->tdExtDevmodeOffset);
lpwszDriverName = (LPOLESTR)((BYTE*)ptd + ptd->tdDriverNameOffset);
lpwszDeviceName = (LPOLESTR)((BYTE*)ptd + ptd->tdDeviceNameOffset);
lpwszPortName = (LPOLESTR)((BYTE*)ptd + ptd->tdPortNameOffset);
MAKE_ANSIPTR_FROMWIDE(pszDriverName, lpwszDriverName);
MAKE_ANSIPTR_FROMWIDE(pszDeviceName, lpwszDeviceName);
MAKE_ANSIPTR_FROMWIDE(pszPortName, lpwszPortName);
if (pDevModeW) {
WideCharToMultiByte(CP_ACP, 0, pDevModeW->dmDeviceName, -1, (LPSTR)DevModeA.dmDeviceName, CCHDEVICENAME, NULL, NULL);
memcpy(&DevModeA.dmSpecVersion, &pDevModeW->dmSpecVersion,
offsetof(DEVMODEA, dmFormName) - offsetof(DEVMODEA, dmSpecVersion));
WideCharToMultiByte(CP_ACP, 0, pDevModeW->dmFormName, -1, (LPSTR)DevModeA.dmFormName, CCHFORMNAME, NULL, NULL);
memcpy(&DevModeA.dmLogPixels, &pDevModeW->dmLogPixels, sizeof(DEVMODEA) - offsetof(DEVMODEA, dmLogPixels));
if (pDevModeW->dmDriverExtra) {
pDevModeA = (DEVMODEA *)HeapAlloc(g_hHeap, 0, sizeof(DEVMODEA) + pDevModeW->dmDriverExtra);
if (!pDevModeA) return NULL;
memcpy(pDevModeA, &DevModeA, sizeof(DEVMODEA));
memcpy(pDevModeA + 1, pDevModeW + 1, pDevModeW->dmDriverExtra);
} else
pDevModeA = &DevModeA;
DevModeA.dmSize = sizeof(DEVMODEA);
} else
pDevModeA = NULL;
hdc = CreateDC(pszDriverName, pszDeviceName, pszPortName, pDevModeA);
if (pDevModeA != &DevModeA) HeapFree(g_hHeap, 0, pDevModeA);
return hdc;
}
| 31.45839 | 190 | 0.528601 | [
"object",
"transform"
] |
f6db1584eade311e9898e67f755b8f59f651dee1 | 3,942 | cxx | C++ | test/test75.cxx | JadeMatrix/libpqxx | fa86ce2103f96cb2a89c381b8075e419dc6ac00b | [
"BSD-3-Clause"
] | null | null | null | test/test75.cxx | JadeMatrix/libpqxx | fa86ce2103f96cb2a89c381b8075e419dc6ac00b | [
"BSD-3-Clause"
] | null | null | null | test/test75.cxx | JadeMatrix/libpqxx | fa86ce2103f96cb2a89c381b8075e419dc6ac00b | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <vector>
#include "test_helpers.hxx"
using namespace std;
using namespace pqxx;
// Test program for libpqxx. Compare const_reverse_iterator iteration of a
// result to a regular, const_iterator iteration.
namespace
{
void test_075()
{
connection conn;
work tx{conn};
test::create_pqxxevents(tx);
const result R( tx.exec("SELECT year FROM pqxxevents") );
PQXX_CHECK(not R.empty(), "No events found, cannot test.");
PQXX_CHECK_EQUAL(R[0], R.at(0), "Inconsistent result indexing.");
PQXX_CHECK(not (R[0] != R.at(0)), "result::row::operator!=() is broken.");
PQXX_CHECK_EQUAL(R[0][0], R[0].at(0), "Inconsistent row indexing.");
PQXX_CHECK(
not (R[0][0] != R[0].at(0)),
"result::field::operator!=() is broken.");
vector<string> contents;
for (const auto &i: R) contents.push_back(i.at(0).as<string>());
cout << to_string(contents.size()) << " years read" << endl;
PQXX_CHECK_EQUAL(
contents.size(),
vector<string>::size_type(R.size()),
"Number of values does not match result size.");
for (result::size_type i=0; i<R.size(); ++i)
PQXX_CHECK_EQUAL(
contents[i],
R.at(i).at(0).c_str(),
"Inconsistent iteration.");
cout << to_string(R.size()) << " years checked" << endl;
// Thorough test for result::const_reverse_iterator
result::const_reverse_iterator ri1(R.rbegin()), ri2(ri1), ri3(R.end());
ri2 = R.rbegin();
PQXX_CHECK(ri2 == ri1, "reverse_iterator copy constructor is broken.");
PQXX_CHECK(ri3 == ri2, "result::end() does not generate rbegin().");
PQXX_CHECK_EQUAL(
ri2 - ri3,
0,
"const_reverse_iterator is at nonzero distance from its own copy.");
PQXX_CHECK(ri2 == ri3 + 0, "reverse_iterator+0 gives strange result.");
PQXX_CHECK(ri2 == ri3 - 0, "reverse_iterator-0 gives strange result.");
PQXX_CHECK(not (ri3 < ri2), "operator<() breaks on equal reverse_iterators.");
PQXX_CHECK(ri2 <= ri3, "operator<=() breaks on equal reverse_iterators.");
PQXX_CHECK(ri3++ == ri2, "reverse_iterator post-increment is broken.");
PQXX_CHECK_EQUAL(ri3 - ri2, 1, "Wrong nonzero reverse_iterator distance.");
PQXX_CHECK(ri3 > ri2, "reverse_iterator operator>() is broken.");
PQXX_CHECK(ri3 >= ri2, "reverse_iterator operator>=() is broken.");
PQXX_CHECK(ri2 < ri3, "reverse_iterator operator<() is broken.");
PQXX_CHECK(ri2 <= ri3, "reverse_iterator operator<=() is broken.");
PQXX_CHECK(ri3 == ri2 + 1, "Adding int to reverse_iterator is broken.");
PQXX_CHECK(
ri2 == ri3 - 1,
"Subtracting int from reverse_iterator is broken.");
PQXX_CHECK(ri3 == ++ri2, "reverse_iterator pre-increment is broken.");
PQXX_CHECK(ri3 >= ri2, "operator>=() breaks on equal reverse_iterators.");
PQXX_CHECK(ri3 >= ri2, "operator<=() breaks on equal reverse_iterators.");
PQXX_CHECK(
ri3.base() == R.back(),
"reverse_iterator does not arrive at back().");
PQXX_CHECK(
ri1->at(0) == (*ri1).at(0),
"reverse_iterator operator->() is inconsistent with operator*().");
PQXX_CHECK(ri2-- == ri3, "reverse_iterator post-decrement is broken.");
PQXX_CHECK(ri2 == --ri3, "reverse_iterator pre-decrement is broken.");
PQXX_CHECK(ri2 == R.rbegin(), "reverse_iterator decrement is broken.");
ri2 += 1;
ri3 -= -1;
PQXX_CHECK(ri2 != R.rbegin(), "Adding to reverse_iterator does not work.");
PQXX_CHECK(
ri3 == ri2,
"reverse_iterator operator-=() breaks on negative distances.");
ri2 -= 1;
PQXX_CHECK(
ri2 == R.rbegin(),
"reverse_iterator operator+=() and operator-=() do not cancel out.");
// Now verify that reverse iterator also sees the same results...
auto l = contents.rbegin();
for (auto i = R.rbegin(); i != R.rend(); ++i, ++l)
PQXX_CHECK_EQUAL(
*l,
i->at(0).c_str(),
"Inconsistent reverse iteration.");
PQXX_CHECK(l == contents.rend(), "Reverse iteration ended too soon.");
PQXX_CHECK(not R.empty(), "No events found in table, cannot test.");
}
} // namespace
PQXX_REGISTER_TEST(test_075);
| 32.578512 | 80 | 0.679097 | [
"vector"
] |
f6e576f67281cacafcd3e14dfeafb193fb98daf1 | 789 | cc | C++ | ash/components/phonehub/fake_browser_tabs_model_provider.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 | ash/components/phonehub/fake_browser_tabs_model_provider.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 | ash/components/phonehub/fake_browser_tabs_model_provider.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 2020 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 "ash/components/phonehub/fake_browser_tabs_model_provider.h"
namespace ash {
namespace phonehub {
FakeBrowserTabsModelProvider::FakeBrowserTabsModelProvider() = default;
FakeBrowserTabsModelProvider::~FakeBrowserTabsModelProvider() {}
void FakeBrowserTabsModelProvider::NotifyBrowserTabsUpdated(
bool is_sync_enabled,
const std::vector<BrowserTabsModel::BrowserTabMetadata>
browser_tabs_metadata) {
BrowserTabsModelProvider::NotifyBrowserTabsUpdated(is_sync_enabled,
browser_tabs_metadata);
}
} // namespace phonehub
} // namespace ash
| 32.875 | 76 | 0.749049 | [
"vector"
] |
f6e835e2a5cc7f96cb74927b1bf03030599934f3 | 32,364 | cpp | C++ | libraries/fc/src/network/http/websocket.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | libraries/fc/src/network/http/websocket.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | libraries/fc/src/network/http/websocket.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | #include <fc/network/http/websocket.hpp>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/config/asio.hpp>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/logger/stub.hpp>
#include <fc/optional.hpp>
#include <fc/variant.hpp>
#include <fc/thread/thread.hpp>
#include <fc/asio.hpp>
/*
#ifdef DEFAULT_LOGGER
# undef DEFAULT_LOGGER
#endif
#define DEFAULT_LOGGER "rpc"
*/
namespace fc { namespace http {
typedef std::shared_ptr<boost::fibers::promise<void> > void_promise_ptr;
namespace detail {
struct asio_with_stub_log : public websocketpp::config::asio {
typedef asio_with_stub_log type;
typedef asio base;
typedef base::concurrency_type concurrency_type;
typedef base::request_type request_type;
typedef base::response_type response_type;
typedef base::message_type message_type;
typedef base::con_msg_manager_type con_msg_manager_type;
typedef base::endpoint_msg_manager_type endpoint_msg_manager_type;
/// Custom Logging policies
/*typedef websocketpp::log::syslog<concurrency_type,
websocketpp::log::elevel> elog_type;
typedef websocketpp::log::syslog<concurrency_type,
websocketpp::log::alevel> alog_type;
*/
//typedef base::alog_type alog_type;
//typedef base::elog_type elog_type;
typedef websocketpp::log::stub elog_type;
typedef websocketpp::log::stub alog_type;
typedef base::rng_type rng_type;
struct transport_config : public base::transport_config {
typedef type::concurrency_type concurrency_type;
typedef type::alog_type alog_type;
typedef type::elog_type elog_type;
typedef type::request_type request_type;
typedef type::response_type response_type;
typedef websocketpp::transport::asio::basic_socket::endpoint
socket_type;
};
typedef websocketpp::transport::asio::endpoint<transport_config>
transport_type;
static const long timeout_open_handshake = 0;
};
struct asio_tls_with_stub_log : public websocketpp::config::asio_tls {
typedef asio_with_stub_log type;
typedef asio_tls base;
typedef base::concurrency_type concurrency_type;
typedef base::request_type request_type;
typedef base::response_type response_type;
typedef base::message_type message_type;
typedef base::con_msg_manager_type con_msg_manager_type;
typedef base::endpoint_msg_manager_type endpoint_msg_manager_type;
/// Custom Logging policies
/*typedef websocketpp::log::syslog<concurrency_type,
websocketpp::log::elevel> elog_type;
typedef websocketpp::log::syslog<concurrency_type,
websocketpp::log::alevel> alog_type;
*/
//typedef base::alog_type alog_type;
//typedef base::elog_type elog_type;
typedef websocketpp::log::stub elog_type;
typedef websocketpp::log::stub alog_type;
typedef base::rng_type rng_type;
struct transport_config : public base::transport_config {
typedef type::concurrency_type concurrency_type;
typedef type::alog_type alog_type;
typedef type::elog_type elog_type;
typedef type::request_type request_type;
typedef type::response_type response_type;
typedef websocketpp::transport::asio::tls_socket::endpoint socket_type;
};
typedef websocketpp::transport::asio::endpoint<transport_config>
transport_type;
static const long timeout_open_handshake = 0;
};
struct asio_tls_stub_log : public websocketpp::config::asio_tls {
typedef asio_tls_stub_log type;
typedef asio_tls base;
typedef base::concurrency_type concurrency_type;
typedef base::request_type request_type;
typedef base::response_type response_type;
typedef base::message_type message_type;
typedef base::con_msg_manager_type con_msg_manager_type;
typedef base::endpoint_msg_manager_type endpoint_msg_manager_type;
//typedef base::alog_type alog_type;
//typedef base::elog_type elog_type;
typedef websocketpp::log::stub elog_type;
typedef websocketpp::log::stub alog_type;
typedef base::rng_type rng_type;
struct transport_config : public base::transport_config {
typedef type::concurrency_type concurrency_type;
typedef type::alog_type alog_type;
typedef type::elog_type elog_type;
typedef type::request_type request_type;
typedef type::response_type response_type;
typedef websocketpp::transport::asio::tls_socket::endpoint socket_type;
};
typedef websocketpp::transport::asio::endpoint<transport_config>
transport_type;
};
using websocketpp::connection_hdl;
typedef websocketpp::server<asio_with_stub_log> websocket_server_type;
typedef websocketpp::server<asio_tls_stub_log> websocket_tls_server_type;
template<typename T>
class websocket_connection_impl : public websocket_connection
{
public:
websocket_connection_impl( T con )
:_ws_connection(con){
}
~websocket_connection_impl()
{
}
virtual void send_message( const std::string& message )override
{
//idump((message));
//std::cerr<<"send: "<<message<<"\n";
auto ec = _ws_connection->send( message );
FC_ASSERT( !ec, "websocket send failed: ${msg}", ("msg",ec.message() ) );
}
virtual void close( int64_t code, const std::string& reason )override
{
_ws_connection->close(code,reason);
}
T _ws_connection;
};
typedef websocketpp::lib::shared_ptr<boost::asio::ssl::context> context_ptr;
class websocket_server_impl
{
public:
websocket_server_impl()
:_server_thread( fc::thread::current() )
{
_server.clear_access_channels( websocketpp::log::alevel::all );
_server.init_asio(&fc::asio::default_io_service());
_server.set_reuse_addr(true);
_server.set_open_handler( [&]( connection_hdl hdl ){
// ilog( "...waiting on server thread" );
_server_thread.async( [&](){
auto new_con = std::make_shared<websocket_connection_impl<websocket_server_type::connection_ptr>>( _server.get_con_from_hdl(hdl) );
_on_connection( _connections[hdl] = new_con );
}).get();
// ilog( "...done waiting on server thread" );
});
_server.set_message_handler( [&]( connection_hdl hdl, websocket_server_type::message_ptr msg ){
// ilog( "...waiting on server thread" );
_server_thread.async( [&](){
auto current_con = _connections.find(hdl);
assert( current_con != _connections.end() );
// wdump(("server")(msg->get_payload()));
// std::cerr<<"recv: "<<msg->get_payload()<<"\n";
auto payload = msg->get_payload();
std::shared_ptr<websocket_connection> con = current_con->second;
++_pending_messages;
auto f = fc::async([this,con,payload](){ if( _pending_messages ) --_pending_messages; con->on_message( payload ); });
if( _pending_messages > 100 )
f.get();
}).get();
// ilog( "...done waiting on server thread" );
});
_server.set_socket_init_handler( [&](websocketpp::connection_hdl hdl, boost::asio::ip::tcp::socket& s ) {
boost::asio::ip::tcp::no_delay option(true);
s.lowest_layer().set_option(option);
} );
_server.set_http_handler( [&]( connection_hdl hdl ){
// ilog( "...waiting on server thread" );
_server_thread.async( [&](){
auto current_con = std::make_shared<websocket_connection_impl<websocket_server_type::connection_ptr>>( _server.get_con_from_hdl(hdl) );
_on_connection( current_con );
auto con = _server.get_con_from_hdl(hdl);
con->defer_http_response();
std::string request_body = con->get_request_body();
//wdump(("server")(request_body));
fc::async([current_con, request_body, con] {
std::string response = current_con->on_http(request_body);
con->set_body( response );
con->set_status( websocketpp::http::status_code::ok );
con->send_http_response();
current_con->closed();
});
}).get();
// ilog( "...done waiting on server thread" );
});
_server.set_close_handler( [&]( connection_hdl hdl ){
// ilog( "...waiting on server thread" );
_server_thread.async( [&](){
if( _connections.find(hdl) != _connections.end() )
{
_connections[hdl]->closed();
_connections.erase( hdl );
}
else
{
wlog( "unknown connection closed" );
}
if( _connections.empty() && _closed )
_closed->set_value();
}).get();
//ilog( "...done waiting on server thread" );
});
_server.set_fail_handler( [&]( connection_hdl hdl ){
if( _server.is_listening() )
{
// ilog( "...waiting on server thread" );
_server_thread.async( [&](){
if( _connections.find(hdl) != _connections.end() )
{
_connections[hdl]->closed();
_connections.erase( hdl );
}
else
{
wlog( "unknown connection failed" );
}
if( _connections.empty() && _closed )
_closed->set_value();
}).get();
//ilog( "...done waiting on server thread" );
}
});
}
~websocket_server_impl()
{
if( _server.is_listening() )
_server.stop_listening();
if( _connections.size() )
_closed = std::make_shared<boost::fibers::promise<void>>();
auto cpy_con = _connections;
for( auto item : cpy_con )
_server.close( item.first, 0, "server exit" );
if( _closed ) _closed->get_future().wait();
}
typedef std::map<connection_hdl, websocket_connection_ptr,std::owner_less<connection_hdl> > con_map;
con_map _connections;
fc::thread& _server_thread;
websocket_server_type _server;
on_connection_handler _on_connection;
void_promise_ptr _closed;
uint32_t _pending_messages = 0;
};
class websocket_tls_server_impl
{
public:
websocket_tls_server_impl( const string& server_pem, const string& ssl_password )
:_server_thread( fc::thread::current() )
{
//if( server_pem.size() )
{
_server.set_tls_init_handler( [=]( websocketpp::connection_hdl hdl ) -> context_ptr {
context_ptr ctx = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv1);
try {
ctx->set_options(boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::no_sslv3 |
boost::asio::ssl::context::single_dh_use);
ctx->set_password_callback([=](std::size_t max_length, boost::asio::ssl::context::password_purpose){ return ssl_password;});
ctx->use_certificate_chain_file(server_pem);
ctx->use_private_key_file(server_pem, boost::asio::ssl::context::pem);
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
return ctx;
});
}
_server.clear_access_channels( websocketpp::log::alevel::all );
_server.init_asio(&fc::asio::default_io_service());
_server.set_reuse_addr(true);
_server.set_open_handler( [&]( connection_hdl hdl ){
_server_thread.async( [&](){
auto new_con = std::make_shared<websocket_connection_impl<websocket_tls_server_type::connection_ptr>>( _server.get_con_from_hdl(hdl) );
_on_connection( _connections[hdl] = new_con );
}).get();
});
_server.set_message_handler( [&]( connection_hdl hdl, websocket_server_type::message_ptr msg ){
_server_thread.async( [&](){
auto current_con = _connections.find(hdl);
assert( current_con != _connections.end() );
auto received = msg->get_payload();
std::shared_ptr<websocket_connection> con = current_con->second;
fc::async([con,received](){ con->on_message( received ); });
}).get();
});
_server.set_http_handler( [&]( connection_hdl hdl ){
_server_thread.async( [&](){
auto current_con = std::make_shared<websocket_connection_impl<websocket_tls_server_type::connection_ptr>>( _server.get_con_from_hdl(hdl) );
try{
_on_connection( current_con );
auto con = _server.get_con_from_hdl(hdl);
//wdump(("server")(con->get_request_body()));
auto response = current_con->on_http( con->get_request_body() );
con->set_body( response );
con->set_status( websocketpp::http::status_code::ok );
} catch ( const fc::exception& e )
{
edump((e.to_detail_string()));
}
current_con->closed();
}).get();
});
_server.set_close_handler( [&]( connection_hdl hdl ){
_server_thread.async( [&](){
_connections[hdl]->closed();
_connections.erase( hdl );
}).get();
});
_server.set_fail_handler( [&]( connection_hdl hdl ){
if( _server.is_listening() )
{
_server_thread.async( [&](){
if( _connections.find(hdl) != _connections.end() )
{
_connections[hdl]->closed();
_connections.erase( hdl );
}
}).get();
}
});
}
~websocket_tls_server_impl()
{
if( _server.is_listening() )
_server.stop_listening();
auto cpy_con = _connections;
for( auto item : cpy_con )
_server.close( item.first, 0, "server exit" );
}
typedef std::map<connection_hdl, websocket_connection_ptr,std::owner_less<connection_hdl> > con_map;
con_map _connections;
fc::thread& _server_thread;
websocket_tls_server_type _server;
on_connection_handler _on_connection;
void_promise_ptr _closed;
};
typedef websocketpp::client<asio_with_stub_log> websocket_client_type;
typedef websocketpp::client<asio_tls_stub_log> websocket_tls_client_type;
typedef websocket_client_type::connection_ptr websocket_client_connection_type;
typedef websocket_tls_client_type::connection_ptr websocket_tls_client_connection_type;
class websocket_client_impl
{
public:
typedef websocket_client_type::message_ptr message_ptr;
websocket_client_impl()
:_client_thread( fc::thread::current() )
{
_client.clear_access_channels( websocketpp::log::alevel::all );
_client.set_message_handler( [&]( connection_hdl hdl, message_ptr msg ){
_client_thread.async( [&](){
// wdump((msg->get_payload()));
// std::cerr<<"recv: "<<msg->get_payload()<<"\n";
auto received = msg->get_payload();
fc::async( [=](){
if( _connection )
_connection->on_message(received);
});
}).get();
});
_client.set_close_handler( [=]( connection_hdl hdl ){
_client_thread.async( [&](){ if( _connection ) {_connection->closed(); _connection.reset();} } ).get();
if( _closed ) _closed->set_value();
});
_client.set_fail_handler( [=]( connection_hdl hdl ){
auto con = _client.get_con_from_hdl(hdl);
auto message = con->get_ec().message();
if( _connection ) {
_client_thread.async( [&](){ if( _connection ) _connection->closed(); _connection.reset(); } ).get();
}
if( _connected /*&& !_connected->ready() REMOVED IN UPDATE */ ) {
try {
_connected->set_exception( std::make_exception_ptr( FC_EXCEPTION( exception, "${message}", ("message",message)) ) );
} catch ( ... ) {}
}
if( _closed ) {
try { _closed->set_value(); } catch ( ... ) {}
}
});
_client.init_asio( &fc::asio::default_io_service() );
}
~websocket_client_impl()
{
if(_connection )
{
//ilog( "close" );
_connection->close(0, "client closed");
_connection.reset();
if( _closed ) {
_closed->get_future().wait();
}
}
}
void_promise_ptr _connected;
void_promise_ptr _closed;
fc::thread& _client_thread;
websocket_client_type _client;
websocket_connection_ptr _connection;
std::string _uri;
};
class websocket_tls_client_impl
{
public:
typedef websocket_tls_client_type::message_ptr message_ptr;
websocket_tls_client_impl( const std::string& ca_filename )
:_client_thread( fc::thread::current() )
{
// ca_filename has special values:
// "_none" disables cert checking (potentially insecure!)
// "_default" uses default CA's provided by OS
_client.clear_access_channels( websocketpp::log::alevel::all );
_client.set_message_handler( [&]( connection_hdl hdl, message_ptr msg ){
_client_thread.async( [&](){
//wdump((msg->get_payload()));
_connection->on_message( msg->get_payload() );
}).get();
});
_client.set_close_handler( [=]( connection_hdl hdl ){
if( _connection )
{
//ilog( "close handler" );
try {
_client_thread.async( [&](){
//wlog(". ${p}", ("p",uint64_t(_connection.get())));
if( !_shutting_down && !_closed && _connection )
_connection->closed();
_connection.reset();
} ).get();
} catch ( const fc::exception& e )
{
if( _closed ) _closed->set_exception( std::current_exception() ); //e.dynamic_copy_exception() );
}
if( _closed ) _closed->set_value();
}
});
_client.set_fail_handler( [=]( connection_hdl hdl ){
elog( "." );
auto con = _client.get_con_from_hdl(hdl);
auto message = con->get_ec().message();
if( _connection )
_client_thread.async( [&](){ if( _connection ) _connection->closed(); _connection.reset(); } ).get();
if( _connected /* && !_connected->ready()REMOVED IN FIBER UPDATE*/ )
_connected->set_exception( std::make_exception_ptr( FC_EXCEPTION( exception, "${message}", ("message",message)) ) );
if( _closed )
_closed->set_value();
});
//
// We need ca_filename to be copied into the closure, as the referenced object might be destroyed by the caller by the time
// tls_init_handler() is called. According to [1], capture-by-value results in the desired behavior (i.e. creation of
// a copy which is stored in the closure) on standards compliant compilers, but some compilers on some optimization levels
// are buggy and are not standards compliant in this situation. Also, keep in mind this is the opinion of a single forum
// poster and might be wrong.
//
// To be safe, the following line explicitly creates a non-reference string which is captured by value, which should have the
// correct behavior on all compilers.
//
// [1] http://www.cplusplus.com/forum/general/142165/
// [2] http://stackoverflow.com/questions/21443023/capturing-a-reference-by-reference-in-a-c11-lambda
//
std::string ca_filename_copy = ca_filename;
_client.set_tls_init_handler( [=](websocketpp::connection_hdl) {
context_ptr ctx = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv1);
try {
ctx->set_options(boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::no_sslv3 |
boost::asio::ssl::context::single_dh_use);
setup_peer_verify( ctx, ca_filename_copy );
} catch (std::exception& e) {
edump((e.what()));
std::cout << e.what() << std::endl;
}
return ctx;
});
_client.init_asio( &fc::asio::default_io_service() );
}
~websocket_tls_client_impl()
{
if(_connection )
{
//wlog(".");
_shutting_down = true;
_connection->close(0, "client closed");
if( _closed )
_closed->get_future().wait();
}
}
std::string get_host()const
{
return websocketpp::uri( _uri ).get_host();
}
void setup_peer_verify( context_ptr& ctx, const std::string& ca_filename )
{
if( ca_filename == "_none" )
return;
ctx->set_verify_mode( boost::asio::ssl::verify_peer );
if( ca_filename == "_default" )
ctx->set_default_verify_paths();
else
ctx->load_verify_file( ca_filename );
ctx->set_verify_depth(10);
ctx->set_verify_callback( boost::asio::ssl::rfc2818_verification( get_host() ) );
}
bool _shutting_down = false;
void_promise_ptr _connected;
void_promise_ptr _closed;
fc::thread& _client_thread;
websocket_tls_client_type _client;
websocket_connection_ptr _connection;
std::string _uri;
};
} // namespace detail
websocket_server::websocket_server():my( new detail::websocket_server_impl() ) {}
websocket_server::~websocket_server(){}
void websocket_server::on_connection( const on_connection_handler& handler )
{
my->_on_connection = handler;
}
void websocket_server::listen( uint16_t port )
{
my->_server.listen(port);
}
void websocket_server::listen( const fc::ip::endpoint& ep )
{
my->_server.listen( boost::asio::ip::tcp::endpoint( boost::asio::ip::address_v4(uint32_t(ep.get_address())),ep.port()) );
}
void websocket_server::start_accept() {
my->_server.start_accept();
}
websocket_tls_server::websocket_tls_server( const string& server_pem, const string& ssl_password ):my( new detail::websocket_tls_server_impl(server_pem, ssl_password) ) {}
websocket_tls_server::~websocket_tls_server(){}
void websocket_tls_server::on_connection( const on_connection_handler& handler )
{
my->_on_connection = handler;
}
void websocket_tls_server::listen( uint16_t port )
{
my->_server.listen(port);
}
void websocket_tls_server::listen( const fc::ip::endpoint& ep )
{
my->_server.listen( boost::asio::ip::tcp::endpoint( boost::asio::ip::address_v4(uint32_t(ep.get_address())),ep.port()) );
}
void websocket_tls_server::start_accept() {
my->_server.start_accept();
}
websocket_tls_client::websocket_tls_client( const std::string& ca_filename ):my( new detail::websocket_tls_client_impl( ca_filename ) ) {}
websocket_tls_client::~websocket_tls_client(){ }
websocket_client::websocket_client( const std::string& ca_filename ):my( new detail::websocket_client_impl() ),smy(new detail::websocket_tls_client_impl( ca_filename )) {}
websocket_client::~websocket_client(){ }
websocket_connection_ptr websocket_client::connect( const std::string& uri )
{ try {
if( uri.substr(0,4) == "wss:" )
return secure_connect(uri);
FC_ASSERT( uri.substr(0,3) == "ws:" );
//wlog( "connecting to ${uri}", ("uri",uri));
websocketpp::lib::error_code ec;
my->_uri = uri;
my->_connected = std::make_shared<boost::fibers::promise<void>>();
my->_client.set_open_handler( [=]( websocketpp::connection_hdl hdl ){
//ilog( "set open handler" );
auto con = my->_client.get_con_from_hdl(hdl);
my->_connection = std::make_shared<detail::websocket_connection_impl<detail::websocket_client_connection_type>>( con );
my->_closed = std::make_shared<boost::fibers::promise<void>>();
//ilog( "connected" );
my->_connected->set_value();
});
auto con = my->_client.get_connection( uri, ec );
if( ec ) FC_ASSERT( !ec, "error: ${e}", ("e",ec.message()) );
//ilog( "_client.connect(con)" );
my->_client.connect(con);
//ilog( "waiting on connected future get" );
my->_connected->get_future().get();
//wlog( "success connecting" );
return my->_connection;
} FC_CAPTURE_AND_RETHROW( (uri) ) }
websocket_connection_ptr websocket_client::secure_connect( const std::string& uri )
{ try {
if( uri.substr(0,3) == "ws:" )
return connect(uri);
FC_ASSERT( uri.substr(0,4) == "wss:" );
//wlog( "connecting to ${uri}", ("uri",uri));
websocketpp::lib::error_code ec;
smy->_uri = uri;
smy->_connected = std::make_shared<boost::fibers::promise<void>>();
smy->_client.set_open_handler( [=]( websocketpp::connection_hdl hdl ){
auto con = smy->_client.get_con_from_hdl(hdl);
smy->_connection = std::make_shared<detail::websocket_connection_impl<detail::websocket_tls_client_connection_type>>( con );
smy->_closed = std::make_shared<boost::fibers::promise<void>>();
smy->_connected->set_value();
});
auto con = smy->_client.get_connection( uri, ec );
if( ec )
FC_ASSERT( !ec, "error: ${e}", ("e",ec.message()) );
smy->_client.connect(con);
smy->_connected->get_future().get();
return smy->_connection;
} FC_CAPTURE_AND_RETHROW( (uri) ) }
websocket_connection_ptr websocket_tls_client::connect( const std::string& uri )
{ try {
//wlog( "connecting to ${uri}", ("uri",uri));
websocketpp::lib::error_code ec;
my->_connected = std::make_shared<boost::fibers::promise<void>>();
my->_client.set_open_handler( [=]( websocketpp::connection_hdl hdl ){
//ilog( "open handler" );
auto con = my->_client.get_con_from_hdl(hdl);
my->_connection = std::make_shared<detail::websocket_connection_impl<detail::websocket_tls_client_connection_type>>( con );
my->_closed = std::make_shared<boost::fibers::promise<void>>();
my->_connected->set_value();
});
auto con = my->_client.get_connection( uri, ec );
if( ec )
{
FC_ASSERT( !ec, "error: ${e}", ("e",ec.message()) );
}
ilog( "_client.connect" );
my->_client.connect(con);
ilog( "waiting..." );
my->_connected->get_future().get();
return my->_connection;
} FC_CAPTURE_AND_RETHROW( (uri) ) }
} } // fc::http
| 42.640316 | 175 | 0.516438 | [
"object"
] |
f6eb2ae05b6c30d93807cf51965ca90591e48d70 | 56,333 | cpp | C++ | examples/SharedMemory/plugins/eglPlugin/eglRendererVisualShapeConverter.cpp | foolyc/bullet3 | f4f5f70886e8d85bb5c000fe0c443fbf958f45d8 | [
"Zlib"
] | 158 | 2016-11-17T19:37:51.000Z | 2022-03-21T19:57:55.000Z | examples/SharedMemory/plugins/eglPlugin/eglRendererVisualShapeConverter.cpp | foolyc/bullet3 | f4f5f70886e8d85bb5c000fe0c443fbf958f45d8 | [
"Zlib"
] | 94 | 2016-11-18T09:55:57.000Z | 2021-01-14T08:50:40.000Z | examples/SharedMemory/plugins/eglPlugin/eglRendererVisualShapeConverter.cpp | foolyc/bullet3 | f4f5f70886e8d85bb5c000fe0c443fbf958f45d8 | [
"Zlib"
] | 51 | 2017-05-24T10:20:25.000Z | 2022-03-17T15:07:02.000Z | /* Copyright (C) 2016 Google
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "eglRendererVisualShapeConverter.h"
#include "../Importers/ImportURDFDemo/URDFImporterInterface.h"
#include "btBulletCollisionCommon.h"
#include "../Importers/ImportObjDemo/LoadMeshFromObj.h"
#include "../Importers/ImportSTLDemo/LoadMeshFromSTL.h"
#include "../Importers/ImportColladaDemo/LoadMeshFromCollada.h"
#include "BulletCollision/CollisionShapes/btShapeHull.h" //to create a tesselation of a generic btConvexShape
#include "../CommonInterfaces/CommonGUIHelperInterface.h"
#include "Bullet3Common/b3FileUtils.h"
#include <string>
#include "../Utils/b3ResourcePath.h"
#include "../TinyRenderer/TinyRenderer.h"
#include "../OpenGLWindow/SimpleCamera.h"
#include "../Importers/ImportMeshUtility/b3ImportMeshUtility.h"
#include <iostream>
#include <fstream>
#include "../Importers/ImportURDFDemo/UrdfParser.h"
#include "../SharedMemory/SharedMemoryPublic.h" //for b3VisualShapeData
#include "../TinyRenderer/model.h"
#include "stb_image/stb_image.h"
#include "LinearMath/btMinMax.h"
#ifdef __APPLE__
#include "OpenGLWindow/MacOpenGLWindow.h"
typedef MacOpenGLWindow DefaultOpenGLWindow;
#else
#ifdef _WIN32
#include "OpenGLWindow/Win32OpenGLWindow.h"
typedef Win32OpenGLWindow DefaultOpenGLWindow;
#else
#ifdef BT_USE_EGL
#include "OpenGLWindow/EGLOpenGLWindow.h"
typedef EGLOpenGLWindow DefaultOpenGLWindow;
#else
#include "OpenGLWindow/X11OpenGLWindow.h"
typedef X11OpenGLWindow DefaultOpenGLWindow;
#endif //BT_USE_EGL
#endif // _WIN32
#endif //__APPLE__
#include "OpenGLWindow/GLInstancingRenderer.h"
#include "OpenGLWindow/GLRenderToTexture.h"
static void printGLString(const char* name, GLenum s)
{
const char* v = (const char*)glGetString(s);
printf("%s = %s\n", name, v);
}
using namespace std;
struct MyTexture3
{
unsigned char* textureData1;
int m_width;
int m_height;
bool m_isCached;
};
struct EGLRendererObjectArray
{
btAlignedObjectArray<int> m_graphicsInstanceIds;
int m_objectUniqueId;
int m_linkIndex;
btTransform m_worldTransform;
btVector3 m_localScaling;
EGLRendererObjectArray()
{
m_worldTransform.setIdentity();
m_localScaling.setValue(1, 1, 1);
}
};
//#define START_WIDTH 2560
//#define START_HEIGHT 2048
#define START_WIDTH 1024
#define START_HEIGHT 768
struct btHashVisual
{
UrdfShape m_vis;
btTransform m_tr;
int getHash() const
{
if (m_vis.m_geometry.m_meshFileName.length())
{
btHashString s = m_vis.m_geometry.m_meshFileName.c_str();
return s.getHash();
}
return 0;
}
bool equals(const btHashVisual& other) const
{
if ((m_vis.m_geometry.m_type == URDF_GEOM_MESH) &&
(other.m_vis.m_geometry.m_type == URDF_GEOM_MESH))
{
bool sameTr = m_tr == other.m_tr;
bool sameVis = m_vis.m_geometry.m_meshFileName == other.m_vis.m_geometry.m_meshFileName;
bool sameLocalFrame = m_vis.m_linkLocalFrame == other.m_vis.m_linkLocalFrame;
return sameTr&&sameVis&&sameLocalFrame;
}
return false;
}
};
struct EGLRendererVisualShapeConverterInternalData
{
class CommonWindowInterface* m_window;
class GLInstancingRenderer* m_instancingRenderer;
btAlignedObjectArray<unsigned char> m_rgbaPixelBuffer1;
btAlignedObjectArray<float> m_depthBuffer1;
btAlignedObjectArray<unsigned char> m_segmentationMaskSourceRgbaPixelBuffer;
btAlignedObjectArray<float> m_segmentationMaskSourceDepthBuffer;
btAlignedObjectArray<int> m_graphicsIndexToSegmentationMask;
btHashMap<btHashInt, EGLRendererObjectArray*> m_swRenderInstances;
btHashMap<btHashPtr, int> m_cachedTextureIds;
btHashMap<btHashVisual, int> m_cachedVisualShapes;
btAlignedObjectArray<b3VisualShapeData> m_visualShapes;
int m_upAxis;
int m_swWidth;
int m_swHeight;
btAlignedObjectArray<unsigned char> m_sourceRgbaPixelBuffer;
btAlignedObjectArray<float> m_sourceDepthBuffer;
TGAImage m_rgbColorBuffer;
b3AlignedObjectArray<MyTexture3> m_textures;
b3AlignedObjectArray<float> m_depthBuffer;
b3AlignedObjectArray<float> m_shadowBuffer;
b3AlignedObjectArray<int> m_segmentationMaskBuffer;
btVector3 m_lightDirection;
bool m_hasLightDirection;
btVector3 m_lightColor;
bool m_hasLightColor;
float m_lightDistance;
bool m_hasLightDistance;
float m_lightAmbientCoeff;
bool m_hasLightAmbientCoeff;
float m_lightDiffuseCoeff;
bool m_hasLightDiffuseCoeff;
float m_lightSpecularCoeff;
bool m_hasLightSpecularCoeff;
bool m_hasShadow;
int m_flags;
SimpleCamera m_camera;
bool m_leftMouseButton;
bool m_middleMouseButton;
bool m_rightMouseButton;
float m_wheelMultiplier;
float m_mouseMoveMultiplier;
float m_mouseXpos;
float m_mouseYpos;
bool m_mouseInitialized;
int m_graphicsUniqueIdGenerator;
EGLRendererVisualShapeConverterInternalData()
: m_upAxis(2),
m_swWidth(START_WIDTH),
m_swHeight(START_HEIGHT),
m_rgbColorBuffer(START_WIDTH, START_HEIGHT, TGAImage::RGB),
m_lightDirection(btVector3(-5, -40, 200 )),
m_hasLightDirection(false),
m_lightColor(btVector3(1.0, 1.0, 1.0)),
m_hasLightColor(false),
m_lightDistance(2.0),
m_hasLightDistance(false),
m_lightAmbientCoeff(0.6),
m_hasLightAmbientCoeff(false),
m_lightDiffuseCoeff(0.35),
m_hasLightDiffuseCoeff(false),
m_lightSpecularCoeff(0.05),
m_hasLightSpecularCoeff(false),
m_hasShadow(false),
m_flags(0),
m_leftMouseButton(false),
m_middleMouseButton(false),
m_rightMouseButton(false),
m_wheelMultiplier(0.01f),
m_mouseMoveMultiplier(0.4f),
m_mouseXpos(0.f),
m_mouseYpos(0.f),
m_mouseInitialized(false),
m_graphicsUniqueIdGenerator(15)
{
m_depthBuffer.resize(m_swWidth * m_swHeight);
m_shadowBuffer.resize(m_swWidth * m_swHeight);
m_segmentationMaskBuffer.resize(m_swWidth * m_swHeight, -1);
// OpenGL window
bool allowRetina = true;
m_window = new DefaultOpenGLWindow();
m_window->setAllowRetina(allowRetina);
b3gWindowConstructionInfo ci;
ci.m_title = "PyBullet";
ci.m_width = m_swWidth;
ci.m_height = m_swHeight;
ci.m_renderDevice = 0;
m_window->createWindow(ci);
m_window->setWindowTitle(ci.m_title);
b3Assert(glGetError() == GL_NO_ERROR);
{
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
}
glClearColor(.7f, .7f, .8f, 1.f);
m_window->startRendering();
b3Assert(glGetError() == GL_NO_ERROR);
glGetError(); //don't remove this call, it is needed for Ubuntu
b3Assert(glGetError() == GL_NO_ERROR);
int maxNumObjectCapacity = 128 * 1024;
int maxShapeCapacityInBytes = 128 * 1024 * 1024;
m_instancingRenderer = new GLInstancingRenderer(maxNumObjectCapacity, maxShapeCapacityInBytes);
b3Assert(glGetError() == GL_NO_ERROR);
m_instancingRenderer->init();
b3Assert(glGetError() == GL_NO_ERROR);
m_instancingRenderer->resize(m_swWidth, m_swHeight);
m_instancingRenderer->InitShaders();
b3Assert(glGetError() == GL_NO_ERROR);
m_instancingRenderer->setActiveCamera(&m_camera);
b3Assert(glGetError() == GL_NO_ERROR);
m_instancingRenderer->updateCamera();
b3Assert(glGetError() == GL_NO_ERROR);
m_instancingRenderer->setLightPosition(m_lightDirection);
m_window->endRendering();
}
virtual ~EGLRendererVisualShapeConverterInternalData()
{
delete m_instancingRenderer;
m_window->closeWindow();
delete m_window;
}
};
static EGLRendererVisualShapeConverter* gWindow = 0;
static void SimpleResizeCallback(float widthf, float heightf)
{
int width = (int)widthf;
int height = (int)heightf;
if (gWindow && gWindow->m_data->m_instancingRenderer)
{
gWindow->m_data->m_instancingRenderer->resize(width, height);
gWindow->setWidthAndHeight(width, height);
}
//if (gApp && gApp->m_instancingRenderer)
// gApp->m_instancingRenderer->resize(width, height);
//
//if (gApp && gApp->m_primRenderer)
// gApp->m_primRenderer->setScreenSize(width, height);
}
#if 0
static void SimpleKeyboardCallback(int key, int state)
{
if (key == B3G_ESCAPE) //&& gApp && gApp->m_window)
{
//gApp->m_window->setRequestExit();
}
else
{
//gApp->defaultKeyboardCallback(key,state);
}
}
#endif
static void SimpleMouseButtonCallback(int button, int state, float x, float y)
{
if (gWindow)
{
gWindow->mouseButtonCallback(button, state, x, y);
}
}
static void SimpleMouseMoveCallback(float x, float y)
{
if (gWindow)
{
gWindow->mouseMoveCallback(x, y);
}
}
static void SimpleWheelCallback(float deltax, float deltay)
{
float wheelMultiplier = 0.01f;
if (gWindow && gWindow->m_data->m_instancingRenderer)
{
class GLInstancingRenderer* renderer = gWindow->m_data->m_instancingRenderer;
b3Vector3 cameraTargetPosition, cameraPosition, cameraUp = b3MakeVector3(0, 0, 0);
int upAxis = renderer->getActiveCamera()->getCameraUpAxis();
cameraUp[upAxis] = 1;
CommonCameraInterface* camera = renderer->getActiveCamera();
camera->getCameraPosition(cameraPosition);
camera->getCameraTargetPosition(cameraTargetPosition);
bool m_leftMouseButton = false;
if (!m_leftMouseButton)
{
float cameraDistance = camera->getCameraDistance();
if (deltay < 0 || cameraDistance > 1)
{
cameraDistance -= deltay * 0.01f;
if (cameraDistance < 1)
cameraDistance = 1;
camera->setCameraDistance(cameraDistance);
}
else
{
b3Vector3 fwd = cameraTargetPosition - cameraPosition;
fwd.normalize();
cameraTargetPosition += fwd * deltay * wheelMultiplier; //todo: expose it in the GUI?
}
}
else
{
if (b3Fabs(deltax) > b3Fabs(deltay))
{
b3Vector3 fwd = cameraTargetPosition - cameraPosition;
b3Vector3 side = cameraUp.cross(fwd);
side.normalize();
cameraTargetPosition += side * deltax * wheelMultiplier;
}
else
{
cameraTargetPosition -= cameraUp * deltay * wheelMultiplier;
}
}
camera->setCameraTargetPosition(cameraTargetPosition[0], cameraTargetPosition[1], cameraTargetPosition[2]);
}
}
void defaultMouseButtonCallback(int button, int state, float x, float y)
{
if (gWindow)
{
gWindow->mouseButtonCallback(button, state, x, y);
}
}
void defaultMouseMoveCallback(float x, float y)
{
if (gWindow)
{
gWindow->mouseMoveCallback(x, y);
} //m_window && m_renderer
}
void EGLRendererVisualShapeConverter::mouseButtonCallback(int button, int state, float x, float y)
{
if (button == 0)
m_data->m_leftMouseButton = (state == 1);
if (button == 1)
m_data->m_middleMouseButton = (state == 1);
if (button == 2)
m_data->m_rightMouseButton = (state == 1);
m_data->m_mouseXpos = x;
m_data->m_mouseYpos = y;
m_data->m_mouseInitialized = true;
}
void EGLRendererVisualShapeConverter::mouseMoveCallback(float x, float y)
{
class GLInstancingRenderer* renderer = m_data->m_instancingRenderer;
if (renderer == 0)
return;
CommonCameraInterface* camera = renderer->getActiveCamera();
bool isAltPressed = m_data->m_window->isModifierKeyPressed(B3G_ALT);
bool isControlPressed = m_data->m_window->isModifierKeyPressed(B3G_CONTROL);
if (isAltPressed || isControlPressed)
{
float xDelta = x - m_data->m_mouseXpos;
float yDelta = y - m_data->m_mouseYpos;
float cameraDistance = camera->getCameraDistance();
float pitch = camera->getCameraPitch();
float yaw = camera->getCameraYaw();
float targPos[3];
float camPos[3];
camera->getCameraTargetPosition(targPos);
camera->getCameraPosition(camPos);
b3Vector3 cameraPosition = b3MakeVector3(b3Scalar(camPos[0]),
b3Scalar(camPos[1]),
b3Scalar(camPos[2]));
b3Vector3 cameraTargetPosition = b3MakeVector3(b3Scalar(targPos[0]),
b3Scalar(targPos[1]),
b3Scalar(targPos[2]));
b3Vector3 cameraUp = b3MakeVector3(0, 0, 0);
cameraUp[camera->getCameraUpAxis()] = 1.f;
if (m_data->m_leftMouseButton)
{
// if (b3Fabs(xDelta)>b3Fabs(yDelta))
// {
pitch -= yDelta * m_data->m_mouseMoveMultiplier;
// } else
// {
yaw -= xDelta * m_data->m_mouseMoveMultiplier;
// }
}
if (m_data->m_middleMouseButton)
{
cameraTargetPosition += cameraUp * yDelta * 0.01;
b3Vector3 fwd = cameraTargetPosition - cameraPosition;
b3Vector3 side = cameraUp.cross(fwd);
side.normalize();
cameraTargetPosition += side * xDelta * 0.01;
}
if (m_data->m_rightMouseButton)
{
cameraDistance -= xDelta * 0.01f;
cameraDistance -= yDelta * 0.01f;
if (cameraDistance < 1)
cameraDistance = 1;
if (cameraDistance > 1000)
cameraDistance = 1000;
}
camera->setCameraDistance(cameraDistance);
camera->setCameraPitch(pitch);
camera->setCameraYaw(yaw);
camera->setCameraTargetPosition(cameraTargetPosition[0], cameraTargetPosition[1], cameraTargetPosition[2]);
}
m_data->m_mouseXpos = x;
m_data->m_mouseYpos = y;
m_data->m_mouseInitialized = true;
}
EGLRendererVisualShapeConverter::EGLRendererVisualShapeConverter()
{
m_data = new EGLRendererVisualShapeConverterInternalData();
float dist = 1.5;
float pitch = -10;
float yaw = -80;
float targetPos[3] = {0, 0, 0};
m_data->m_camera.setCameraUpAxis(m_data->m_upAxis);
resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
gWindow = this;
m_data->m_window->setResizeCallback(SimpleResizeCallback);
m_data->m_window->setWheelCallback(SimpleWheelCallback);
m_data->m_window->setMouseButtonCallback(SimpleMouseButtonCallback);
m_data->m_window->setMouseMoveCallback(SimpleMouseMoveCallback);
}
EGLRendererVisualShapeConverter::~EGLRendererVisualShapeConverter()
{
gWindow = 0;
resetAll();
delete m_data;
}
void EGLRendererVisualShapeConverter::setLightDirection(float x, float y, float z)
{
m_data->m_lightDirection.setValue(x, y, z);
m_data->m_hasLightDirection = true;
}
void EGLRendererVisualShapeConverter::setLightColor(float x, float y, float z)
{
m_data->m_lightColor.setValue(x, y, z);
m_data->m_hasLightColor = true;
}
void EGLRendererVisualShapeConverter::setLightDistance(float dist)
{
m_data->m_lightDistance = dist;
m_data->m_hasLightDistance = true;
}
void EGLRendererVisualShapeConverter::setShadow(bool hasShadow)
{
m_data->m_hasShadow = hasShadow;
}
void EGLRendererVisualShapeConverter::setFlags(int flags)
{
m_data->m_flags = flags;
}
void EGLRendererVisualShapeConverter::setLightAmbientCoeff(float ambientCoeff)
{
m_data->m_lightAmbientCoeff = ambientCoeff;
m_data->m_hasLightAmbientCoeff = true;
}
void EGLRendererVisualShapeConverter::setLightDiffuseCoeff(float diffuseCoeff)
{
m_data->m_lightDiffuseCoeff = diffuseCoeff;
m_data->m_hasLightDiffuseCoeff = true;
}
void EGLRendererVisualShapeConverter::setLightSpecularCoeff(float specularCoeff)
{
m_data->m_lightSpecularCoeff = specularCoeff;
m_data->m_hasLightSpecularCoeff = true;
}
///todo: merge into single file with TinyRendererVisualShapeConverter
static void convertURDFToVisualShape2(const UrdfShape* visual, const char* urdfPathPrefix, const btTransform& visualTransform, btAlignedObjectArray<GLInstanceVertex>& verticesOut, btAlignedObjectArray<int>& indicesOut, btAlignedObjectArray<MyTexture3>& texturesOut, b3VisualShapeData& visualShapeOut, struct CommonFileIOInterface* fileIO, int flags)
{
visualShapeOut.m_visualGeometryType = visual->m_geometry.m_type;
visualShapeOut.m_dimensions[0] = 0;
visualShapeOut.m_dimensions[1] = 0;
visualShapeOut.m_dimensions[2] = 0;
memset(visualShapeOut.m_meshAssetFileName, 0, sizeof(visualShapeOut.m_meshAssetFileName));
#if 0
if (visual->m_geometry.m_hasLocalMaterial)
{
visualShapeOut.m_rgbaColor[0] = visual->m_geometry.m_localMaterial.m_matColor.m_rgbaColor[0];
visualShapeOut.m_rgbaColor[1] = visual->m_geometry.m_localMaterial.m_matColor.m_rgbaColor[1];
visualShapeOut.m_rgbaColor[2] = visual->m_geometry.m_localMaterial.m_matColor.m_rgbaColor[2];
visualShapeOut.m_rgbaColor[3] = visual->m_geometry.m_localMaterial.m_matColor.m_rgbaColor[3];
}
#endif
GLInstanceGraphicsShape* glmesh = 0;
btConvexShape* convexColShape = 0;
switch (visual->m_geometry.m_type)
{
case URDF_GEOM_CYLINDER:
case URDF_GEOM_CAPSULE:
{
btVector3 p1 = visual->m_geometry.m_capsuleFrom;
btVector3 p2 = visual->m_geometry.m_capsuleTo;
btTransform tr;
tr.setIdentity();
btScalar rad, len;
btVector3 center(0, 0, 0);
btVector3 axis(0, 0, 1);
btAlignedObjectArray<btVector3> vertices;
int numSteps = 32;
if (visual->m_geometry.m_hasFromTo)
{
btVector3 v = p2 - p1;
btVector3 dir = v.normalized();
tr = visual->m_linkLocalFrame;
len = v.length();
rad = visual->m_geometry.m_capsuleRadius;
btVector3 ax1, ax2;
btPlaneSpace1(dir, ax1, ax2);
for (int i = 0; i < numSteps; i++)
{
{
btVector3 vert = p1 + ax1 * rad * btSin(SIMD_2_PI * (float(i) / numSteps)) + ax2 * rad * btCos(SIMD_2_PI * (float(i) / numSteps));
vertices.push_back(vert);
}
{
btVector3 vert = p2 + ax1 * rad * btSin(SIMD_2_PI * (float(i) / numSteps)) + ax2 * rad * btCos(SIMD_2_PI * (float(i) / numSteps));
vertices.push_back(vert);
}
}
if (visual->m_geometry.m_type == URDF_GEOM_CAPSULE)
{
btVector3 pole1 = p1 - dir * rad;
btVector3 pole2 = p2 + dir * rad;
vertices.push_back(pole1);
vertices.push_back(pole2);
}
}
else
{
//assume a capsule along the Z-axis, centered at the origin
tr = visual->m_linkLocalFrame;
len = visual->m_geometry.m_capsuleHeight;
rad = visual->m_geometry.m_capsuleRadius;
for (int i = 0; i < numSteps; i++)
{
btVector3 vert(rad * btSin(SIMD_2_PI * (float(i) / numSteps)), rad * btCos(SIMD_2_PI * (float(i) / numSteps)), len / 2.);
vertices.push_back(vert);
vert[2] = -len / 2.;
vertices.push_back(vert);
}
if (visual->m_geometry.m_type == URDF_GEOM_CAPSULE)
{
btVector3 pole1(0, 0, +len / 2. + rad);
btVector3 pole2(0, 0, -len / 2. - rad);
vertices.push_back(pole1);
vertices.push_back(pole2);
}
}
visualShapeOut.m_localVisualFrame[0] = tr.getOrigin()[0];
visualShapeOut.m_localVisualFrame[1] = tr.getOrigin()[1];
visualShapeOut.m_localVisualFrame[2] = tr.getOrigin()[2];
visualShapeOut.m_localVisualFrame[3] = tr.getRotation()[0];
visualShapeOut.m_localVisualFrame[4] = tr.getRotation()[1];
visualShapeOut.m_localVisualFrame[5] = tr.getRotation()[2];
visualShapeOut.m_localVisualFrame[6] = tr.getRotation()[3];
visualShapeOut.m_dimensions[0] = len;
visualShapeOut.m_dimensions[1] = rad;
btConvexHullShape* cylZShape = new btConvexHullShape(&vertices[0].x(), vertices.size(), sizeof(btVector3));
//btCapsuleShape* cylZShape = new btCapsuleShape(rad,len);//btConvexHullShape(&vertices[0].x(), vertices.size(), sizeof(btVector3));
cylZShape->setMargin(0.001);
convexColShape = cylZShape;
break;
}
case URDF_GEOM_BOX:
{
visualShapeOut.m_dimensions[0] = visual->m_geometry.m_boxSize[0];
visualShapeOut.m_dimensions[1] = visual->m_geometry.m_boxSize[1];
visualShapeOut.m_dimensions[2] = visual->m_geometry.m_boxSize[2];
btVector3 extents = visual->m_geometry.m_boxSize;
btBoxShape* boxShape = new btBoxShape(extents * 0.5f);
//btConvexShape* boxShape = new btConeShapeX(extents[2]*0.5,extents[0]*0.5);
convexColShape = boxShape;
convexColShape->setMargin(0.001);
break;
}
case URDF_GEOM_SPHERE:
{
visualShapeOut.m_dimensions[0] = visual->m_geometry.m_sphereRadius;
btScalar radius = visual->m_geometry.m_sphereRadius;
btSphereShape* sphereShape = new btSphereShape(radius);
convexColShape = sphereShape;
convexColShape->setMargin(0.001);
break;
}
case URDF_GEOM_MESH:
{
strncpy(visualShapeOut.m_meshAssetFileName, visual->m_geometry.m_meshFileName.c_str(), VISUAL_SHAPE_MAX_PATH_LEN);
visualShapeOut.m_meshAssetFileName[VISUAL_SHAPE_MAX_PATH_LEN - 1] = 0;
visualShapeOut.m_dimensions[0] = visual->m_geometry.m_meshScale[0];
visualShapeOut.m_dimensions[1] = visual->m_geometry.m_meshScale[1];
visualShapeOut.m_dimensions[2] = visual->m_geometry.m_meshScale[2];
switch (visual->m_geometry.m_meshFileType)
{
case UrdfGeometry::FILE_OBJ:
{
//glmesh = LoadMeshFromObj(fullPath,visualPathPrefix);
b3ImportMeshData meshData;
if (b3ImportMeshUtility::loadAndRegisterMeshFromFileInternal(visual->m_geometry.m_meshFileName, meshData, fileIO))
{
if (flags&URDF_USE_MATERIAL_COLORS_FROM_MTL)
{
if (meshData.m_flags & B3_IMPORT_MESH_HAS_RGBA_COLOR)
{
visualShapeOut.m_rgbaColor[0] = meshData.m_rgbaColor[0];
visualShapeOut.m_rgbaColor[1] = meshData.m_rgbaColor[1];
visualShapeOut.m_rgbaColor[2] = meshData.m_rgbaColor[2];
if (flags&URDF_USE_MATERIAL_TRANSPARANCY_FROM_MTL)
{
visualShapeOut.m_rgbaColor[3] = meshData.m_rgbaColor[3];
} else
{
visualShapeOut.m_rgbaColor[3] = 1;
}
}
}
if (meshData.m_textureImage1)
{
MyTexture3 texData;
texData.m_width = meshData.m_textureWidth;
texData.m_height = meshData.m_textureHeight;
texData.textureData1 = meshData.m_textureImage1;
texData.m_isCached = meshData.m_isCached;
texturesOut.push_back(texData);
}
glmesh = meshData.m_gfxShape;
}
break;
}
case UrdfGeometry::FILE_STL:
glmesh = LoadMeshFromSTL(visual->m_geometry.m_meshFileName.c_str(), fileIO);
break;
case UrdfGeometry::FILE_COLLADA:
{
btAlignedObjectArray<GLInstanceGraphicsShape> visualShapes;
btAlignedObjectArray<ColladaGraphicsInstance> visualShapeInstances;
btTransform upAxisTrans;
upAxisTrans.setIdentity();
float unitMeterScaling = 1;
int upAxis = 2;
LoadMeshFromCollada(visual->m_geometry.m_meshFileName.c_str(),
visualShapes,
visualShapeInstances,
upAxisTrans,
unitMeterScaling,
upAxis, fileIO);
glmesh = new GLInstanceGraphicsShape;
// int index = 0;
glmesh->m_indices = new b3AlignedObjectArray<int>();
glmesh->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
for (int i = 0; i < visualShapeInstances.size(); i++)
{
ColladaGraphicsInstance* instance = &visualShapeInstances[i];
GLInstanceGraphicsShape* gfxShape = &visualShapes[instance->m_shapeIndex];
b3AlignedObjectArray<GLInstanceVertex> verts;
verts.resize(gfxShape->m_vertices->size());
int baseIndex = glmesh->m_vertices->size();
for (int i = 0; i < gfxShape->m_vertices->size(); i++)
{
verts[i].normal[0] = gfxShape->m_vertices->at(i).normal[0];
verts[i].normal[1] = gfxShape->m_vertices->at(i).normal[1];
verts[i].normal[2] = gfxShape->m_vertices->at(i).normal[2];
verts[i].uv[0] = gfxShape->m_vertices->at(i).uv[0];
verts[i].uv[1] = gfxShape->m_vertices->at(i).uv[1];
verts[i].xyzw[0] = gfxShape->m_vertices->at(i).xyzw[0];
verts[i].xyzw[1] = gfxShape->m_vertices->at(i).xyzw[1];
verts[i].xyzw[2] = gfxShape->m_vertices->at(i).xyzw[2];
verts[i].xyzw[3] = gfxShape->m_vertices->at(i).xyzw[3];
}
int curNumIndices = glmesh->m_indices->size();
int additionalIndices = gfxShape->m_indices->size();
glmesh->m_indices->resize(curNumIndices + additionalIndices);
for (int k = 0; k < additionalIndices; k++)
{
glmesh->m_indices->at(curNumIndices + k) = gfxShape->m_indices->at(k) + baseIndex;
}
//compensate upAxisTrans and unitMeterScaling here
btMatrix4x4 upAxisMat;
upAxisMat.setIdentity();
// upAxisMat.setPureRotation(upAxisTrans.getRotation());
btMatrix4x4 unitMeterScalingMat;
unitMeterScalingMat.setPureScaling(btVector3(unitMeterScaling, unitMeterScaling, unitMeterScaling));
btMatrix4x4 worldMat = unitMeterScalingMat * upAxisMat * instance->m_worldTransform;
//btMatrix4x4 worldMat = instance->m_worldTransform;
int curNumVertices = glmesh->m_vertices->size();
int additionalVertices = verts.size();
glmesh->m_vertices->reserve(curNumVertices + additionalVertices);
for (int v = 0; v < verts.size(); v++)
{
btVector3 pos(verts[v].xyzw[0], verts[v].xyzw[1], verts[v].xyzw[2]);
pos = worldMat * pos;
verts[v].xyzw[0] = float(pos[0]);
verts[v].xyzw[1] = float(pos[1]);
verts[v].xyzw[2] = float(pos[2]);
glmesh->m_vertices->push_back(verts[v]);
}
}
glmesh->m_numIndices = glmesh->m_indices->size();
glmesh->m_numvertices = glmesh->m_vertices->size();
//glmesh = LoadMeshFromCollada(visual->m_geometry.m_meshFileName.c_str());
break;
}
default:
// should never get here (findExistingMeshFile returns false if it doesn't recognize extension)
btAssert(0);
}
if (glmesh && glmesh->m_vertices && (glmesh->m_numvertices > 0))
{
//apply the geometry scaling
for (int i = 0; i < glmesh->m_vertices->size(); i++)
{
glmesh->m_vertices->at(i).xyzw[0] *= visual->m_geometry.m_meshScale[0];
glmesh->m_vertices->at(i).xyzw[1] *= visual->m_geometry.m_meshScale[1];
glmesh->m_vertices->at(i).xyzw[2] *= visual->m_geometry.m_meshScale[2];
}
}
else
{
b3Warning("issue extracting mesh from COLLADA/STL file %s\n", visual->m_geometry.m_meshFileName.c_str());
}
break;
} // case mesh
case URDF_GEOM_PLANE:
// TODO: plane in egl renderer
// TODO: export visualShapeOut for external render
break;
default:
{
b3Warning("TinyRenderer: unknown visual geometry type %i\n", visual->m_geometry.m_type);
}
}
//if we have a convex, tesselate into localVertices/localIndices
if ((glmesh == 0) && convexColShape)
{
btShapeHull* hull = new btShapeHull(convexColShape);
hull->buildHull(0.0);
{
// int strideInBytes = 9*sizeof(float);
int numVertices = hull->numVertices();
int numIndices = hull->numIndices();
glmesh = new GLInstanceGraphicsShape;
// int index = 0;
glmesh->m_indices = new b3AlignedObjectArray<int>();
glmesh->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
for (int i = 0; i < numVertices; i++)
{
GLInstanceVertex vtx;
btVector3 pos = hull->getVertexPointer()[i];
vtx.xyzw[0] = pos.x();
vtx.xyzw[1] = pos.y();
vtx.xyzw[2] = pos.z();
vtx.xyzw[3] = 1.f;
btVector3 normal = pos.safeNormalize();
vtx.normal[0] = normal.x();
vtx.normal[1] = normal.y();
vtx.normal[2] = normal.z();
btScalar u = btAtan2(normal[0], normal[2]) / (2 * SIMD_PI) + 0.5;
btScalar v = normal[1] * 0.5 + 0.5;
vtx.uv[0] = u;
vtx.uv[1] = v;
glmesh->m_vertices->push_back(vtx);
}
btAlignedObjectArray<int> indices;
for (int i = 0; i < numIndices; i++)
{
glmesh->m_indices->push_back(hull->getIndexPointer()[i]);
}
glmesh->m_numvertices = glmesh->m_vertices->size();
glmesh->m_numIndices = glmesh->m_indices->size();
}
delete hull;
delete convexColShape;
convexColShape = 0;
}
if (glmesh && glmesh->m_numIndices > 0 && glmesh->m_numvertices > 0)
{
int baseIndex = verticesOut.size();
for (int i = 0; i < glmesh->m_indices->size(); i++)
{
indicesOut.push_back(glmesh->m_indices->at(i) + baseIndex);
}
for (int i = 0; i < glmesh->m_vertices->size(); i++)
{
GLInstanceVertex& v = glmesh->m_vertices->at(i);
btVector3 vert(v.xyzw[0], v.xyzw[1], v.xyzw[2]);
btVector3 vt = visualTransform * vert;
v.xyzw[0] = vt[0];
v.xyzw[1] = vt[1];
v.xyzw[2] = vt[2];
btVector3 triNormal(v.normal[0], v.normal[1], v.normal[2]);
triNormal = visualTransform.getBasis() * triNormal;
v.normal[0] = triNormal[0];
v.normal[1] = triNormal[1];
v.normal[2] = triNormal[2];
verticesOut.push_back(v);
}
}
delete glmesh;
}
static btVector4 sColors[4] =
{
btVector4(60. / 256., 186. / 256., 84. / 256., 1),
btVector4(244. / 256., 194. / 256., 13. / 256., 1),
btVector4(219. / 256., 50. / 256., 54. / 256., 1),
btVector4(72. / 256., 133. / 256., 237. / 256., 1),
//btVector4(1,1,0,1),
};
// If you are getting segfaults in this function it may be ecause you are
// compliling the plugin with differently from pybullet, try complining the
// plugin with distutils too.
int EGLRendererVisualShapeConverter::convertVisualShapes(
int linkIndex, const char* pathPrefix, const btTransform& localInertiaFrame,
const UrdfLink* linkPtr, const UrdfModel* model,
int orgGraphicsUniqueId, int bodyUniqueId, struct CommonFileIOInterface* fileIO)
{
if (orgGraphicsUniqueId< 0)
{
orgGraphicsUniqueId = m_data->m_graphicsUniqueIdGenerator++;
}
btAssert(linkPtr); // TODO: remove if (not doing it now, because diff will be 50+ lines)
if (linkPtr)
{
bool useVisual;
int cnt = 0;
if (linkPtr->m_visualArray.size() > 0)
{
useVisual = true;
cnt = linkPtr->m_visualArray.size();
}
else
{
// We have to see something, take collision shape. Useful for MuJoCo xml, where there are no explicit visual shapes.
useVisual = false;
cnt = linkPtr->m_collisionArray.size();
}
for (int v1 = 0; v1 < cnt; v1++)
{
btAlignedObjectArray<MyTexture3> textures;
btAlignedObjectArray<GLInstanceVertex> vertices;
btAlignedObjectArray<int> indices;
btTransform startTrans;
startTrans.setIdentity();
//int graphicsIndex = -1;
const UrdfShape* vis;
if (useVisual)
{
vis = &linkPtr->m_visualArray[v1];
}
else
{
vis = &linkPtr->m_collisionArray[v1];
}
// see note at function header
btTransform childTrans = vis->m_linkLocalFrame;
int colorIndex = linkIndex; //colObj? colObj->getBroadphaseHandle()->getUid() & 3 : 0;
if (colorIndex < 0)
colorIndex = 0;
colorIndex &= 3;
btVector4 color;
color = sColors[colorIndex];
float rgbaColor[4] = { (float)color[0], (float)color[1], (float)color[2], (float)color[3] };
//if (colObj->getCollisionShape()->getShapeType()==STATIC_PLANE_PROXYTYPE)
//{
// color.setValue(1,1,1,1);
//}
if (model)
{
if (useVisual)
{
btHashString matName(linkPtr->m_visualArray[v1].m_materialName.c_str());
UrdfMaterial* const* matPtr = model->m_materials[matName];
if (matPtr)
{
for (int i = 0; i < 4; i++)
{
rgbaColor[i] = (*matPtr)->m_matColor.m_rgbaColor[i];
}
//printf("UrdfMaterial %s, rgba = %f,%f,%f,%f\n",mat->m_name.c_str(),mat->m_rgbaColor[0],mat->m_rgbaColor[1],mat->m_rgbaColor[2],mat->m_rgbaColor[3]);
//m_data->m_linkColors.insert(linkIndex,mat->m_rgbaColor);
}
else
{
///programmatic created models may have the color in the visual
if (vis && vis->m_geometry.m_hasLocalMaterial)
{
for (int i = 0; i < 4; i++)
{
rgbaColor[i] = vis->m_geometry.m_localMaterial.m_matColor.m_rgbaColor[i];
}
}
}
}
}
else
{
if (vis && vis->m_geometry.m_hasLocalMaterial)
{
for (int i = 0; i < 4; i++)
{
rgbaColor[i] = vis->m_geometry.m_localMaterial.m_matColor.m_rgbaColor[i];
}
}
}
EGLRendererObjectArray** visualsPtr = m_data->m_swRenderInstances[orgGraphicsUniqueId];
if (visualsPtr == 0)
{
m_data->m_swRenderInstances.insert(orgGraphicsUniqueId, new EGLRendererObjectArray);
}
visualsPtr = m_data->m_swRenderInstances[orgGraphicsUniqueId];
btAssert(visualsPtr);
EGLRendererObjectArray* visuals = *visualsPtr;
visuals->m_objectUniqueId = bodyUniqueId;
visuals->m_linkIndex = linkIndex;
b3VisualShapeData visualShape;
visualShape.m_objectUniqueId = bodyUniqueId;
visualShape.m_linkIndex = linkIndex;
visualShape.m_localVisualFrame[0] = vis->m_linkLocalFrame.getOrigin()[0];
visualShape.m_localVisualFrame[1] = vis->m_linkLocalFrame.getOrigin()[1];
visualShape.m_localVisualFrame[2] = vis->m_linkLocalFrame.getOrigin()[2];
visualShape.m_localVisualFrame[3] = vis->m_linkLocalFrame.getRotation()[0];
visualShape.m_localVisualFrame[4] = vis->m_linkLocalFrame.getRotation()[1];
visualShape.m_localVisualFrame[5] = vis->m_linkLocalFrame.getRotation()[2];
visualShape.m_localVisualFrame[6] = vis->m_linkLocalFrame.getRotation()[3];
visualShape.m_rgbaColor[0] = rgbaColor[0];
visualShape.m_rgbaColor[1] = rgbaColor[1];
visualShape.m_rgbaColor[2] = rgbaColor[2];
visualShape.m_rgbaColor[3] = rgbaColor[3];
int shapeIndex = -1;
btHashVisual tmp;
{
B3_PROFILE("convertURDFToVisualShape2");
btTransform tr = localInertiaFrame.inverse() * childTrans;
tmp.m_vis = *vis;
tmp.m_tr = tr;
int* bla = m_data->m_cachedVisualShapes[tmp];
if (bla)
{
shapeIndex = *bla;
}
else
{
convertURDFToVisualShape2(vis, pathPrefix, tr, vertices, indices, textures, visualShape, fileIO, m_data->m_flags);
}
}
m_data->m_visualShapes.push_back(visualShape);
int textureIndex = -1;
if (shapeIndex < 0)
{
if (vertices.size() && indices.size())
{
unsigned char* textureImage1 = 0;
int textureWidth = 0;
int textureHeight = 0;
bool isCached = false;
if (textures.size())
{
textureImage1 = textures[0].textureData1;
textureWidth = textures[0].m_width;
textureHeight = textures[0].m_height;
isCached = textures[0].m_isCached;
int* bla = m_data->m_cachedTextureIds[textureImage1];
if (bla)
{
textureIndex = *bla;
}
else
{
textureIndex = m_data->m_instancingRenderer->registerTexture(textureImage1, textureWidth, textureHeight);
m_data->m_cachedTextureIds.insert(textureImage1, textureIndex);
}
}
}
}
{
B3_PROFILE("m_instancingRenderer register");
// register mesh to m_instancingRenderer too.
if (shapeIndex < 0)
{
shapeIndex = m_data->m_instancingRenderer->registerShape(&vertices[0].xyzw[0], vertices.size(), &indices[0], indices.size(), B3_GL_TRIANGLES, textureIndex);
m_data->m_cachedVisualShapes.insert(tmp, shapeIndex);
}
double scaling[3] = { 1, 1, 1 };
int graphicsIndex = m_data->m_instancingRenderer->registerGraphicsInstance(shapeIndex, &visualShape.m_localVisualFrame[0], &visualShape.m_localVisualFrame[3], &visualShape.m_rgbaColor[0], scaling);
int segmentationMask = bodyUniqueId + ((linkIndex + 1) << 24);
{
if (graphicsIndex >= 0)
{
visuals->m_graphicsInstanceIds.push_back(graphicsIndex);
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
m_data->m_instancingRenderer->writeTransforms();
}
for (int i = 0; i < textures.size(); i++)
{
if (!textures[i].m_isCached)
{
free(textures[i].textureData1);
}
}
}
}
return orgGraphicsUniqueId;
}
int EGLRendererVisualShapeConverter::getNumVisualShapes(int bodyUniqueId)
{
int start = -1;
//find first one, then count how many
for (int i = 0; i < m_data->m_visualShapes.size(); i++)
{
if (m_data->m_visualShapes[i].m_objectUniqueId == bodyUniqueId)
{
start = i;
break;
}
}
int count = 0;
if (start >= 0)
{
for (int i = start; i < m_data->m_visualShapes.size(); i++)
{
if (m_data->m_visualShapes[i].m_objectUniqueId == bodyUniqueId)
{
count++;
}
else
{
//storage of each visual shape for a given body unique id assumed to be contiguous
break;
}
}
}
return count;
}
int EGLRendererVisualShapeConverter::getVisualShapesData(int bodyUniqueId, int shapeIndex, struct b3VisualShapeData* shapeData)
{
int start = -1;
//find first one, then count how many
for (int i = 0; i < m_data->m_visualShapes.size(); i++)
{
if (m_data->m_visualShapes[i].m_objectUniqueId == bodyUniqueId)
{
start = i;
break;
}
}
//int count = 0;
if (start >= 0)
{
if (start + shapeIndex < m_data->m_visualShapes.size())
{
*shapeData = m_data->m_visualShapes[start + shapeIndex];
return 1;
}
}
return 0;
}
void EGLRendererVisualShapeConverter::changeRGBAColor(int bodyUniqueId, int linkIndex, int shapeIndex, const double rgbaColor[4])
{
//int start = -1;
for (int i = 0; i < m_data->m_visualShapes.size(); i++)
{
if (m_data->m_visualShapes[i].m_objectUniqueId == bodyUniqueId && m_data->m_visualShapes[i].m_linkIndex == linkIndex)
{
m_data->m_visualShapes[i].m_rgbaColor[0] = rgbaColor[0];
m_data->m_visualShapes[i].m_rgbaColor[1] = rgbaColor[1];
m_data->m_visualShapes[i].m_rgbaColor[2] = rgbaColor[2];
m_data->m_visualShapes[i].m_rgbaColor[3] = rgbaColor[3];
m_data->m_instancingRenderer->writeSingleInstanceColorToCPU(rgbaColor,i);
}
}
for (int i = 0; i < m_data->m_swRenderInstances.size(); i++)
{
EGLRendererObjectArray** ptrptr = m_data->m_swRenderInstances.getAtIndex(i);
if (ptrptr && *ptrptr)
{
float rgba[4] = {(float)rgbaColor[0], (float)rgbaColor[1], (float)rgbaColor[2], (float)rgbaColor[3]};
EGLRendererObjectArray* visuals = *ptrptr;
if ((bodyUniqueId == visuals->m_objectUniqueId) && (linkIndex == visuals->m_linkIndex))
{
}
}
}
}
void EGLRendererVisualShapeConverter::setUpAxis(int axis)
{
m_data->m_upAxis = axis;
m_data->m_camera.setCameraUpAxis(axis);
m_data->m_camera.update();
m_data->m_instancingRenderer->updateCamera();
}
void EGLRendererVisualShapeConverter::resetCamera(float camDist, float yaw, float pitch, float camPosX, float camPosY, float camPosZ)
{
m_data->m_camera.setCameraDistance(camDist);
m_data->m_camera.setCameraPitch(pitch);
m_data->m_camera.setCameraYaw(yaw);
m_data->m_camera.setCameraTargetPosition(camPosX, camPosY, camPosZ);
m_data->m_camera.setAspectRatio((float)m_data->m_swWidth / (float)m_data->m_swHeight);
m_data->m_camera.update();
}
void EGLRendererVisualShapeConverter::clearBuffers(TGAColor& clearColor)
{
float farPlane = m_data->m_camera.getCameraFrustumFar();
for (int y = 0; y < m_data->m_swHeight; ++y)
{
for (int x = 0; x < m_data->m_swWidth; ++x)
{
m_data->m_rgbColorBuffer.set(x, y, clearColor);
m_data->m_depthBuffer[x + y * m_data->m_swWidth] = -farPlane;
m_data->m_shadowBuffer[x + y * m_data->m_swWidth] = -1e30f;
m_data->m_segmentationMaskBuffer[x + y * m_data->m_swWidth] = -1;
}
}
}
void EGLRendererVisualShapeConverter::render()
{
//mode the the actual render code inside 'copyImageData' since we need to know the width/height
}
void EGLRendererVisualShapeConverter::render(const float viewMat[16], const float projMat[16])
{
// This code is very similar to that of
// PhysicsServerCommandProcessor::processRequestCameraImageCommand
// maybe code from there should be moved.
// Tiny allows rendering with viewMat, projMat explicitly, but
// GLInstancingRender calls m_activeCamera, so set this.
m_data->m_camera.setVRCamera(viewMat, projMat);
render();
m_data->m_camera.disableVRCamera();
//cout<<viewMat[4*0 + 0]<<" "<<viewMat[4*0+1]<<" "<<viewMat[4*0+2]<<" "<<viewMat[4*0+3] << endl;
//cout<<viewMat[4*1 + 0]<<" "<<viewMat[4*1+1]<<" "<<viewMat[4*1+2]<<" "<<viewMat[4*1+3] << endl;
//cout<<viewMat[4*2 + 0]<<" "<<viewMat[4*2+1]<<" "<<viewMat[4*2+2]<<" "<<viewMat[4*2+3] << endl;
//cout<<viewMat[4*3 + 0]<<" "<<viewMat[4*3+1]<<" "<<viewMat[4*3+2]<<" "<<viewMat[4*3+3] << endl;
}
void EGLRendererVisualShapeConverter::getWidthAndHeight(int& width, int& height)
{
width = m_data->m_swWidth;
height = m_data->m_swHeight;
}
void EGLRendererVisualShapeConverter::setWidthAndHeight(int width, int height)
{
m_data->m_swWidth = width;
m_data->m_swHeight = height;
m_data->m_depthBuffer.resize(m_data->m_swWidth * m_data->m_swHeight);
m_data->m_shadowBuffer.resize(m_data->m_swWidth * m_data->m_swHeight);
m_data->m_segmentationMaskBuffer.resize(m_data->m_swWidth * m_data->m_swHeight);
m_data->m_rgbColorBuffer = TGAImage(width, height, TGAImage::RGB);
}
void EGLRendererVisualShapeConverter::setProjectiveTextureMatrices(const float viewMatrix[16], const float projectionMatrix[16])
{
m_data->m_instancingRenderer->setProjectiveTextureMatrices(viewMatrix,projectionMatrix);
}
void EGLRendererVisualShapeConverter::setProjectiveTexture(bool useProjectiveTexture)
{
m_data->m_instancingRenderer->setProjectiveTexture(useProjectiveTexture);
}
//copied from OpenGLGuiHelper.cpp
void EGLRendererVisualShapeConverter::copyCameraImageDataGL(
unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels,
float* depthBuffer, int depthBufferSizeInPixels,
int* segmentationMaskBuffer, int segmentationMaskSizeInPixels,
int startPixelIndex, int* widthPtr, int* heightPtr, int* numPixelsCopied)
{
if (numPixelsCopied)
*numPixelsCopied = 0;
int destinationWidth = *widthPtr;
int destinationHeight = *heightPtr;
int sourceWidth = btMin(destinationWidth, (int)(m_data->m_window->getWidth() * m_data->m_window->getRetinaScale()));
int sourceHeight = btMin(destinationHeight, (int)(m_data->m_window->getHeight() * m_data->m_window->getRetinaScale()));
int numTotalPixels = (*widthPtr) * (*heightPtr);
int numRemainingPixels = numTotalPixels - startPixelIndex;
int numBytesPerPixel = 4; //RGBA
int numRequestedPixels = btMin(rgbaBufferSizeInPixels, numRemainingPixels);
if (1)
{
if (startPixelIndex == 0)
{
m_data->m_window->endRendering();
m_data->m_window->startRendering();
glViewport(0,0, sourceWidth*m_data->m_window->getRetinaScale(), sourceHeight*m_data->m_window->getRetinaScale());
B3_PROFILE("m_instancingRenderer render");
m_data->m_instancingRenderer->writeTransforms();
if (m_data->m_hasLightDirection)
{
m_data->m_instancingRenderer->setLightPosition(m_data->m_lightDirection);
}
m_data->m_instancingRenderer->setActiveCamera(&m_data->m_camera);
m_data->m_instancingRenderer->updateCamera(m_data->m_upAxis);
m_data->m_instancingRenderer->renderScene();
m_data->m_instancingRenderer->drawLine(b3MakeVector3(0, 0, 0), b3MakeVector3(1, 0, 0), b3MakeVector3(1, 0, 0), 3);
m_data->m_instancingRenderer->drawLine(b3MakeVector3(0, 0, 0), b3MakeVector3(0, 1, 0), b3MakeVector3(0, 1, 0), 3);
m_data->m_instancingRenderer->drawLine(b3MakeVector3(0, 0, 0), b3MakeVector3(0, 0, 1), b3MakeVector3(0, 0, 1), 3);
int numBytesPerPixel = 4; //RGBA
if (pixelsRGBA || depthBuffer)
{
{
BT_PROFILE("copy pixels");
//copy the image into our local cache
m_data->m_sourceRgbaPixelBuffer.resize(sourceWidth * sourceHeight * numBytesPerPixel);
m_data->m_sourceDepthBuffer.resize(sourceWidth * sourceHeight);
{
BT_PROFILE("getScreenPixels");
int rgbaBufferSizeInPixels = m_data->m_sourceRgbaPixelBuffer.size();
int depthBufferSizeInPixels = m_data->m_sourceDepthBuffer.size();
// Copied from SimpleOpenGL3App::getScreenPixels
b3Assert((sourceWidth * sourceHeight * 4) == rgbaBufferSizeInPixels);
//glClear(GL_COLOR_BUFFER_BIT);
//b3Warning("EGL\n");
if ((sourceWidth * sourceHeight * 4) == rgbaBufferSizeInPixels) // remove this if
{
glReadPixels(0, 0, sourceWidth, sourceHeight, GL_RGBA, GL_UNSIGNED_BYTE, &(m_data->m_sourceRgbaPixelBuffer[0]));
int glstat;
glstat = glGetError();
b3Assert(glstat == GL_NO_ERROR);
}
if ((sourceWidth * sourceHeight) == depthBufferSizeInPixels)
{
glReadPixels(0, 0, sourceWidth, sourceHeight, GL_DEPTH_COMPONENT, GL_FLOAT, &(m_data->m_sourceDepthBuffer[0]));
int glstat;
glstat = glGetError();
b3Assert(glstat == GL_NO_ERROR);
}
}
}
m_data->m_rgbaPixelBuffer1.resize((*widthPtr) * (*heightPtr) * numBytesPerPixel);
m_data->m_depthBuffer1.resize((*widthPtr) * (*heightPtr));
//rescale and flip
{
BT_PROFILE("resize and flip");
for (int j = 0; j < *heightPtr; j++)
{
for (int i = 0; i < *widthPtr; i++)
{
int xIndex = int(float(i) * (float(sourceWidth) / float(*widthPtr)));
int yIndex = int(float(*heightPtr - 1 - j) * (float(sourceHeight) / float(*heightPtr)));
btClamp(xIndex, 0, sourceWidth);
btClamp(yIndex, 0, sourceHeight);
int bytesPerPixel = 4; //RGBA
int sourcePixelIndex = (xIndex + yIndex * sourceWidth) * bytesPerPixel;
int sourceDepthIndex = xIndex + yIndex * sourceWidth;
#define COPY4PIXELS 1
#ifdef COPY4PIXELS
int* dst = (int*)&m_data->m_rgbaPixelBuffer1[(i + j * (*widthPtr)) * 4 + 0];
int* src = (int*)&m_data->m_sourceRgbaPixelBuffer[sourcePixelIndex + 0];
*dst = *src;
#else
m_data->m_rgbaPixelBuffer1[(i + j * widthPtr) * 4 + 0] = sourceRgbaPixelBuffer[sourcePixelIndex + 0];
m_data->m_rgbaPixelBuffer1[(i + j * widthPtr) * 4 + 1] = sourceRgbaPixelBuffer[sourcePixelIndex + 1];
m_data->m_rgbaPixelBuffer1[(i + j * widthPtr) * 4 + 2] = sourceRgbaPixelBuffer[sourcePixelIndex + 2];
m_data->m_rgbaPixelBuffer1[(i + j * widthPtr) * 4 + 3] = 255;
#endif
if (depthBuffer)
{
m_data->m_depthBuffer1[i + j * (*widthPtr)] = m_data->m_sourceDepthBuffer[sourceDepthIndex];
}
}
}
}
}
if (segmentationMaskBuffer)
{
{
m_data->m_window->startRendering();
glViewport(0,0, sourceWidth*m_data->m_window->getRetinaScale(), sourceHeight*m_data->m_window->getRetinaScale());
BT_PROFILE("renderScene");
m_data->m_instancingRenderer->renderSceneInternal(B3_SEGMENTATION_MASK_RENDERMODE);
}
{
BT_PROFILE("copy pixels");
//copy the image into our local cache
m_data->m_segmentationMaskSourceRgbaPixelBuffer.resize(sourceWidth * sourceHeight * numBytesPerPixel);
m_data->m_segmentationMaskSourceDepthBuffer.resize(sourceWidth * sourceHeight);
{
BT_PROFILE("getScreenPixels");
{
glReadPixels(0, 0, sourceWidth, sourceHeight, GL_DEPTH_COMPONENT, GL_FLOAT, &(m_data->m_segmentationMaskSourceDepthBuffer[0]));
int glstat;
glstat = glGetError();
b3Assert(glstat == GL_NO_ERROR);
}
{
glReadPixels(0, 0, sourceWidth, sourceHeight, GL_RGBA, GL_UNSIGNED_BYTE, &(m_data->m_segmentationMaskSourceRgbaPixelBuffer[0]));
int glstat;
glstat = glGetError();
b3Assert(glstat == GL_NO_ERROR);
}
}
}
m_data->m_segmentationMaskBuffer.resize(destinationWidth * destinationHeight, -1);
//rescale and flip
{
BT_PROFILE("resize and flip");
for (int j = 0; j < destinationHeight; j++)
{
for (int i = 0; i < destinationWidth; i++)
{
int xIndex = int(float(i) * (float(sourceWidth) / float(destinationWidth)));
int yIndex = int(float(destinationHeight - 1 - j) * (float(sourceHeight) / float(destinationHeight)));
btClamp(xIndex, 0, sourceWidth);
btClamp(yIndex, 0, sourceHeight);
int bytesPerPixel = 4; //RGBA
int sourcePixelIndex = (xIndex + yIndex * sourceWidth) * bytesPerPixel;
int sourceDepthIndex = xIndex + yIndex * sourceWidth;
if (segmentationMaskBuffer)
{
float depth = m_data->m_segmentationMaskSourceDepthBuffer[sourceDepthIndex];
if (depth < 1)
{
int segMask = m_data->m_segmentationMaskSourceRgbaPixelBuffer[sourcePixelIndex + 0] + 256 * (m_data->m_segmentationMaskSourceRgbaPixelBuffer[sourcePixelIndex + 1]) + 256 * 256 * (m_data->m_segmentationMaskSourceRgbaPixelBuffer[sourcePixelIndex + 2]);
m_data->m_segmentationMaskBuffer[i + j * destinationWidth] = segMask;
}
else
{
m_data->m_segmentationMaskBuffer[i + j * destinationWidth] = -1;
}
}
}
}
}
}
glViewport(0, 0, m_data->m_window->getWidth() * m_data->m_window->getRetinaScale(), m_data->m_window->getHeight() * m_data->m_window->getRetinaScale());
}
if (pixelsRGBA)
{
BT_PROFILE("copy rgba pixels");
for (int i = 0; i < numRequestedPixels * numBytesPerPixel; i++)
{
pixelsRGBA[i] = m_data->m_rgbaPixelBuffer1[i + startPixelIndex * numBytesPerPixel];
}
}
if (depthBuffer)
{
BT_PROFILE("copy depth buffer pixels");
for (int i = 0; i < numRequestedPixels; i++)
{
depthBuffer[i] = m_data->m_depthBuffer1[i + startPixelIndex];
}
}
if (segmentationMaskBuffer)
{
BT_PROFILE("copy segmentation mask buffer pixels");
for (int i = 0; i < numRequestedPixels; i++)
{
int graphicsIndexSegMask = m_data->m_segmentationMaskBuffer[i + startPixelIndex];
int segMask = -1;
if (graphicsIndexSegMask >= 0 && graphicsIndexSegMask < m_data->m_graphicsIndexToSegmentationMask.size())
{
segMask = m_data->m_graphicsIndexToSegmentationMask[graphicsIndexSegMask];
}
if ((m_data->m_flags & ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX) == 0)
{
if (segMask >= 0)
{
segMask &= ((1 << 24) - 1);
}
}
segmentationMaskBuffer[i] = segMask;
}
}
if (numPixelsCopied)
{
*numPixelsCopied = numRequestedPixels;
}
}
}
void EGLRendererVisualShapeConverter::copyCameraImageData(unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels,
float* depthBuffer, int depthBufferSizeInPixels,
int* segmentationMaskBuffer, int segmentationMaskSizeInPixels,
int startPixelIndex, int* widthPtr, int* heightPtr, int* numPixelsCopied)
{
B3_PROFILE("copyCameraImageDataGL");
copyCameraImageDataGL(pixelsRGBA, rgbaBufferSizeInPixels,
depthBuffer, depthBufferSizeInPixels,
segmentationMaskBuffer, segmentationMaskSizeInPixels,
startPixelIndex, widthPtr, heightPtr, numPixelsCopied);
}
void EGLRendererVisualShapeConverter::removeVisualShape(int collisionObjectUniqueId)
{
EGLRendererObjectArray** ptrptr = m_data->m_swRenderInstances[collisionObjectUniqueId];
if (ptrptr && *ptrptr)
{
EGLRendererObjectArray* ptr = *ptrptr;
if (ptr)
{
for (int i = 0; i < ptr->m_graphicsInstanceIds.size(); i++)
{
m_data->m_instancingRenderer->removeGraphicsInstance(ptr->m_graphicsInstanceIds[i]);
}
}
delete ptr;
m_data->m_swRenderInstances.remove(collisionObjectUniqueId);
}
}
void EGLRendererVisualShapeConverter::resetAll()
{
m_data->m_cachedTextureIds.clear();
for (int i = 0; i < m_data->m_swRenderInstances.size(); i++)
{
EGLRendererObjectArray** ptrptr = m_data->m_swRenderInstances.getAtIndex(i);
if (ptrptr && *ptrptr)
{
EGLRendererObjectArray* ptr = *ptrptr;
if (ptr)
{
}
delete ptr;
}
}
for (int i = 0; i < m_data->m_textures.size(); i++)
{
if (!m_data->m_textures[i].m_isCached)
{
free(m_data->m_textures[i].textureData1);
}
}
m_data->m_textures.clear();
m_data->m_swRenderInstances.clear();
m_data->m_visualShapes.clear();
m_data->m_graphicsIndexToSegmentationMask.clear();
m_data->m_instancingRenderer->removeAllInstances();
}
void EGLRendererVisualShapeConverter::changeShapeTexture(int objectUniqueId, int jointIndex, int shapeIndex, int textureUniqueId)
{
btAssert(textureUniqueId < m_data->m_textures.size());
if (textureUniqueId >= 0 && textureUniqueId < m_data->m_textures.size())
{
}
}
int EGLRendererVisualShapeConverter::registerTexture(unsigned char* texels, int width, int height)
{
MyTexture3 texData;
texData.m_width = width;
texData.m_height = height;
texData.textureData1 = texels;
texData.m_isCached = false;
m_data->m_textures.push_back(texData);
return m_data->m_textures.size() - 1;
}
int EGLRendererVisualShapeConverter::loadTextureFile(const char* filename, struct CommonFileIOInterface* fileIO)
{
B3_PROFILE("loadTextureFile");
int width, height, n;
unsigned char* image = 0;
if (fileIO)
{
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
int fileId = fileIO->fileOpen(filename,"rb");
if (fileId>=0)
{
int size = fileIO->getFileSize(fileId);
if (size>0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId,&buffer[0],size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
}
fileIO->fileClose(fileId);
}
if (buffer.size())
{
image = stbi_load_from_memory((const unsigned char*)&buffer[0], buffer.size(), &width, &height, &n, 3);
}
} else
{
image = stbi_load(filename, &width, &height, &n, 3);
}
if (image && (width >= 0) && (height >= 0))
{
return registerTexture(image, width, height);
}
return -1;
}
void EGLRendererVisualShapeConverter::syncTransform(int collisionObjectUniqueId, const btTransform& worldTransform, const btVector3& localScaling)
{
EGLRendererObjectArray** renderObjPtr = m_data->m_swRenderInstances[collisionObjectUniqueId];
if (renderObjPtr)
{
EGLRendererObjectArray* renderObj = *renderObjPtr;
renderObj->m_worldTransform = worldTransform;
renderObj->m_localScaling = localScaling;
for (int i = 0; i < renderObj->m_graphicsInstanceIds.size(); i++)
{
int graphicsInstanceId = renderObj->m_graphicsInstanceIds[i];
if (graphicsInstanceId >= 0)
{
btVector3 pos = worldTransform.getOrigin();
btQuaternion orn = worldTransform.getRotation();
m_data->m_instancingRenderer->writeSingleInstanceTransformToCPU(pos, orn, graphicsInstanceId);
}
}
}
}
bool EGLRendererVisualShapeConverter::getCameraInfo(int* width, int* height, float viewMatrix[16], float projectionMatrix[16], float camUp[3], float camForward[3], float hor[3], float vert[3], float* yaw, float* pitch, float* camDist, float cameraTarget[3]) const
{
if (m_data->m_instancingRenderer && m_data->m_instancingRenderer->getActiveCamera())
{
*width = m_data->m_window->getWidth() * m_data->m_window->getRetinaScale();
*height = m_data->m_window->getHeight() * m_data->m_window->getRetinaScale();
m_data->m_instancingRenderer->getActiveCamera()->getCameraViewMatrix(viewMatrix);
m_data->m_instancingRenderer->getActiveCamera()->getCameraProjectionMatrix(projectionMatrix);
m_data->m_instancingRenderer->getActiveCamera()->getCameraUpVector(camUp);
m_data->m_instancingRenderer->getActiveCamera()->getCameraForwardVector(camForward);
float top = 1.f;
float bottom = -1.f;
float tanFov = (top - bottom) * 0.5f / 1;
float fov = btScalar(2.0) * btAtan(tanFov);
btVector3 camPos, camTarget;
m_data->m_instancingRenderer->getActiveCamera()->getCameraPosition(camPos);
m_data->m_instancingRenderer->getActiveCamera()->getCameraTargetPosition(camTarget);
btVector3 rayFrom = camPos;
btVector3 rayForward = (camTarget - camPos);
rayForward.normalize();
float farPlane = 10000.f;
rayForward *= farPlane;
btVector3 rightOffset;
btVector3 cameraUp = btVector3(camUp[0], camUp[1], camUp[2]);
btVector3 vertical = cameraUp;
btVector3 hori;
hori = rayForward.cross(vertical);
hori.normalize();
vertical = hori.cross(rayForward);
vertical.normalize();
float tanfov = tanf(0.5f * fov);
hori *= 2.f * farPlane * tanfov;
vertical *= 2.f * farPlane * tanfov;
btScalar aspect = float(*width) / float(*height);
hori *= aspect;
//compute 'hor' and 'vert' vectors, useful to generate raytracer rays
hor[0] = hori[0] * m_data->m_window->getRetinaScale();
hor[1] = hori[1] * m_data->m_window->getRetinaScale();
hor[2] = hori[2] * m_data->m_window->getRetinaScale();
vert[0] = vertical[0] * m_data->m_window->getRetinaScale();
vert[1] = vertical[1] * m_data->m_window->getRetinaScale();
vert[2] = vertical[2] * m_data->m_window->getRetinaScale();
*yaw = m_data->m_instancingRenderer->getActiveCamera()->getCameraYaw();
*pitch = m_data->m_instancingRenderer->getActiveCamera()->getCameraPitch();
*camDist = m_data->m_instancingRenderer->getActiveCamera()->getCameraDistance();
cameraTarget[0] = camTarget[0];
cameraTarget[1] = camTarget[1];
cameraTarget[2] = camTarget[2];
return true;
}
return false;
}
| 32.375287 | 349 | 0.705057 | [
"mesh",
"geometry",
"render",
"shape",
"model"
] |
f6ed08c85cf0e5b11eacdc3a7da7413207a8c350 | 3,041 | cpp | C++ | src/parser/expression/subquery_expression.cpp | preetansh/terrier | 1d677fdbbd247ddca2ab45e09cb914c6af658ce5 | [
"MIT"
] | null | null | null | src/parser/expression/subquery_expression.cpp | preetansh/terrier | 1d677fdbbd247ddca2ab45e09cb914c6af658ce5 | [
"MIT"
] | 2 | 2020-08-24T16:29:40.000Z | 2020-09-08T16:34:51.000Z | src/parser/expression/subquery_expression.cpp | preetansh/terrier | 1d677fdbbd247ddca2ab45e09cb914c6af658ce5 | [
"MIT"
] | null | null | null | #include "parser/expression/subquery_expression.h"
#include "common/json.h"
namespace terrier::parser {
std::unique_ptr<AbstractExpression> SubqueryExpression::Copy() const {
std::vector<common::ManagedPointer<AbstractExpression>> select_columns;
for (const auto &col : subselect_->GetSelectColumns()) {
select_columns.emplace_back(common::ManagedPointer(col));
}
auto group_by = subselect_->GetSelectGroupBy() == nullptr ? nullptr : subselect_->GetSelectGroupBy()->Copy();
auto order_by = subselect_->GetSelectOrderBy() == nullptr ? nullptr : subselect_->GetSelectOrderBy()->Copy();
auto limit = subselect_->GetSelectLimit() == nullptr ? nullptr : subselect_->GetSelectLimit()->Copy();
auto parser_select = std::make_unique<SelectStatement>(
std::move(select_columns), subselect_->IsSelectDistinct(), subselect_->GetSelectTable()->Copy(),
subselect_->GetSelectCondition(), std::move(group_by), std::move(order_by), std::move(limit));
auto expr = std::make_unique<SubqueryExpression>(std::move(parser_select));
expr->SetMutableStateForCopy(*this);
return expr;
}
int SubqueryExpression::DeriveDepth() {
int current_depth = this->GetDepth();
for (auto &select_elem : subselect_->GetSelectColumns()) {
int select_depth = select_elem->DeriveDepth();
if (select_depth >= 0 && (current_depth == -1 || select_depth < current_depth)) {
this->SetDepth(select_depth);
current_depth = select_depth;
}
}
auto where = subselect_->GetSelectCondition();
if (where != nullptr) {
auto where_depth = const_cast<parser::AbstractExpression *>(where.Get())->DeriveDepth();
if (where_depth >= 0 && where_depth < current_depth) this->SetDepth(where_depth);
}
return this->GetDepth();
}
common::hash_t SubqueryExpression::Hash() const {
common::hash_t hash = AbstractExpression::Hash();
for (auto select_elem : subselect_->GetSelectColumns()) {
hash = common::HashUtil::CombineHashes(hash, select_elem->Hash());
}
hash = common::HashUtil::CombineHashes(hash, common::HashUtil::Hash(subselect_->IsSelectDistinct()));
if (subselect_->GetSelectCondition() != nullptr)
hash = common::HashUtil::CombineHashes(hash, subselect_->GetSelectCondition()->Hash());
return hash;
}
nlohmann::json SubqueryExpression::ToJson() const {
nlohmann::json j = AbstractExpression::ToJson();
j["subselect"] = subselect_->ToJson();
return j;
}
std::vector<std::unique_ptr<AbstractExpression>> SubqueryExpression::FromJson(const nlohmann::json &j) {
std::vector<std::unique_ptr<AbstractExpression>> exprs;
auto e1 = AbstractExpression::FromJson(j);
exprs.insert(exprs.end(), std::make_move_iterator(e1.begin()), std::make_move_iterator(e1.end()));
subselect_ = std::make_unique<parser::SelectStatement>();
auto e2 = subselect_->FromJson(j.at("subselect"));
exprs.insert(exprs.end(), std::make_move_iterator(e2.begin()), std::make_move_iterator(e2.end()));
return exprs;
}
DEFINE_JSON_BODY_DECLARATIONS(SubqueryExpression);
} // namespace terrier::parser
| 41.657534 | 111 | 0.726077 | [
"vector"
] |
f6eecd62c4b99f18cb5d7128522f5307f8d5c3d5 | 263 | cpp | C++ | AutoJoin/test.cpp | JateNensvold/logcabin | 6966ab07e8780de4ee2c706df4c2530922f7d265 | [
"ISC"
] | null | null | null | AutoJoin/test.cpp | JateNensvold/logcabin | 6966ab07e8780de4ee2c706df4c2530922f7d265 | [
"ISC"
] | null | null | null | AutoJoin/test.cpp | JateNensvold/logcabin | 6966ab07e8780de4ee2c706df4c2530922f7d265 | [
"ISC"
] | null | null | null | #include "autojoin.cpp"
int main(void)
{
autojoin testobject = autojoin();
vector<string> test = testobject.parseString("127.0.0.1:1552", ':');
for(int index = 0; index < (int)test.size(); index++)
{
cout << test[index] << endl;
}
} | 20.230769 | 72 | 0.577947 | [
"vector"
] |
f6f158a73be42ea2602811ad64a2a2c655dab088 | 27,881 | cc | C++ | tensorflow/compiler/tf2xla/kernels/pooling_ops.cc | Zwysilence/tensorflow | b55001be83da044bb21d539d433dec6231eaec55 | [
"Apache-2.0"
] | 3 | 2018-09-25T00:35:34.000Z | 2018-09-25T00:38:06.000Z | tensorflow/compiler/tf2xla/kernels/pooling_ops.cc | Zwysilence/tensorflow | b55001be83da044bb21d539d433dec6231eaec55 | [
"Apache-2.0"
] | 1 | 2018-09-04T07:44:56.000Z | 2018-09-04T07:44:56.000Z | tensorflow/compiler/tf2xla/kernels/pooling_ops.cc | Zwysilence/tensorflow | b55001be83da044bb21d539d433dec6231eaec55 | [
"Apache-2.0"
] | 2 | 2020-03-04T13:59:48.000Z | 2020-03-09T13:11:45.000Z | /* Copyright 2017 The TensorFlow 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.
==============================================================================*/
// XLA specific pooling ops.
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/pooling.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/conv_grad_ops.h"
#include "tensorflow/core/kernels/pooling_ops_common.h"
namespace tensorflow {
namespace {
// Superclass of pooling ops.
class PoolingOp : public XlaOpKernel {
public:
PoolingOp(OpKernelConstruction* ctx, int num_spatial_dims,
const DataType reduction_type)
: XlaOpKernel(ctx),
num_spatial_dims_(num_spatial_dims),
reduction_type_(reduction_type) {
if (ctx->num_inputs() == 1) {
std::vector<int32> ksize_int;
std::vector<int32> stride_int;
OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_int));
OP_REQUIRES(ctx, ksize_int.size() == num_dims(),
errors::InvalidArgument("Sliding window ksize field must "
"specify ",
num_dims(), " dimensions"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_int));
OP_REQUIRES(ctx, stride_int.size() == num_dims(),
errors::InvalidArgument("Sliding window stride field must "
"specify ",
num_dims(), " dimensions"));
for (int i = 0; i < num_dims(); ++i) {
ksize_.push_back(ksize_int[i]);
stride_.push_back(stride_int[i]);
}
}
Padding padding;
OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding));
padding_ = (padding == VALID) ? xla::Padding::kValid : xla::Padding::kSame;
OP_REQUIRES_OK(
ctx, DataTypeToPrimitiveType(reduction_type_, &xla_reduction_type_));
}
int num_dims() const { return num_spatial_dims_ + 2; }
protected:
xla::StatusOr<std::vector<int64>> GetKernelSize(XlaOpKernelContext* ctx) {
if (ctx->num_inputs() == 1) {
return ksize_;
}
const TensorShape ksize_shape = ctx->InputShape(1);
// Validate input sizes.
if (!TensorShapeUtils::IsVector(ksize_shape)) {
return errors::InvalidArgument("ksize must be a vector, not shape ",
ksize_shape.DebugString());
}
if (ksize_shape.num_elements() != num_dims()) {
return errors::InvalidArgument(
"Sliding window ksize field must "
"specify ",
num_dims(), " dimensions");
}
std::vector<int64> ksize;
auto status = ctx->ConstantInputAsIntVector(1, &ksize);
if (!status.ok()) {
return status;
}
return ksize;
}
xla::StatusOr<std::vector<int64>> GetStride(XlaOpKernelContext* ctx) {
if (ctx->num_inputs() == 1) {
return stride_;
}
const TensorShape stride_shape = ctx->InputShape(2);
// Validate input sizes.
if (!TensorShapeUtils::IsVector(stride_shape)) {
return errors::InvalidArgument("stride must be a vector, not shape ",
stride_shape.DebugString());
}
if (stride_shape.num_elements() != num_dims()) {
return errors::InvalidArgument(
"Sliding window stride field must "
"specify ",
num_dims(), " dimensions");
}
std::vector<int64> stride;
auto status = ctx->ConstantInputAsIntVector(2, &stride);
if (!status.ok()) {
return status;
}
return stride;
}
protected:
const int num_spatial_dims_;
std::vector<int64> ksize_;
std::vector<int64> stride_;
xla::Padding padding_;
TensorFormat data_format_ = FORMAT_NHWC;
DataType reduction_type_;
xla::PrimitiveType xla_reduction_type_;
};
// Converts the tensor data format to the one required by the XLA pooling
// library.
xla::TensorFormat XlaTensorFormat(tensorflow::TensorFormat data_format,
int num_spatial_dims) {
int num_dims = num_spatial_dims + 2;
int batch_dimension = GetTensorBatchDimIndex(num_dims, data_format);
int feature_dimension = GetTensorFeatureDimIndex(num_dims, data_format);
gtl::InlinedVector<int64, 4> spatial_dimensions(num_spatial_dims);
for (int spatial_dim = 0; spatial_dim < num_spatial_dims; ++spatial_dim) {
spatial_dimensions[spatial_dim] =
GetTensorSpatialDimIndex(num_dims, data_format, spatial_dim);
}
return xla::TensorFormat(/*batch_dimension=*/batch_dimension,
/*feature_dimension=*/feature_dimension,
/*spatial_dimensions=*/spatial_dimensions);
}
class MaxPoolOp : public PoolingOp {
public:
MaxPoolOp(OpKernelConstruction* ctx, int num_spatial_dims)
: PoolingOp(ctx, /*num_spatial_dims=*/num_spatial_dims,
/*reduction_type=*/ctx->input_type(0)) {}
void Compile(XlaOpKernelContext* ctx) override {
auto ksize_or_error = GetKernelSize(ctx);
OP_REQUIRES_OK(ctx, ksize_or_error.status());
std::vector<int64> ksize = ksize_or_error.ValueOrDie();
auto stride_or_error = GetStride(ctx);
OP_REQUIRES_OK(ctx, stride_or_error.status());
std::vector<int64> stride = stride_or_error.ValueOrDie();
const TensorShape input_shape = ctx->InputShape(0);
OP_REQUIRES(ctx, input_shape.dims() == num_dims(),
errors::InvalidArgument("Input to ", type_string(),
" operator must have ", num_dims(),
" dimensions"));
auto pooling =
xla::MaxPool(ctx->Input(0), ksize, stride, padding_,
XlaTensorFormat(data_format_, input_shape.dims() - 2));
ctx->SetOutput(0, pooling);
}
};
class MaxPool2DOp : public MaxPoolOp {
public:
explicit MaxPool2DOp(OpKernelConstruction* ctx)
: MaxPoolOp(ctx, /*num_spatial_dims=*/2) {
string data_format_str;
OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str));
OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_),
errors::InvalidArgument("Invalid data format"));
}
};
REGISTER_XLA_OP(Name("MaxPool"), MaxPool2DOp);
REGISTER_XLA_OP(Name("MaxPoolV2")
.CompileTimeConstInput("ksize")
.CompileTimeConstInput("strides"),
MaxPool2DOp);
class MaxPool3DOp : public MaxPoolOp {
public:
explicit MaxPool3DOp(OpKernelConstruction* ctx)
: MaxPoolOp(ctx, /*num_spatial_dims=*/3) {}
};
REGISTER_XLA_OP(Name("MaxPool3D"), MaxPool3DOp);
class AvgPoolOp : public PoolingOp {
public:
AvgPoolOp(OpKernelConstruction* ctx, int num_spatial_dims)
: PoolingOp(ctx, /*num_spatial_dims=*/num_spatial_dims,
/*reduction_type=*/
XlaHelpers::SumAccumulationType(ctx->input_type(0))) {}
void Compile(XlaOpKernelContext* ctx) override {
auto ksize_or_error = GetKernelSize(ctx);
OP_REQUIRES_OK(ctx, ksize_or_error.status());
std::vector<int64> ksize = ksize_or_error.ValueOrDie();
auto stride_or_error = GetStride(ctx);
OP_REQUIRES_OK(ctx, stride_or_error.status());
std::vector<int64> stride = stride_or_error.ValueOrDie();
const TensorShape input_shape = ctx->InputShape(0);
OP_REQUIRES(ctx, input_shape.dims() == num_dims(),
errors::InvalidArgument("Input to ", type_string(),
" operator must have ", num_dims(),
" dimensions"));
auto xla_data_format =
XlaTensorFormat(data_format_, input_shape.dims() - 2);
auto spatial_padding = MakeSpatialPadding(
input_shape.dim_sizes(), ksize, stride, padding_, xla_data_format);
// Convert the input to the reduction type.
auto converted_input =
ConvertElementType(ctx->Input(0), xla_reduction_type_);
auto pooling =
xla::AvgPool(converted_input, ksize, stride, spatial_padding,
xla_data_format, padding_ == xla::Padding::kValid);
// Convert the pooling result back to the input type before returning it.
ctx->SetOutput(0, ConvertElementType(pooling, ctx->input_xla_type(0)));
}
};
class AvgPool2DOp : public AvgPoolOp {
public:
explicit AvgPool2DOp(OpKernelConstruction* ctx)
: AvgPoolOp(ctx, /*num_spatial_dims=*/2) {
string data_format_str;
OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str));
OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_),
errors::InvalidArgument("Invalid data format"));
}
};
REGISTER_XLA_OP(Name("AvgPool"), AvgPool2DOp);
class AvgPool3DOp : public AvgPoolOp {
public:
explicit AvgPool3DOp(OpKernelConstruction* ctx)
: AvgPoolOp(ctx, /*num_spatial_dims=*/3) {}
};
REGISTER_XLA_OP(Name("AvgPool3D"), AvgPool3DOp);
// The operation to compute MaxPool gradients.
// It takes three inputs:
// - The original input tensor
// - The original output tensor
// - Backprop tensor for output
// It produces one output: backprop tensor for input.
class MaxPoolGradOp : public XlaOpKernel {
public:
MaxPoolGradOp(OpKernelConstruction* ctx, int num_spatial_dims)
: XlaOpKernel(ctx), num_spatial_dims_(num_spatial_dims) {
if (ctx->num_inputs() == 3) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_));
}
OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_));
}
int num_dims() const { return num_spatial_dims_ + 2; }
void Compile(XlaOpKernelContext* ctx) override {
if (ctx->num_inputs() != 3) {
OP_REQUIRES(
ctx, ctx->num_inputs() == 5,
errors::InvalidArgument("Must supply ksize and stride arguments."));
const TensorShape ksize_shape = ctx->InputShape(3);
// Validate input sizes.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ksize_shape),
errors::InvalidArgument("ksize must be a vector, not shape ",
ksize_shape.DebugString()));
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(3, &ksize_));
const TensorShape stride_shape = ctx->InputShape(4);
// Validate input sizes.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(stride_shape),
errors::InvalidArgument("stride must be a vector, not shape ",
stride_shape.DebugString()));
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(4, &stride_));
}
OP_REQUIRES(ctx, ksize_.size() == num_dims(),
errors::InvalidArgument("Sliding window ksize field must "
"specify ",
num_dims(), " dimensions"));
OP_REQUIRES(ctx, stride_.size() == num_dims(),
errors::InvalidArgument("Sliding window strides field must "
"specify ",
num_dims(), " dimensions"));
const TensorShape tensor_in_shape = ctx->InputShape(0);
const TensorShape tensor_out_shape = ctx->InputShape(1);
const TensorShape out_backprop_shape = ctx->InputShape(2);
// For maxpooling, tensor_in should have num_dims() dimensions.
OP_REQUIRES(ctx, tensor_in_shape.dims() == num_dims(),
errors::InvalidArgument("tensor_in must be ", num_dims(),
"-dimensional"));
OP_REQUIRES(ctx, tensor_out_shape.dims() == num_dims(),
errors::InvalidArgument("tensor_out must be ", num_dims(),
"-dimensional"));
// For maxpooling, out_backprop should have num_dims() dimensions.
OP_REQUIRES(ctx, out_backprop_shape.dims() == num_dims(),
errors::InvalidArgument("out_backprop must be ", num_dims(),
"-dimensional"));
// TODO(phawkins): The XLA version doesn't need tensor_out. Investigate
// whether this is a good time/space tradeoff.
auto input = ctx->Input(0);
auto out_backprop = ctx->Input(2);
xla::Padding xla_padding =
(padding_ == VALID) ? xla::Padding::kValid : xla::Padding::kSame;
xla::PrimitiveType element_type;
OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(input_type(2), &element_type));
xla::XlaOp init_value = XlaHelpers::Zero(ctx->builder(), input_type(2));
auto select = CreateScalarGeComputation(element_type, ctx->builder());
auto scatter = CreateScalarAddComputation(element_type, ctx->builder());
xla::XlaOp gradients =
xla::SelectAndScatter(input, select, ksize_, stride_, xla_padding,
out_backprop, init_value, scatter);
ctx->SetOutput(0, gradients);
}
protected:
const int num_spatial_dims_;
std::vector<int64> ksize_;
std::vector<int64> stride_;
Padding padding_;
TensorFormat data_format_ = FORMAT_NHWC;
};
class MaxPool2DGradOp : public MaxPoolGradOp {
public:
explicit MaxPool2DGradOp(OpKernelConstruction* ctx)
: MaxPoolGradOp(ctx, /*num_spatial_dims=*/2) {
string data_format;
OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format));
OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_),
errors::InvalidArgument("Invalid data format"));
}
};
REGISTER_XLA_OP(Name("MaxPoolGrad"), MaxPool2DGradOp);
REGISTER_XLA_OP(Name("MaxPoolGradV2")
.CompileTimeConstInput("ksize")
.CompileTimeConstInput("strides"),
MaxPool2DGradOp);
class MaxPool3DGradOp : public MaxPoolGradOp {
public:
explicit MaxPool3DGradOp(OpKernelConstruction* ctx)
: MaxPoolGradOp(ctx, /*num_spatial_dims=*/3) {}
};
REGISTER_XLA_OP(Name("MaxPool3DGrad"), MaxPool3DGradOp);
// Average-pooling gradient
class AvgPoolGradOp : public XlaOpKernel {
public:
AvgPoolGradOp(OpKernelConstruction* ctx, int num_spatial_dims)
: XlaOpKernel(ctx), num_spatial_dims_(num_spatial_dims) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_));
OP_REQUIRES(ctx, ksize_.size() == num_dims(),
errors::InvalidArgument("Sliding window ksize field must "
"specify ",
num_dims(), " dimensions"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_));
OP_REQUIRES(ctx, stride_.size() == num_dims(),
errors::InvalidArgument("Sliding window strides field must "
"specify ",
num_dims(), " dimensions"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_));
OP_REQUIRES(ctx, ksize_[0] == 1 && stride_[0] == 1,
errors::Unimplemented(
"Pooling is not yet supported on the batch dimension."));
}
int num_dims() const { return num_spatial_dims_ + 2; }
void Compile(XlaOpKernelContext* ctx) override {
TensorShape gradients_shape;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &gradients_shape));
const TensorShape out_backprop_shape = ctx->InputShape(1);
// For avgpooling, tensor_in_shape should have num_dims() dimensions.
OP_REQUIRES(ctx, gradients_shape.dims() == num_dims(),
errors::InvalidArgument("orig_input_shape must be ", num_dims(),
"-dimensional"));
// For avgpooling, out_backprop should have num_dims() dimensions.
OP_REQUIRES(ctx, out_backprop_shape.dims() == num_dims(),
errors::InvalidArgument("out_backprop must be ", num_dims(),
"-dimensional"));
auto out_backprop = ctx->Input(1);
std::vector<int64> stride_int64s(stride_.begin(), stride_.end());
xla::Padding xla_padding =
(padding_ == VALID) ? xla::Padding::kValid : xla::Padding::kSame;
xla::PrimitiveType xla_reduction_type;
auto reduction_type = XlaHelpers::SumAccumulationType(ctx->input_type(1));
OP_REQUIRES_OK(
ctx, DataTypeToPrimitiveType(reduction_type, &xla_reduction_type));
auto converted_out_backprop =
xla::ConvertElementType(out_backprop, xla_reduction_type);
auto xla_data_format =
XlaTensorFormat(data_format_, gradients_shape.dims() - 2);
auto padding_values =
MakeSpatialPadding(gradients_shape.dim_sizes(), ksize_, stride_int64s,
xla_padding, xla_data_format);
auto in_backprop =
xla::AvgPoolGrad(converted_out_backprop, gradients_shape.dim_sizes(),
ksize_, stride_int64s, padding_values, xla_data_format,
/*counts_include_padding=*/padding_ == VALID);
// Convert the pooling result back to the input type before returning it.
xla::PrimitiveType xla_out_backprop_type;
OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(ctx->input_type(1),
&xla_out_backprop_type));
ctx->SetOutput(0,
xla::ConvertElementType(in_backprop, xla_out_backprop_type));
}
protected:
const int num_spatial_dims_;
std::vector<int64> ksize_;
std::vector<int32> stride_;
Padding padding_;
TensorFormat data_format_ = FORMAT_NHWC;
};
class AvgPool2DGradOp : public AvgPoolGradOp {
public:
explicit AvgPool2DGradOp(OpKernelConstruction* ctx)
: AvgPoolGradOp(ctx, /*num_spatial_dims=*/2) {
string data_format;
OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format));
OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_),
errors::InvalidArgument("Invalid data format"));
}
};
REGISTER_XLA_OP(Name("AvgPoolGrad").CompileTimeConstInput("orig_input_shape"),
AvgPool2DGradOp);
class AvgPool3DGradOp : public AvgPoolGradOp {
public:
explicit AvgPool3DGradOp(OpKernelConstruction* ctx)
: AvgPoolGradOp(ctx, /*num_spatial_dims=*/3) {}
};
REGISTER_XLA_OP(Name("AvgPool3DGrad").CompileTimeConstInput("orig_input_shape"),
AvgPool3DGradOp);
class MaxPoolGradGradOp : public XlaOpKernel {
public:
MaxPoolGradGradOp(OpKernelConstruction* ctx, int num_spatial_dims)
: XlaOpKernel(ctx), num_spatial_dims_(num_spatial_dims) {
if (ctx->num_inputs() == 3) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_));
}
OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_));
}
int num_dims() const { return num_spatial_dims_ + 2; }
void Compile(XlaOpKernelContext* ctx) override {
if (ctx->num_inputs() != 3) {
OP_REQUIRES(
ctx, ctx->num_inputs() == 5,
errors::InvalidArgument("Must supply ksize and stride arguments."));
const TensorShape ksize_shape = ctx->InputShape(3);
// Validate input sizes.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ksize_shape),
errors::InvalidArgument("ksize must be a vector, not shape ",
ksize_shape.DebugString()));
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(3, &ksize_));
const TensorShape stride_shape = ctx->InputShape(4);
// Validate input sizes.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(stride_shape),
errors::InvalidArgument("stride must be a vector, not shape ",
stride_shape.DebugString()));
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(4, &stride_));
}
OP_REQUIRES(ctx, ksize_.size() == num_dims(),
errors::InvalidArgument("Sliding window ksize field must "
"specify ",
num_dims(), " dimensions"));
OP_REQUIRES(ctx, stride_.size() == num_dims(),
errors::InvalidArgument("Sliding window strides field must "
"specify ",
num_dims(), " dimensions"));
const TensorShape tensor_in_shape = ctx->InputShape(0);
const TensorShape tensor_out_shape = ctx->InputShape(1);
const TensorShape out_backprop_shape = ctx->InputShape(2);
// For maxpooling, tensor_in should have num_dims() dimensions.
OP_REQUIRES(ctx, tensor_in_shape.dims() == num_dims(),
errors::InvalidArgument("tensor_in must be ", num_dims(),
"-dimensional"));
OP_REQUIRES(ctx, tensor_out_shape.dims() == num_dims(),
errors::InvalidArgument("tensor_out must be ", num_dims(),
"-dimensional"));
// For maxpooling, out_backprop should have num_dims() dimensions.
OP_REQUIRES(ctx, out_backprop_shape.dims() == num_dims(),
errors::InvalidArgument("out_backprop must be ", num_dims(),
"-dimensional"));
// What we want to compute:
// Given y = MaxPool(x), and xs_grad = MaxPoolGrad(x, y, ys_grad)
// MaxPoolGradGrad computes {ys_grad}_grad given x, y, and {xs_grad}_grad.
//
// In the regular TF op, this amounts to selecting for each window the
// incoming backprop value from xs_grad_grad that corresponds to the maximal
// value in the corresponding window of x.
//
// TODO(b/73062247): What we really want is a ReduceWindow with different
// arrays for index selection vs return value selection--a select-to-gather.
//
// Here, we implement a bitwise hack: we use the hi 16 bits of input for
// separate max pooling alongside each of the hi and lo 16 bits of
// out_backprop packed into 16 lo bits, which we then glue back together at
// the end to get a full 32 bits of gradient.
//
// This could select the wrong backprop value for two x values that are
// equally maximal up to the first 16 bits, in which case we are taking the
// latter.
//
// Note that in principle we could use 32 separate maxpools to recover each
// of 32 bits of the gradient while preserving 31 bits of input for the max
// pooling criteria; here, we just truncate to the first 16 bits of input.
auto input = ctx->Input(0);
auto out_backprop = ctx->Input(2);
auto b = ctx->builder();
auto sixteen = xla::ConstantR0<uint32>(b, 16);
// in (f32) -> round to bf16 -> f32 for correct bitwidth -> 16-high-bit u32
auto in_hi = xla::BitcastConvertType(
xla::ConvertElementType(xla::ConvertElementType(input, xla::BF16),
xla::F32),
xla::U32);
auto bp_int = xla::BitcastConvertType(out_backprop, xla::U32);
auto bp_hi = xla::ShiftRightLogical(bp_int, sixteen);
auto bp_lo =
xla::ShiftRightLogical(xla::ShiftLeft(bp_int, sixteen), sixteen);
auto in_hi_bp_hi = xla::Add(in_hi, bp_hi); // Want an unsigned add.
auto in_hi_bp_lo = xla::Add(in_hi, bp_lo); // Want an unsigned add.
auto init_value = xla::MinValue(b, xla::F32);
// We will reduce by taking the maximal value up to 16 bits (ignoring the lo
// 16 bits of packed-in hi/lo backprop value).
auto rb = b->CreateSubBuilder("GreaterOrEqOf_ByFirst16Bits");
{
// F32 parameters to satisfy lowering type restriction for reduce opcode.
const xla::Shape scalar = xla::ShapeUtil::MakeShape(xla::F32, {});
auto lhs = xla::Parameter(rb.get(), 0, scalar, "lhs");
auto rhs = xla::Parameter(rb.get(), 1, scalar, "rhs");
auto sixteen = xla::ConstantR0<int32>(rb.get(), 16);
auto lhs_criteria =
xla::ShiftLeft(xla::ShiftRightLogical(
xla::BitcastConvertType(lhs, xla::S32), sixteen),
sixteen);
auto rhs_criteria =
xla::ShiftLeft(xla::ShiftRightLogical(
xla::BitcastConvertType(rhs, xla::S32), sixteen),
sixteen);
// Must use a F32 comparison, because S32 would not work for negatives.
xla::Select(xla::Ge(xla::BitcastConvertType(lhs_criteria, xla::F32),
xla::BitcastConvertType(rhs_criteria, xla::F32)),
lhs, rhs);
}
auto reduce = rb->BuildAndNoteError();
xla::Padding xla_padding =
(padding_ == VALID) ? xla::Padding::kValid : xla::Padding::kSame;
auto pooled_hi =
xla::ReduceWindow(xla::BitcastConvertType(in_hi_bp_hi, xla::F32),
init_value, reduce, ksize_, stride_, xla_padding);
auto pooled_lo =
xla::ReduceWindow(xla::BitcastConvertType(in_hi_bp_lo, xla::F32),
init_value, reduce, ksize_, stride_, xla_padding);
auto grads_hi =
xla::ShiftLeft(xla::BitcastConvertType(pooled_hi, xla::U32), sixteen);
auto grads_lo = xla::ShiftRightLogical(
xla::ShiftLeft(xla::BitcastConvertType(pooled_lo, xla::U32), sixteen),
sixteen);
auto grads = xla::Add(grads_hi, grads_lo); // Want an unsigned add.
xla::PrimitiveType element_type;
OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(input_type(2), &element_type));
ctx->SetOutput(0, xla::BitcastConvertType(grads, element_type));
}
protected:
const int num_spatial_dims_;
std::vector<int64> ksize_;
std::vector<int64> stride_;
Padding padding_;
TensorFormat data_format_ = FORMAT_NHWC;
};
class MaxPool2DGradGradOp : public MaxPoolGradGradOp {
public:
explicit MaxPool2DGradGradOp(OpKernelConstruction* ctx)
: MaxPoolGradGradOp(ctx, /*num_spatial_dims=*/2) {
string data_format;
OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format));
OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_),
errors::InvalidArgument("Invalid data format"));
}
};
REGISTER_XLA_OP(Name("MaxPoolGradGrad").TypeConstraint("T", DT_FLOAT),
MaxPool2DGradGradOp);
REGISTER_XLA_OP(Name("MaxPoolGradGradV2")
.TypeConstraint("T", DT_FLOAT)
.CompileTimeConstInput("ksize")
.CompileTimeConstInput("strides"),
MaxPool2DGradGradOp);
class MaxPool3DGradGradOp : public MaxPoolGradGradOp {
public:
explicit MaxPool3DGradGradOp(OpKernelConstruction* ctx)
: MaxPoolGradGradOp(ctx, /*num_spatial_dims=*/3) {
string data_format;
OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format));
OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_),
errors::InvalidArgument("Invalid data format"));
}
};
REGISTER_XLA_OP(Name("MaxPool3DGradGrad").TypeConstraint("T", DT_FLOAT),
MaxPool3DGradGradOp);
} // anonymous namespace
} // namespace tensorflow
| 42.631498 | 80 | 0.645278 | [
"shape",
"vector"
] |
f6f400ff5bb3e0c033ca940f6564935c7c2a197c | 2,362 | cpp | C++ | app/src/main/jni/liveMedia/ADTSAudioFileServerMediaSubsession.cpp | Key-CN/Live555Porting-for-Android | db8b7b46fbc3dcf166c85cf3ec8b4cd04c3e2150 | [
"Apache-2.0"
] | 24 | 2017-08-10T16:33:03.000Z | 2022-03-25T16:18:18.000Z | app/src/main/jni/liveMedia/ADTSAudioFileServerMediaSubsession.cpp | Key-CN/Live555Porting-for-Android | db8b7b46fbc3dcf166c85cf3ec8b4cd04c3e2150 | [
"Apache-2.0"
] | 6 | 2017-11-01T09:58:05.000Z | 2020-10-17T13:17:48.000Z | app/src/main/jni/liveMedia/ADTSAudioFileServerMediaSubsession.cpp | Key-CN/Live555Porting-for-Android | db8b7b46fbc3dcf166c85cf3ec8b4cd04c3e2150 | [
"Apache-2.0"
] | 11 | 2017-08-28T13:02:43.000Z | 2021-04-15T07:19:02.000Z | /**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2017 Live Networks, Inc. All rights reserved.
// A 'ServerMediaSubsession' object that creates new, unicast, "RTPSink"s
// on demand, from an AAC audio file in ADTS format
// Implementation
#include "ADTSAudioFileServerMediaSubsession.hh"
#include "ADTSAudioFileSource.hh"
#include "MPEG4GenericRTPSink.hh"
ADTSAudioFileServerMediaSubsession*
ADTSAudioFileServerMediaSubsession::createNew(UsageEnvironment& env,
char const* fileName,
Boolean reuseFirstSource) {
return new ADTSAudioFileServerMediaSubsession(env, fileName, reuseFirstSource);
}
ADTSAudioFileServerMediaSubsession
::ADTSAudioFileServerMediaSubsession(UsageEnvironment& env,
char const* fileName, Boolean reuseFirstSource)
: FileServerMediaSubsession(env, fileName, reuseFirstSource) {
}
ADTSAudioFileServerMediaSubsession
::~ADTSAudioFileServerMediaSubsession() {
}
FramedSource* ADTSAudioFileServerMediaSubsession
::createNewStreamSource(unsigned /*clientSessionId*/, unsigned& estBitrate) {
estBitrate = 96; // kbps, estimate
return ADTSAudioFileSource::createNew(envir(), fFileName);
}
RTPSink* ADTSAudioFileServerMediaSubsession
::createNewRTPSink(Groupsock* rtpGroupsock,
unsigned char rtpPayloadTypeIfDynamic,
FramedSource* inputSource) {
ADTSAudioFileSource* adtsSource = (ADTSAudioFileSource*)inputSource;
return MPEG4GenericRTPSink::createNew(envir(), rtpGroupsock,
rtpPayloadTypeIfDynamic,
adtsSource->samplingFrequency(),
"audio", "AAC-hbr", adtsSource->configStr(),
adtsSource->numChannels());
}
| 38.721311 | 81 | 0.779848 | [
"object"
] |
f6f58d5d6422a2af671cb319bd56d1755edfd777 | 866 | cpp | C++ | src/roq/samples/import/application.cpp | roq-trading/examples | 1e8ac9f5a960378ae4dc4d4a6b83f8daf6a65cba | [
"BSD-3-Clause"
] | null | null | null | src/roq/samples/import/application.cpp | roq-trading/examples | 1e8ac9f5a960378ae4dc4d4a6b83f8daf6a65cba | [
"BSD-3-Clause"
] | null | null | null | src/roq/samples/import/application.cpp | roq-trading/examples | 1e8ac9f5a960378ae4dc4d4a6b83f8daf6a65cba | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2017-2022, Hans Erik Thrane */
#include "roq/samples/import/application.hpp"
#include <stdexcept>
#include <vector>
#include "roq/exceptions.hpp"
#include "roq/samples/import/processor.hpp"
using namespace std::literals;
namespace roq {
namespace samples {
namespace import {
int Application::main_helper(const std::span<std::string_view> &args) {
if (std::size(args) != 2)
log::fatal("Expected exactly 1 argument, got {}"sv, std::size(args) - 1);
Processor(args[1]).dispatch();
return EXIT_SUCCESS;
}
int Application::main(int argc, char **argv) {
// wrap arguments (prefer to not work with raw pointers)
std::vector<std::string_view> args;
args.reserve(argc);
for (int i = 0; i < argc; ++i)
args.emplace_back(argv[i]);
return main_helper(args);
}
} // namespace import
} // namespace samples
} // namespace roq
| 23.405405 | 77 | 0.691686 | [
"vector"
] |
f6f5fc1531ffb942a1d740becfb820fcb69f37f9 | 38,438 | cc | C++ | CCA/Components/Models/Radiation/RMCRT/RMCRTCommon.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 3 | 2020-06-10T08:21:31.000Z | 2020-06-23T18:33:16.000Z | CCA/Components/Models/Radiation/RMCRT/RMCRTCommon.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | null | null | null | CCA/Components/Models/Radiation/RMCRT/RMCRTCommon.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 2 | 2019-12-30T05:48:30.000Z | 2020-02-12T16:24:16.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2019 The University of Utah
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
//______________________________________________________________________
//
#include <CCA/Components/Models/Radiation/RMCRT/RMCRTCommon.h>
#include <Core/Grid/DbgOutput.h>
#include <Core/Grid/Variables/PerPatch.h>
#include <Core/Math/MersenneTwister.h>
#include <Core/Util/DOUT.hpp>
#include <fstream>
#define DEBUG -9 // 1: divQ, 2: boundFlux, 3: scattering
#define FIXED_RAY_DIR -9 // Sets ray direction. 1: (0.7071,0.7071, 0), 2: (0.7071, 0, 0.7071), 3: (0, 0.7071, 0.7071)
// 4: (0.7071, 0.7071, 7071), 5: (1,0,0) 6: (0, 1, 0), 7: (0,0,1)
#define SIGN 1 // Multiply the FIXED_RAY_DIRs by value
#define FUZZ 1e-12 // numerical fuzz
//#define FAST_EXP // This uses a fast approximate exp() function that is
// significantly faster.
//______________________________________________________________________
//
using namespace Uintah;
// These are used externally (e.g. Radiamoter.cc), keep them visible
// outside this unit
Dout g_ray_dbg("Ray_dbg", "Radiation Models", "RMCRT Ray general debug stream", false);
Dout g_ray_BC ("Ray_BC", "Radiation Models", "RMCRT RayBC debug stream", false);
//______________________________________________________________________
// Static variable declarations
// This class is instantiated by ray() and radiometer().
// You only want 1 instance of each of these variables thus we use
// static variables
//______________________________________________________________________
double RMCRTCommon::d_threshold;
double RMCRTCommon::d_sigma;
double RMCRTCommon::d_sigmaScat;
double RMCRTCommon::d_maxRayLength; // max ray length.
bool RMCRTCommon::d_isSeedRandom;
bool RMCRTCommon::d_allowReflect;
int RMCRTCommon::d_matl;
std::string RMCRTCommon::d_abskgBC_tag;
std::map<std::string,Task::WhichDW> RMCRTCommon::d_abskg_dw;
std::vector<IntVector> RMCRTCommon::d_dbgCells;
MaterialSet* RMCRTCommon::d_matlSet{nullptr};
const VarLabel* RMCRTCommon::d_sigmaT4Label;
const VarLabel* RMCRTCommon::d_abskgLabel;
const VarLabel* RMCRTCommon::d_divQLabel;
const VarLabel* RMCRTCommon::d_boundFluxLabel;
const VarLabel* RMCRTCommon::d_radiationVolqLabel;
const VarLabel* RMCRTCommon::d_compAbskgLabel;
const VarLabel* RMCRTCommon::d_compTempLabel;
const VarLabel* RMCRTCommon::d_cellTypeLabel;
//______________________________________________________________________
// Class: Constructor.
//______________________________________________________________________
//
RMCRTCommon::RMCRTCommon( TypeDescription::Type FLT_DBL )
: d_FLT_DBL(FLT_DBL)
{
if (RMCRTCommon::d_FLT_DBL == TypeDescription::double_type){
d_sigmaT4Label = VarLabel::create( "sigmaT4", CCVariable<double>::getTypeDescription() );
proc0cout << "__________________________________ USING DOUBLE VERSION OF RMCRT" << std::endl;
} else {
d_sigmaT4Label = VarLabel::create( "sigmaT4", CCVariable<float>::getTypeDescription() );
d_abskgLabel = VarLabel::create( "abskgRMCRT", CCVariable<float>::getTypeDescription() );
proc0cout << "__________________________________ USING FLOAT VERSION OF RMCRT" << std::endl;
}
d_boundFluxLabel = VarLabel::create( "RMCRTboundFlux", CCVariable<Stencil7>::getTypeDescription() );
d_radiationVolqLabel = VarLabel::create( "radiationVolq", CCVariable<double>::getTypeDescription() );
d_gac = Ghost::AroundCells;
d_gn = Ghost::None;
d_flowCell = -1; //<----HARD CODED FLOW CELL
d_maxRayLength = DBL_MAX;
#ifdef FAST_EXP
d_fastExp.populateExp_int(-2, 2);
#endif
}
//______________________________________________________________________
// Method: Destructor
//______________________________________________________________________
//
RMCRTCommon::~RMCRTCommon()
{
VarLabel::destroy( d_sigmaT4Label );
VarLabel::destroy( d_boundFluxLabel );
VarLabel::destroy( d_radiationVolqLabel );
if (RMCRTCommon::d_FLT_DBL == TypeDescription::float_type){
VarLabel::destroy( d_abskgLabel );
}
// when the radiometer class is invoked d_matlSet it deleted twice. This prevents that.
if( d_matlSet ) {
if ( d_matlSet->getReferenceCount() == 1 ){
d_matlSet->removeReference();
delete d_matlSet;
}
}
}
//______________________________________________________________________
// Register the material index and label names
//______________________________________________________________________
void
RMCRTCommon::registerVarLabels(int matlIndex,
const VarLabel* abskg,
const VarLabel* temperature,
const VarLabel* celltype,
const VarLabel* divQ )
{
d_matl = matlIndex;
d_compAbskgLabel = abskg;
d_compTempLabel = temperature;
d_cellTypeLabel = celltype;
d_divQLabel = divQ;
d_abskgBC_tag = d_compAbskgLabel->getName(); // The label name changes when using floats.
// If using RMCRT:DBL
const Uintah::TypeDescription* td = d_compAbskgLabel->typeDescription();
const Uintah::TypeDescription::Type subtype = td->getSubType()->getType();
if ( RMCRTCommon::d_FLT_DBL == TypeDescription::double_type && subtype == TypeDescription::double_type ) {
d_abskgLabel = d_compAbskgLabel;
}
//__________________________________
// define the materialSet
// The constructor can be called twice, so only create matlSet once.
if (d_matlSet == nullptr) {
d_matlSet = scinew MaterialSet();
std::vector<int> m;
m.push_back(matlIndex);
d_matlSet->addAll(m);
d_matlSet->addReference();
}
}
//______________________________________________________________________
// This task will convert the CCVariable abskg from double -> float
// If abskg is of type double and the component has
// specified that RMCRT communicate the all-to-all variables (abskg & sigmaT4)
// as a float then convert abskg to float
//______________________________________________________________________
void
RMCRTCommon::sched_DoubleToFloat( const LevelP& level,
SchedulerP& sched,
Task::WhichDW notUsed )
{
const Uintah::TypeDescription* td = d_compAbskgLabel->typeDescription();
const Uintah::TypeDescription::Type subtype = td->getSubType()->getType();
int L = level->getIndex();
Task::WhichDW abskgDW = get_abskg_whichDW( L, d_compAbskgLabel );
// only run task if a conversion is needed.
Task* tsk = nullptr;
if ( RMCRTCommon::d_FLT_DBL == TypeDescription::float_type && subtype == TypeDescription::double_type ){
tsk = scinew Task( "RMCRTCommon::DoubleToFloat", this, &RMCRTCommon::DoubleToFloat, abskgDW);
} else {
return;
}
printSchedule(level, g_ray_dbg, "RMCRTCommon::DoubleToFloat");
tsk->requires( abskgDW, d_compAbskgLabel, d_gn, 0 );
tsk->computes(d_abskgLabel);
sched->addTask( tsk, level->eachPatch(), d_matlSet);
}
//______________________________________________________________________
//
//______________________________________________________________________
void
RMCRTCommon::DoubleToFloat( const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset* matls,
DataWarehouse* old_dw,
DataWarehouse* new_dw,
Task::WhichDW which_dw )
{
//__________________________________
for (int p=0; p < patches->size(); p++) {
const Patch* patch = patches->get(p);
printTask(patches, patch, g_ray_dbg, "Doing RMCRTCommon::DoubleToFloat");
constCCVariable<double> abskg_D;
CCVariable< float > abskg_F;
DataWarehouse* myDW = new_dw->getOtherDataWarehouse(which_dw);
myDW->get(abskg_D, d_compAbskgLabel, d_matl, patch, Ghost::None, 0);
new_dw->allocateAndPut(abskg_F, d_abskgLabel, d_matl, patch);
for (CellIterator iter = patch->getExtraCellIterator();!iter.done();iter++){
const IntVector& c = *iter;
abskg_F[c] = (float)abskg_D[c];
// bulletproofing
if (std::isinf( abskg_F[c] ) || std::isnan( abskg_F[c] ) ) {
std::ostringstream warn;
warn<< "RMCRTCommon::DoubleToFloat A non-physical abskg detected (" << abskg_F[c] << ") at cell: " << c << "\n";
throw InternalError( warn.str(), __FILE__, __LINE__ );
}
}
}
}
//______________________________________________________________________
//
//______________________________________________________________________
void
RMCRTCommon::sched_sigmaT4( const LevelP& level,
SchedulerP& sched,
Task::WhichDW temp_dw,
const bool includeEC )
{
std::string taskname = "RMCRTCommon::sigmaT4";
Task* tsk = nullptr;
if ( RMCRTCommon::d_FLT_DBL == TypeDescription::double_type ) {
tsk = scinew Task( taskname, this, &RMCRTCommon::sigmaT4<double>, temp_dw, includeEC );
} else {
tsk = scinew Task( taskname, this, &RMCRTCommon::sigmaT4<float>, temp_dw, includeEC );
}
printSchedule(level, g_ray_dbg, "RMCRTCommon::sched_sigmaT4");
tsk->requires( temp_dw, d_compTempLabel, d_gn, 0 );
tsk->computes(d_sigmaT4Label);
sched->addTask( tsk, level->eachPatch(), d_matlSet, RMCRTCommon::TG_RMCRT );
}
//______________________________________________________________________
// Compute total intensity over all wave lengths (sigma * Temperature^4/pi)
//______________________________________________________________________
template< class T>
void
RMCRTCommon::sigmaT4( const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset* matls,
DataWarehouse* old_dw,
DataWarehouse* new_dw,
Task::WhichDW which_temp_dw,
const bool includeEC )
{
//__________________________________
// do the work
for (int p=0; p < patches->size(); p++){
const Patch* patch = patches->get(p);
printTask(patches, patch, g_ray_dbg, "Doing RMCRTCommon::sigmaT4");
double sigma_over_pi = d_sigma/M_PI;
constCCVariable<double> temp;
CCVariable< T > sigmaT4; // sigma T ^4/pi
DataWarehouse* temp_dw = new_dw->getOtherDataWarehouse(which_temp_dw);
temp_dw->get(temp, d_compTempLabel, d_matl, patch, Ghost::None, 0);
new_dw->allocateAndPut(sigmaT4, d_sigmaT4Label, d_matl, patch);
// set the cell iterator
CellIterator iter = patch->getCellIterator();
if(includeEC){
iter = patch->getExtraCellIterator();
}
for (;!iter.done();iter++){
const IntVector& c = *iter;
double T_sqrd = temp[c] * temp[c];
sigmaT4[c] = sigma_over_pi * T_sqrd * T_sqrd;
}
}
}
//______________________________________________________________________
//
//______________________________________________________________________
void
RMCRTCommon::raySignStep(double sign[],
int cellStep[],
const Vector& inv_direction_vector){
// get new step and sign
for ( int d=0; d<3; d++){
double me = copysign((double)1.0, inv_direction_vector[d]); // +- 1
sign[d] = std::max(0.0, me); // 0, 1
cellStep[d] = int(me);
}
}
//______________________________________________________________________
// Compute the ray direction
//______________________________________________________________________
Vector
RMCRTCommon::findRayDirection(MTRand& mTwister,
const IntVector& origin,
const int iRay )
{
if( d_isSeedRandom == false ){
mTwister.seed((origin.x() + origin.y() + origin.z()) * iRay +1);
}
// Random Points On Sphere
double plusMinus_one = 2.0 * mTwister.randDblExc() - 1.0 + DBL_EPSILON; // add fuzz to avoid inf in 1/dirVector
double r = sqrt(1.0 - plusMinus_one * plusMinus_one); // Radius of circle at z
double theta = 2.0 * M_PI * mTwister.randDblExc(); // Uniform betwen 0-2Pi
Vector direction_vector;
direction_vector[0] = r*cos(theta); // Convert to cartesian
direction_vector[1] = r*sin(theta);
direction_vector[2] = plusMinus_one;
/*`==========DEBUGGING==========*/
#if ( FIXED_RAY_DIR == 1)
direction_vector = Vector(0.707106781186548, 0.707106781186548, 0.) * Vector(SIGN);
#elif ( FIXED_RAY_DIR == 2 )
direction_vector = Vector(0.707106781186548, 0.0, 0.707106781186548) * Vector(SIGN);
#elif ( FIXED_RAY_DIR == 3 )
direction_vector = Vector(0.0, 0.707106781186548, 0.707106781186548) * Vector(SIGN);
#elif ( FIXED_RAY_DIR == 4 )
direction_vector = Vector(0.707106781186548, 0.707106781186548, 0.707106781186548) * Vector(SIGN);
#elif ( FIXED_RAY_DIR == 5 )
direction_vector = Vector(1, 0, 0) * Vector(SIGN);
#elif ( FIXED_RAY_DIR == 6 )
direction_vector = Vector(0, 1, 0) * Vector(SIGN);
#elif ( FIXED_RAY_DIR == 7 )
direction_vector = Vector(0, 0, 1) * Vector(SIGN);
#else
#endif
/*===========DEBUGGING==========`*/
return direction_vector;
}
//______________________________________________________________________
// Compute the physical location of a ray's origin
//______________________________________________________________________
void
RMCRTCommon::ray_Origin( MTRand& mTwister,
const Point CC_pos,
const Vector dx,
const bool useCCRays,
Vector& rayOrigin )
{
if( useCCRays == false ){
double x = mTwister.rand() * dx.x();
double y = mTwister.rand() * dx.y();
double z = mTwister.rand() * dx.z();
Vector offset(x,y,z); // Note you HAVE to compute the components separately to ensure that the
// random numbers called in the x,y,z order -Todd
if ( offset.x() > dx.x() ||
offset.y() > dx.y() ||
offset.z() > dx.z() ) {
std::cout << " Warning:ray_Origin The Mersenne twister random number generator has returned garbage (" << offset
<< ") Now forcing the ray origin to be located at the cell-center\n" ;
offset = Vector( 0.5*dx.x(), 0.5*dx.y(), 0.5*dx.z() );
}
rayOrigin[0] = CC_pos.x() - 0.5*dx.x() + offset.x();
rayOrigin[1] = CC_pos.y() - 0.5*dx.y() + offset.y();
rayOrigin[2] = CC_pos.z() - 0.5*dx.z() + offset.z();
}else{
rayOrigin[0] = CC_pos(0);
rayOrigin[1] = CC_pos(1);
rayOrigin[2] = CC_pos(2);
}
}
//______________________________________________________________________
// Core function:
//______________________________________________________________________
void
RMCRTCommon::reflect(double& fs,
IntVector& cur,
IntVector& prevCell,
const double abskg,
bool& in_domain,
int& step,
double& sign,
double& ray_direction)
{
fs = fs * (1 - abskg);
//put cur back inside the domain
cur = prevCell;
in_domain = true;
// apply reflection condition
step *= -1; // begin stepping in opposite direction
sign *= -1;
ray_direction *= -1;
//dbg2 << " REFLECTING " << std::endl;
}
//______________________________________________________________________
// Integrate the intensity
//______________________________________________________________________
template <class T >
void
RMCRTCommon::updateSumI (const Level* level,
Vector& ray_direction,
Vector& ray_origin,
const IntVector& origin,
const Vector& Dx,
constCCVariable< T >& sigmaT4OverPi,
constCCVariable< T >& abskg,
constCCVariable<int>& celltype,
unsigned long int& nRaySteps,
double& sumI,
MTRand& mTwister)
{
IntVector cur = origin;
IntVector prevCell = cur;
// Cell stepping direction for ray marching
int step[3];
double sign[3]; // is 0 for negative ray direction
Vector inv_ray_direction = Vector(1.0)/ray_direction;
/*`==========TESTING==========*/
#if DEBUG == 1
if( isDbgCell(origin) ) {
printf(" updateSumI: [%d,%d,%d] ray_dir [%g,%g,%g] ray_loc [%g,%g,%g]\n", origin.x(), origin.y(), origin.z(),ray_direction.x(), ray_direction.y(), ray_direction.z(), ray_origin.x(), ray_origin.y(), ray_origin.z());
}
#endif
/*===========TESTING==========`*/
raySignStep(sign, step, ray_direction);
Point CC_pos = level->getCellPosition(origin);
// rayDx is the distance from bottom, left, back, corner of cell to ray
double rayDx[3];
rayDx[0] = ray_origin.x() - ( CC_pos.x() - 0.5*Dx[0] );
rayDx[1] = ray_origin.y() - ( CC_pos.y() - 0.5*Dx[1] );
rayDx[2] = ray_origin.z() - ( CC_pos.z() - 0.5*Dx[2] );
// tMax is the physical distance from the ray origin to each of the respective planes of intersection
double tMax[3];
tMax[0] = (sign[0] * Dx[0] - rayDx[0]) * inv_ray_direction.x();
tMax[1] = (sign[1] * Dx[1] - rayDx[1]) * inv_ray_direction.y();
tMax[2] = (sign[2] * Dx[2] - rayDx[2]) * inv_ray_direction.z();
//Length of t to traverse one cell
Vector tDelta = Abs(inv_ray_direction) * Dx;
//Initializes the following values for each ray
bool in_domain = true;
double tMax_prev = 0;
double intensity = 1.0;
double fs = 1.0;
int nReflect = 0; // Number of reflections
double optical_thickness = 0;
double expOpticalThick_prev = 1.0;
double rayLength_scatter = 0.0; // ray length for each scattering event
double rayLength = 0.0; // total length of the ray
Vector ray_location = ray_origin;
#ifdef RAY_SCATTER
double scatCoeff = std::max( d_sigmaScat, 1e-99 ); // avoid division by zero [m^-1]
// Determine the length at which scattering will occur
// See CCA/Components/Arches/RMCRT/PaulasAttic/MCRT/ArchesRMCRT/ray.cc
double scatLength = -log(mTwister.randDblExc() ) / scatCoeff;
#endif
//______________________________________________________________________
while ( intensity > d_threshold && (rayLength < d_maxRayLength) ){
DIR dir = NONE;
while ( in_domain && (rayLength < d_maxRayLength) ){
prevCell = cur;
double disMin = -9; // Represents ray segment length.
T abskg_prev = abskg[prevCell]; // optimization
T sigmaT4OverPi_prev = sigmaT4OverPi[prevCell];
//__________________________________
// Determine which cell the ray will enter next
dir = NONE;
if ( tMax[0] < tMax[1] ){ // X < Y
if ( tMax[0] < tMax[2] ){ // X < Z
dir = X;
} else {
dir = Z;
}
} else {
if( tMax[1] < tMax[2] ){ // Y < Z
dir = Y;
} else {
dir = Z;
}
}
//__________________________________
// update marching variables
cur[dir] = cur[dir] + step[dir];
disMin = (tMax[dir] - tMax_prev);
tMax_prev = tMax[dir];
tMax[dir] = tMax[dir] + tDelta[dir];
// occassionally disMin ~ -1e-15ish
if( disMin > -FUZZ && disMin < FUZZ){
disMin += FUZZ;
}
rayLength += disMin;
rayLength_scatter += disMin;
ray_location[0] = ray_location[0] + (disMin * ray_direction[0]);
ray_location[1] = ray_location[1] + (disMin * ray_direction[1]);
ray_location[2] = ray_location[2] + (disMin * ray_direction[2]);
in_domain = (celltype[cur] == d_flowCell);
optical_thickness += abskg_prev*disMin;
nRaySteps++;
/*`==========TESTING==========*/
#if ( DEBUG >= 1 )
if( isDbgCell( origin )){
printf( " cur [%d,%d,%d] prev [%d,%d,%d]", cur.x(), cur.y(), cur.z(), prevCell.x(), prevCell.y(), prevCell.z());
printf( " dir %d ", dir );
printf( "tMax [%g,%g,%g] ",tMax[0],tMax[1], tMax[2]);
printf( "rayLoc [%g,%g,%g] ",ray_location.x(),ray_location.y(), ray_location.z());
printf( "distanceTraveled %g tMax[dir]: %g tMax_prev: %g, Dx[dir]: %g\n",disMin, tMax[dir], tMax_prev, Dx[dir]);
printf( " tDelta [%g,%g,%g] \n",tDelta.x(),tDelta.y(), tDelta.z());
// printf( " abskg[prev] %g \t sigmaT4OverPi[prev]: %g \n",abskg[prevCell], sigmaT4OverPi[prevCell]);
// printf( " abskg[cur] %g \t sigmaT4OverPi[cur]: %g \t cellType: %i\n",abskg[cur], sigmaT4OverPi[cur], celltype[cur]);
printf( " optical_thickkness %g \t rayLength: %g\n", optical_thickness, rayLength);
}
#endif
/*===========TESTING==========`*/
//Eqn 3-15(see below reference) while
//Third term inside the parentheses is accounted for in Inet. Chi is accounted for in Inet calc.
/*`==========TESTING==========*/
#ifdef FAST_EXP
// We need to know the range of optical_thickness before we can select
// which implementation to use.
double expOpticalThick = d_fastExp.fast_exp(-optical_thickness);
//double expOpticalThick = exp(-optical_thickness);
double S_exp = d_fastExp.Schraudolph_exp(-optical_thickness);
double fast_exp = d_fastExp.fast_exp(-optical_thickness);
double exp2 = d_fastExp.exp2(-optical_thickness);
double exp3 = d_fastExp.exp3(-optical_thickness);
double exp5 = d_fastExp.exp5(-optical_thickness);
double exp7 = d_fastExp.exp7(-optical_thickness);
double exact = exp(-optical_thickness);
cout << " X: " << -optical_thickness << endl;
cout << " Sch_exp error: " << ((S_exp - exact)/exact ) * 100 << " S_exp: " << S_exp << " exact: " << exact << endl;
cout << " fast_exp error: " << ((fast_exp - exact)/exact ) * 100 << " fast_exp:" << fast_exp << endl;
cout << " exp2 error: " << ((exp2 - exact)/exact ) * 100 << " exp2: " << exp2 << endl;
cout << " exp3 error: " << ((exp3 - exact)/exact ) * 100 << " exp3: " << exp3 << endl;
cout << " exp5 error: " << ((exp5 - exact)/exact ) * 100 << " exp5: " << exp5 << endl;
cout << " exp7 error: " << ((exp7 - exact)/exact ) * 100 << " exp7: " << exp7 << endl;
#else
double expOpticalThick = exp(-optical_thickness);
#endif
/*===========TESTING==========`*/
sumI += sigmaT4OverPi_prev * ( expOpticalThick_prev - expOpticalThick ) * fs;
expOpticalThick_prev = expOpticalThick;
#ifdef RAY_SCATTER
if (rayLength_scatter > scatLength && in_domain ){
// get new scatLength for each scattering event
scatLength = -log(mTwister.randDblExc() ) / scatCoeff;
ray_direction = findRayDirection( mTwister, cur );
inv_ray_direction = Vector(1.0)/ray_direction;
// get new step and sign
int stepOld = step[dir];
raySignStep( sign, step, ray_direction);
// if sign[dir] changes sign, put ray back into prevCell (back scattering)
// a sign change only occurs when the product of old and new is negative
if( step[dir] * stepOld < 0 ){
cur = prevCell;
}
Point CC_pos = level->getCellPosition(cur);
rayDx[0] = ray_location.x() - ( CC_pos.x() - 0.5*Dx[0] );
rayDx[1] = ray_location.y() - ( CC_pos.y() - 0.5*Dx[1] );
rayDx[2] = ray_location.z() - ( CC_pos.z() - 0.5*Dx[2] );
tMax[0] = (sign[0] * Dx[0] - rayDx[0]) * inv_ray_direction.x();
tMax[1] = (sign[1] * Dx[1] - rayDx[1]) * inv_ray_direction.y();
tMax[2] = (sign[2] * Dx[2] - rayDx[2]) * inv_ray_direction.z();
//Length of t to traverse one cell
tDelta = Abs(inv_ray_direction) * Dx;
/*`==========TESTING==========*/
#if (DEBUG == 3)
if( isDbgCell( origin) ){
Vector mytDelta = tDelta / Dx;
Vector myrayLoc = ray_location / Dx;
printf( " Scatter: [%i, %i, %i], rayLength: %g, tmax: %g, %g, %g tDelta: %g, %g, %g ray_dir: %g, %g, %g\n",cur.x(), cur.y(), cur.z(),rayLength, tMax[0] / Dx[0], tMax[1] / Dx[1], tMax[2] / Dx[2], mytDelta.x(), mytDelta.y() , mytDelta.z(), ray_direction.x(), ray_direction.y() , ray_direction.z());
printf( " dir: %i sign: [%g, %g, %g], step [%i, %i, %i] cur: [%i, %i, %i], prevCell: [%i, %i, %i]\n", dir, sign[0], sign[1], sign[2], step[0], step[1], step[2], cur[0], cur[1], cur[2], prevCell[0], prevCell[1], prevCell[2] );
printf( " ray_location: [%g, %g, %g]\n", myrayLoc[0], myrayLoc[1], myrayLoc[2] );
// printf(" rayDx [%g, %g, %g] CC_pos[%g, %g, %g]\n", rayDx[0], rayDx[1], rayDx[2], CC_pos.x(), CC_pos.y(), CC_pos.z());
}
#endif
/*===========TESTING==========`*/
tMax_prev = 0;
rayLength_scatter = 0; // allow for multiple scattering events per ray
}
#endif
if( rayLength < 0 || std::isnan(rayLength) || std::isinf(rayLength) ) {
std::ostringstream warn;
warn<< "ERROR:RMCRTCommon::updateSumI The ray length is non-physical (" << rayLength << ")"
<< " origin: " << origin << " cur: " << cur << "\n";
throw InternalError( warn.str(), __FILE__, __LINE__ );
}
} //end domain while loop. ++++++++++++++
//______________________________________________________________________
T wallEmissivity = abskg[cur];
if (wallEmissivity > 1.0){ // Ensure wall emissivity doesn't exceed one.
wallEmissivity = 1.0;
}
intensity = exp(-optical_thickness);
sumI += wallEmissivity * sigmaT4OverPi[cur] * intensity;
intensity = intensity * fs;
// //__________________________________
// // BULLETPROOFING
// if ( std::isinf(sumI) || std::isnan(sumI) ){
// printf( "\n\n______________________________________________________________________\n");
// std::cout << " cur: " << cur << " prevCell: " << prevCell << "\n";
// std::cout << " dir: " << dir << " sumI: " << sumI << "\n";
// std::cout << " tMax: " << tMax << "\n";
// std::cout << " rayLoc: " << ray_location << "\n";
// std::cout << " tMax[dir]: " << tMax[dir] << " tMax_prev: " << tMax_prev << " Dx[dir]: " << Dx[dir] << "\n";
// std::cout << " tDelta: " << tDelta << " \n";
// std::cout << " abskg[prev]: " << abskg[prevCell] << " \t sigmaT4OverPi[prev]: " << sigmaT4OverPi[prevCell] << "\n";
// std::cout << " abskg[cur]: " << abskg[cur] << " \t sigmaT4OverPi[cur]: " << sigmaT4OverPi[cur] << "\t cellType: " <<celltype[cur] << "\n";
// std::cout << " optical_thickkness: " << optical_thickness << " \t rayLength: " << rayLength << "\n";
//
// IntVector l = abskg.getLowIndex();
// IntVector h = abskg.getHighIndex();
// printf( " abskg: [%d,%d,%d] -> [%d,%d,%d] \n", l.x(), l.y(), l.z() , h.x(), h.y(), h.z() );
//
// std::ostringstream warn;
// warn<< "ERROR:RMCRTCommon::updateSumI sumI is non-physical (" << sumI << ")"
// << " origin: " << origin << " cur: " << cur << "\n";
// throw InternalError( warn.str(), __FILE__, __LINE__ );
// }
// when a ray reaches the end of the domain, we force it to terminate.
if(!d_allowReflect) intensity = 0;
/*`==========TESTING==========*/
#if DEBUG >= 0
if( isDbgCell( origin) ){
printf( " cur [%d,%d,%d] intensity: %g expOptThick: %g, fs: %g allowReflect: %i\n",
cur.x(), cur.y(), cur.z(), intensity, exp(-optical_thickness), fs, d_allowReflect );
}
#endif
/*===========TESTING==========`*/
//__________________________________
// Reflections
if ( intensity > d_threshold && d_allowReflect ){
reflect( fs, cur, prevCell, abskg[cur], in_domain, step[dir], sign[dir], ray_direction[dir]);
++nReflect;
}
} // threshold while loop.
} // end of updateSumI function
//______________________________________________________________________
// Move all computed variables from old_dw -> new_dw
//______________________________________________________________________
void
RMCRTCommon::sched_CarryForward_FineLevelLabels ( const LevelP& level,
SchedulerP& sched )
{
std::string taskname = "RMCRTCommon::sched_CarryForward_FineLevelLabels";
printSchedule( level, g_ray_dbg, taskname );
Task* tsk = scinew Task( taskname, this, &RMCRTCommon::carryForward_FineLevelLabels );
tsk->requires( Task::OldDW, d_divQLabel, d_gn, 0 );
tsk->requires( Task::OldDW, d_boundFluxLabel, d_gn, 0 );
tsk->requires( Task::OldDW, d_radiationVolqLabel, d_gn, 0 );
tsk->requires( Task::OldDW, d_sigmaT4Label, d_gn, 0 );
tsk->computes( d_divQLabel );
tsk->computes( d_boundFluxLabel );
tsk->computes( d_radiationVolqLabel );
tsk->computes( d_sigmaT4Label );
sched->addTask( tsk, level->eachPatch(), d_matlSet, RMCRTCommon::TG_CARRY_FORWARD );
}
//______________________________________________________________________
//
void
RMCRTCommon::carryForward_FineLevelLabels(DetailedTask* dtask,
Task::CallBackEvent event,
const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset* matls,
DataWarehouse* old_dw,
DataWarehouse* new_dw,
void* old_TaskGpuDW,
void* new_TaskGpuDW,
void* stream,
int deviceID)
{
printTask( patches, patches->get(0), g_ray_dbg, "Doing RMCRTCommon::carryForward_FineLevelLabels" );
bool replaceVar = true;
new_dw->transferFrom(old_dw, d_divQLabel, patches, matls, dtask, replaceVar, nullptr );
new_dw->transferFrom(old_dw, d_boundFluxLabel, patches, matls, dtask, replaceVar, nullptr );
new_dw->transferFrom(old_dw, d_radiationVolqLabel, patches, matls, dtask, replaceVar, nullptr );
new_dw->transferFrom(old_dw, d_sigmaT4Label, patches, matls, dtask, replaceVar, nullptr );
}
//______________________________________________________________________
// Utility task: move variable from old_dw -> new_dw
//______________________________________________________________________
void
RMCRTCommon::sched_CarryForward_Var ( const LevelP& level,
SchedulerP& sched,
const VarLabel* variable,
const int tg_num /* == -1 */)
{
std::string taskname = " carryForward_Var: " + variable->getName();
printSchedule(level, g_ray_dbg, taskname);
Task* task = scinew Task( taskname, this, &RMCRTCommon::carryForward_Var, variable );
task->requires(Task::OldDW, variable, d_gn, 0);
task->computes(variable);
sched->addTask( task, level->eachPatch(), d_matlSet, tg_num);
}
//______________________________________________________________________
void
RMCRTCommon::carryForward_Var ( DetailedTask* dtask,
Task::CallBackEvent event,
const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset* matls,
DataWarehouse* old_dw,
DataWarehouse* new_dw,
void* old_TaskGpuDW,
void* new_TaskGpuDW,
void* stream,
int deviceID,
const VarLabel* variable )
{
new_dw->transferFrom(old_dw, variable, patches, matls, dtask, true, nullptr);
}
//______________________________________________________________________
//
//______________________________________________________________________
bool
RMCRTCommon::isDbgCell( const IntVector me)
{
for( unsigned int i = 0; i<d_dbgCells.size(); i++) {
if( me == d_dbgCells[i]) {
return true;
}
}
return false;
}
//______________________________________________________________________
// Populate vector with integers which have been randomly shuffled.
// This is sampling without replacement and can be used to in a
// Latin-Hyper-Cube sampling scheme. The algorithm used is the
// modern fisher-yates shuffle.
//______________________________________________________________________
void
RMCRTCommon::randVector( std::vector <int> &int_array,
MTRand& mTwister,
const IntVector& cell )
{
int max= int_array.size();
for (int i=0; i<max; i++){ // populate sequential array from 0 to max-1
int_array[i] = i;
}
if( d_isSeedRandom == false ){
mTwister.seed((cell.x() + cell.y() + cell.z()));
}
for (int i=max-1; i>0; i--){ // fisher-yates shuffle starting with max-1
#ifdef FIXED_RANDOM_NUM
int rand_int = 0.3*i;
#else
int rand_int = mTwister.randInt(i);
#endif
int swap = int_array[i];
int_array[i] = int_array[rand_int];
int_array[rand_int] = swap;
}
}
//______________________________________________________________________
// For RMCRT algorithms the absorption coefficient can be required from either the old_dw or
// new_dw depending on if RMCRT:float is specified. On coarse levels abskg _always_ resides
// in the newDW. If RMCRT:float is used then abskg on the fine level resides in the new_dw.
// This method creates a global map and the key for the (map d_abskg_dw <string, Task::WhichDW>)
// is the labelName_L-X, the value in the map is the old or new dw.
//_____________________________________________________________________
void
RMCRTCommon::set_abskg_dw_perLevel ( const LevelP& fineLevel,
Task::WhichDW fineLevel_abskg_dw )
{
int maxLevels = fineLevel->getGrid()->numLevels();
printSchedule(fineLevel, g_ray_dbg, "RMCRTCommon::set_abskg_dws");
//__________________________________
// fineLevel could have two entries. One for abskg and abskgRMCRT
std::ostringstream key;
key << d_compAbskgLabel->getName() << "_L-"<< fineLevel->getIndex();
d_abskg_dw[key.str()] = fineLevel_abskg_dw;
//__________________________________
// fineLevel: FLOAT abskgRMCRT
if ( RMCRTCommon::d_FLT_DBL == TypeDescription::float_type ) {
std::ostringstream key1;
key1 << d_abskgLabel->getName() << "_L-"<< fineLevel->getIndex();
d_abskg_dw[key1.str()] = Task::NewDW;
}
//__________________________________
// coarse levels always require from the newDW
for(int L = 0; L<maxLevels; L++) {
if ( L != fineLevel->getIndex() ) {
std::ostringstream key2;
key2 << d_abskgLabel->getName() << "_L-"<< L;
d_abskg_dw[key2.str()] = Task::NewDW;
}
}
#if 0 // debugging
for( auto iter = d_abskg_dw.begin(); iter != d_abskg_dw.end(); iter++ ){
std::cout << " key: " << (*iter).first << " value: " << (*iter).second << std::endl;
}
#endif
}
//______________________________________________________________________
// return the dw associated for this abskg and level
//______________________________________________________________________
DataWarehouse*
RMCRTCommon::get_abskg_dw ( const int L,
const VarLabel* label,
DataWarehouse* new_dw)
{
Task::WhichDW dw = get_abskg_whichDW ( L, label );
DataWarehouse* abskg_dw = new_dw->getOtherDataWarehouse( dw );
return abskg_dw;
}
//______________________________________________________________________
// return the Task::WhichDW for this abskg and level
//______________________________________________________________________
Task::WhichDW
RMCRTCommon::get_abskg_whichDW ( const int L,
const VarLabel* label)
{
std::ostringstream key;
key << label->getName() << "_L-"<< L;
Task::WhichDW abskgDW = d_abskg_dw[key.str()];
// std::cout << " key: " << key.str() << " value: " << abskgDW << std::endl;
return abskgDW;
}
//______________________________________________________________________
//
//______________________________________________________________________
// Explicit template instantiations:
template void
RMCRTCommon::updateSumI ( const Level*, Vector&, Vector&, const IntVector&, const Vector&, constCCVariable< double >&, constCCVariable<double>&, constCCVariable<int>&, unsigned long int&, double&, MTRand&);
template void
RMCRTCommon::updateSumI ( const Level*, Vector&, Vector&, const IntVector&, const Vector&, constCCVariable< float >&, constCCVariable<float>&, constCCVariable<int>&, unsigned long int&, double&, MTRand&);
| 39.914849 | 319 | 0.628128 | [
"vector"
] |
f6f61c7090bb286398ca53260bc176edf47eb94f | 4,187 | cpp | C++ | src/InjectOpenGLIntrinsics.cpp | champyen/Halide | 8c0dbba26971c4b2a0adbb4c45aac2688642401d | [
"MIT"
] | 1 | 2021-08-16T13:10:03.000Z | 2021-08-16T13:10:03.000Z | src/InjectOpenGLIntrinsics.cpp | champyen/Halide | 8c0dbba26971c4b2a0adbb4c45aac2688642401d | [
"MIT"
] | null | null | null | src/InjectOpenGLIntrinsics.cpp | champyen/Halide | 8c0dbba26971c4b2a0adbb4c45aac2688642401d | [
"MIT"
] | null | null | null | #include "InjectOpenGLIntrinsics.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "CodeGen_GPU_Dev.h"
#include "Substitute.h"
#include "FuseGPUThreadLoops.h"
#include "Scope.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
/** Normalizes image loads/stores and produces glsl_texture_load/stores. */
class InjectOpenGLIntrinsics : public IRMutator {
public:
InjectOpenGLIntrinsics()
: inside_kernel_loop(false) {
}
Scope<int> scope;
bool inside_kernel_loop;
private:
using IRMutator::visit;
void visit(const Call *call) {
if (call->call_type != Call::Intrinsic) {
IRMutator::visit(call);
return;
}
if (call->name == Call::image_load) {
vector<Expr> call_args = call->args;
//
// Create
// glsl_texture_load("name",
// name.buffer,
// (x - x_min + 0.5)/x_extent,
// (y - y_min + 0.5)/y_extent,
// c)
// from
// image_load("name",
// name.buffer,
// x - x_min, x_extent,
// y - y_min, y_extent,
// c - c_min, c_extent
// )
//
vector<Expr> args(5);
args[0] = call_args[0]; // "name"
args[1] = call_args[1]; // name.buffer
// Normalize first two coordinates.
for (size_t i = 0; i < 2; i++) {
int to_index = 2 + i;
int from_index = 2 + i * 2;
args[to_index] =
(Cast::make(Float(32), mutate(call_args[from_index])) + 0.5f) /
mutate(call_args[from_index + 1]);
}
// Confirm that user explicitly specified constant value for min
// value of c dimension for ImageParams accessed by GLSL-based filters.
if (call->param.defined()) {
bool const_min_constraint =
call->param.min_constraint(2).defined() &&
is_const(call->param.min_constraint(2));
user_assert(const_min_constraint)
<< "GLSL: Requires minimum for c-dimension set to constant "
<< "for ImageParam '" << args[0] << "'. "
<< "Call set_min(2, min) or set_bounds(2, min, extent) to set.\n";
}
Expr c_coordinate = mutate(call_args[2 + 2 * 2]);
args[4] = c_coordinate;
Type load_type = call->type;
load_type.width = 4;
Expr load_call = Call::make(load_type, Call::glsl_texture_load,
vector<Expr>(&args[0], &args[4]),
Call::Intrinsic, Function(), 0,
call->image, call->param);
// Add a shuffle_vector intrinsic to swizzle a single channel
// scalar out of the vec4 loaded by glsl_texture_load. This may
// be widened to the size of the Halide function color dimension
// during vectorization.
expr = Call::make(call->type, Call::shuffle_vector,
vec(load_call, c_coordinate), Call::Intrinsic);
} else if (call->name == Call::image_store) {
user_assert(call->args.size() == 6)
<< "GLSL stores require three coordinates.\n";
// Create
// gl_texture_store(name, name.buffer, x, y, c, value)
// out of
// image_store(name, name.buffer, x, y, c, value)
vector<Expr> args(call->args);
args[5] = mutate(call->args[5]); // mutate value
expr = Call::make(call->type, Call::glsl_texture_store,
args, Call::Intrinsic);
} else {
IRMutator::visit(call);
}
}
};
Stmt inject_opengl_intrinsics(Stmt s) {
InjectOpenGLIntrinsics gl;
return gl.mutate(s);
}
}
}
| 36.408696 | 86 | 0.493193 | [
"vector"
] |
f6f65a58d35a4897014629dfcd4566d80b9cdb53 | 2,870 | cpp | C++ | src/CoreLib/Formats/FileFormatCSV.cpp | mapron/d2modgen | 6906de7bfc4c2cebf7ca523c559ae8ae26012034 | [
"MIT"
] | 17 | 2022-01-08T09:27:08.000Z | 2022-03-19T08:23:42.000Z | src/CoreLib/Formats/FileFormatCSV.cpp | mapron/d2modgen | 6906de7bfc4c2cebf7ca523c559ae8ae26012034 | [
"MIT"
] | 11 | 2022-01-08T11:25:42.000Z | 2022-02-13T05:17:00.000Z | src/CoreLib/Formats/FileFormatCSV.cpp | mapron/d2modgen | 6906de7bfc4c2cebf7ca523c559ae8ae26012034 | [
"MIT"
] | 2 | 2022-01-14T16:43:55.000Z | 2022-03-09T07:56:43.000Z | /*
* Copyright (C) 2022 Smirnov Vladimir / mapron1@gmail.com
* SPDX-License-Identifier: MIT
* See LICENSE file for details.
*/
#include "FileFormatCSV.hpp"
#include <cassert>
namespace D2ModGen {
namespace {
class FastCsvTable {
const char* begin;
const char* end;
const char* curr;
public:
FastCsvTable(const char* begin, size_t length)
{
this->begin = begin;
this->curr = begin;
this->end = begin + length;
}
bool scanLine()
{
if (curr >= end)
return false;
const char* peek = curr;
size_t tabs = 0;
while (peek < end) {
if (*peek == '\t')
tabs++;
if (*peek == '\r' || *peek == '\n')
break;
peek++;
}
const char* i = curr;
const char* lineEnd = peek;
line = std::string_view(curr, peek - curr);
if (*peek == '\r')
++peek;
if (*peek == '\n')
++peek;
curr = peek;
row.resize(tabs + 1);
size_t index = 0;
const char* prevI = i;
while (i < lineEnd) {
if (*i == '\t') {
row[index] = i == prevI ? std::string_view() : std::string_view(prevI, i - prevI);
prevI = i + 1;
index++;
}
i++;
}
row[index] = i == prevI ? std::string_view() : std::string_view(prevI, i - prevI);
return true;
}
std::vector<std::string_view> row;
std::string_view line;
};
}
bool writeCSVToBuffer(std::string& csvData, const Table& table)
{
for (size_t i = 0; i < table.columns.size(); ++i) {
if (i > 0)
csvData += '\t';
csvData += table.columns[i];
}
csvData += "\r\n";
for (const auto& row : table.rows) {
for (size_t i = 0; i < row.data.size(); ++i) {
if (i > 0)
csvData += '\t';
csvData += row.data[i].str;
}
csvData += "\r\n";
}
return true;
}
bool readCSVFromBuffer(const std::string& csvData, Table& table)
{
FastCsvTable csvTable(csvData.data(), csvData.size());
if (!csvTable.scanLine())
return false;
table.columns.resize(csvTable.row.size());
for (size_t i = 0; i < csvTable.row.size(); ++i)
table.columns[i] = std::string(csvTable.row[i]);
std::vector<TableCell> data;
while (csvTable.scanLine()) {
data.resize(csvTable.row.size());
for (size_t i = 0; i < csvTable.row.size(); ++i)
data[i].str = std::string(csvTable.row[i]);
table.rows.push_back(TableRow(data));
}
#ifndef NDEBUG
{
std::string check;
writeCSVToBuffer(check, table);
assert(check == csvData);
}
#endif
return true;
}
}
| 24.322034 | 98 | 0.489547 | [
"vector"
] |
f6f993695edc17dd3193745610c36100f9cff714 | 2,707 | hpp | C++ | ios/Pods/boost-for-react-native/boost/hana/fwd/concept/integral_constant.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 8,805 | 2015-11-03T00:52:29.000Z | 2022-03-29T22:30:03.000Z | ios/Pods/boost-for-react-native/boost/hana/fwd/concept/integral_constant.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 14,694 | 2015-02-24T15:13:42.000Z | 2022-03-31T13:16:45.000Z | ios/Pods/boost-for-react-native/boost/hana/fwd/concept/integral_constant.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 1,329 | 2015-11-03T20:25:51.000Z | 2022-03-31T18:10:38.000Z | /*!
@file
Forward declares `boost::hana::IntegralConstant`.
@copyright Louis Dionne 2013-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_FWD_CONCEPT_INTEGRAL_CONSTANT_HPP
#define BOOST_HANA_FWD_CONCEPT_INTEGRAL_CONSTANT_HPP
#include <boost/hana/config.hpp>
BOOST_HANA_NAMESPACE_BEGIN
//! @ingroup group-concepts
//! The `IntegralConstant` concept represents compile-time integral values.
//!
//! The `IntegralConstant` concept represents objects that hold a
//! `constexpr` value of an integral type. In other words, it describes
//! the essential functionality provided by `std::integral_constant`.
//! An `IntegralConstant` is also just a special kind of `Constant`
//! whose inner value is of an integral type.
//!
//!
//! Minimal complete definition
//! ---------------------------
//! The requirements for being an `IntegralConstant` are quite simple.
//! First, an `IntegralConstant` `C` must be a `Constant` such that
//! `Tag::value_type` is an integral type, where `Tag` is the tag of `C`.
//!
//! Secondly, `C` must have a nested `static constexpr` member named
//! `value`, such that the following code is valid:
//! @code
//! constexpr auto v = C::value;
//! @endcode
//! Because of the requirement that `Tag::value_type` be an integral type,
//! it follows that `C::value` must be an integral value.
//!
//! Finally, it is necessary to specialize the `IntegralConstant` template
//! in the `boost::hana` namespace to tell Hana that a type is a model
//! of `IntegralConstant`:
//! @code
//! namespace boost { namespace hana {
//! template <>
//! struct IntegralConstant<your_custom_tag> {
//! static constexpr bool value = true;
//! };
//! }}
//! @endcode
//!
//!
//! Refined concept
//! ---------------
//! 1. `Constant` (free implementation of `value`)\n
//! The `value` function required to be a `Constant` can be implemented
//! as follows for `IntegralConstant`s:
//! @code
//! value<C>() == C::value
//! @endcode
//! The `to` function must still be provided explicitly for the model
//! of `Constant` to be complete.
//!
//!
//! Concrete models
//! ---------------
//! `hana::integral_constant`
template <typename C>
struct IntegralConstant;
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_FWD_CONCEPT_INTEGRAL_CONSTANT_HPP
| 36.581081 | 80 | 0.612856 | [
"model"
] |
f6fedeec5fe148a43640f0790d2895ea2005c29a | 15,611 | cpp | C++ | ai1.0/othello.cpp | kenchan-liu/qt-homework | 52096696407c279e3046f6cf5e99fd443cdb69bf | [
"AFL-3.0"
] | null | null | null | ai1.0/othello.cpp | kenchan-liu/qt-homework | 52096696407c279e3046f6cf5e99fd443cdb69bf | [
"AFL-3.0"
] | null | null | null | ai1.0/othello.cpp | kenchan-liu/qt-homework | 52096696407c279e3046f6cf5e99fd443cdb69bf | [
"AFL-3.0"
] | null | null | null | #include "othello.h"
#include "ui_othello.h"
#include <Qpainter>
#include <QPixmap>
#include "QCursor"
#include <iostream>
#include<QDebug>
#include "QMouseEvent"
#include <string>
#include <vector>
#include <time.h>
#include <Windows.h>
#include <queue>
#include <stack>
#include<QSize>
#include <conio.h>
#include<QMessageBox>
#include<math.h>
using namespace std;
bool mousedown = false;
int mousex;
int mousey;
Board * mainBoard;
othello::othello(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::othello)
{
ui->setupUi(this);
init();
mode=1;
mainBoard=new Board();
resetBoard(mainBoard);
turn="a";
playera=Blackchess;
playerb=Whitechess;
playert=Blackchess;
computert=Whitechess;
nom=true;
QString a;
a= ui->lineEdit->text();
hard=a.toInt();
isGameStart=false;
groupButton1=new QButtonGroup(this);
groupButton1->addButton(ui->aim,0);
groupButton1->addButton(ui->hmm,1);
ui->hmm->setChecked(true); //默认human_mode
connect(ui->pushButton, SIGNAL(clicked()),this,SLOT(ClickButton()));
background.load("C:/Users/kentl/Documents/build-Othello-Desktop_Qt_5_9_6_MinGW_32bit-Debug/debug/images/1.jpg");
black.load("G:/noir.png");
white.load("G:/blanc.png");
hintblack.load("G:/hintblack.png");
hintwhite.load("G:/hintwhite.png");
background=background.scaled(QSize(400,400), Qt::KeepAspectRatio);
black=black.scaled(QSize(50,50),Qt::KeepAspectRatio);
white=white.scaled(QSize(50,50),Qt::KeepAspectRatio);
hintblack=hintblack.scaled(QSize(50,50),Qt::KeepAspectRatio);
hintwhite=hintwhite.scaled(QSize(50,50),Qt::KeepAspectRatio);
}
void othello::on_pushButton_clicked(){
if(isGameStart==false){
QMessageBox msgBox;
msgBox.setText("www.baidu.com");
msgBox.exec();
ui->pushButton->setText("Reset");
turn="a";
switch(groupButton1->checkedId())
{
case 0:
mode=-1;
break;
case 1:
mode=1;
break;
}
isGameStart=true;
resetBoard(mainBoard);
repaint();
}
else{
resetBoard(mainBoard);
turn="a";
isGameStart=false;
repaint();
ui->pushButton->setText("Start");
}
}
othello::~othello()
{
delete ui;
}
void othello::init(){
struct posnode originpos;
originpos.x=originpos.y=8;
}
void othello::mousePressEvent(QMouseEvent *e){
if(mode==1){
mousex=e->x()/50;
mousey=e->y()/50;
if(turn.compare("a")==0&&isGameOver(mainBoard)!=true&&!gameOver){
if(makeMove(mainBoard,playera,mousex,mousey)==true){
Last.x=mousex;
Last.y=mousey;
if(getMove(mainBoard,playerb).size()!=0){
turn="b";
}
}
else{
cout<<"Reinput"<<endl;
}
}else{
if(makeMove(mainBoard,playerb,mousex,mousey)==true){
Last.x=mousex;
Last.y=mousey;
if(getMove(mainBoard,playera).size()!=0){
turn="a";
}
}
else{
cout<<"Reinput"<<endl;
}
}
repaint();
}
else{
mousex=e->x()/50;
mousey=e->y()/50;
if(turn.compare("a")==0&&isGameOver(mainBoard)!=true&&!gameOver){
if(makeMove(mainBoard,playert,mousex,mousey)==true){
makeMove(mainBoard,playert,mousex,mousey);
Last.x=mousex;
Last.y=mousey;
if(getMove(mainBoard,computert).size()!=0){
turn="b";
}
}
repaint();
}
posi p;
p=min(mainBoard,3,-9999,9999,Whitechess,hard);
if(makeMove(mainBoard,computert,p.x,p.y)==true){
if(getMove(mainBoard,playert).size()!=0){
turn="a";
}
}
repaint();
}
}
void othello::paintEvent(QPaintEvent *event){
this->resize(600,400);
QPainter painter(this);
painter.setRenderHint(QPainter::SmoothPixmapTransform,true);
painter.drawPixmap(0,0,400,400,background);
int c;
if(turn=="b"){
c=Whitechess;
}
else{
c=Blackchess;
}
int potential[8][8];
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
potential[i][j]=0;
}
}
if(isGameOver(mainBoard)&&nom){
QMessageBox msgBox;
if(report(mainBoard,Whitechess)>report(mainBoard,Blackchess))
msgBox.setText("white win.");
else
msgBox.setText("black win.");
msgBox.exec();
nom=false;
}
vector<posi> nodes =getMove(mainBoard,c);
for(int i=0;i<nodes.size();i++){
int x=nodes[i].x;
int y=nodes[i].y;
potential[x][y]=c;
}
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if(mainBoard->get(i,j)==Whitechess){
painter.drawPixmap(0+50*i,0+50*j,50,50,white);
}
else if(mainBoard->get(i,j)==Blackchess){
painter.drawPixmap(0+50*i,0+50*j,50,50,black);
}
if(potential[i][j]==Blackchess){
painter.drawPixmap(0+50*i,0+50*j,50,50,hintblack);
}
if(potential[i][j]==Whitechess){
painter.drawPixmap(0+50*i,0+50*j,50,50,hintwhite);
}
}
}
}
bool othello::makeMove(Board *mainboard, int playerTile, int col, int row){
vector<posi> tilesToFlip = isValid(mainboard, playerTile, col, row);
if (tilesToFlip.size()==0) {
return false;
}
mainboard->set(col, row, playerTile);
while (tilesToFlip.size()!=0) {
posi tilepos = tilesToFlip.back();
tilesToFlip.pop_back();
mainboard->set(tilepos.x, tilepos.y, playerTile);
}
repaint();
return true;
}
vector<posi> othello::isValid(Board *board, int tile, int col, int row){
vector<posi> tilesToFlip;
if (isOnBoard(col, row) == false || board->get(col, row) != 0) {
return tilesToFlip;
}
int othertile;
board->set(col, row, tile);
if (tile == Blackchess) {
othertile = Whitechess;
}
else {
othertile = Blackchess;
}
for (int i = 0; i < 8; i++) {
int x = col;
int y = row;
int xdirection = Direction[i][0];
int ydirection = Direction[i][1];
x += xdirection;
y += ydirection;
if (isOnBoard(x, y) && board->get(x, y) == othertile) {
x += xdirection;
y += ydirection;
if (isOnBoard(x, y) == false) {
continue;
}
while (board->get(x, y) == othertile) {
x += xdirection;
y += ydirection;
if (isOnBoard(x, y) == false) {
break;
}
}
if (isOnBoard(x, y) == false) {
continue;
}
if (board->get(x, y) == tile) {
while (true) {
x -= xdirection;
y -= ydirection;
if (x == col && y == row) {
break;
}
tilesToFlip.push_back(posi(x, y));
}
}
}
}
board->set(col, row, 0);
return tilesToFlip;
}
vector<posi> othello::getMove(Board *board, int tile){
vector<posi> validMoves;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++){
if (isValid(board, tile, i, j).size() != 0) {
validMoves.push_back(posi(i, j));
}
}
}
return validMoves;
}
bool othello::isOnBoard(int x, int y){
return x>=0&&x<=7&&y>=0&&y<=7;
}
bool othello::isOnCorner(int x,int y){
return (x==0&&y==0)||(x==7&&y==0)||(x==0&&y==7);
}
bool othello::isGameOver(Board* board) {
int black = 0;
int white = 0;
int flag = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board->get(i, j) == Blackchess) {
black++;
}
else if (board->get(i, j) == Whitechess) {
white++;
}
else {
flag++;
}
}
}
if (black == 0 || white == 0) {
return true;
}
if (flag != 0) {
return false;
}
return true;
}
int othello::report(Board *b,int t){
int black=0,white=0;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if (b->get(i, j) == Blackchess) {
black++;
}
else if (b->get(i, j) == Whitechess) {
white++;
}
}
}
if(t==Whitechess){
return white;
}
else
return black;
}
void othello::resetBoard(Board *board){
board->init();
board->set(3,3,Whitechess);
board->set(3,4,Blackchess);
board->set(4,3,Blackchess);
board->set(4,4,Whitechess);
}
posi othello::max(Board *mb, int depth, int alpha, int beta, int tile,int hard){
int best = -10000;
Board *nm=new Board();
posi move ;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
nm->set(i,j,mb->get(i,j));
}
}
vector<posi> gm=getMove(mb,tile);
if(depth==0){
for(int i=0;i<getMove(mb,tile).size();i++){
nm->set(gm[i].x,gm[i].y,tile);
if(evaluate(nm,hard)>best){
best=evaluate(nm,hard);move=gm[i];
}
nm->set(gm[i].x,gm[i].y,0);
}
return move;
}
if(gm.size()==0){
return move;
}
for (int i = 0; i < getMove(mb,tile).size(); i++) {
alpha = best>alpha?best:alpha;
if(alpha >= beta){
break;
}
nm->set(gm[i].x,gm[i].y,tile);
posi next;
next=min(nm, depth - 1,alpha, beta, -tile, hard);
nm->set(next.x,next.y,-tile);
int value = evaluate(nm,hard);
if (value < best) {
best = value;
move = gm[i];
}
nm->set(next.x,next.y,0);
nm->set(gm[i].x, gm[i].y,0);
}
return move;
}
posi othello::min(Board *mb, int depth, int alpha, int beta, int tile,int hard){
int best = 10000;
Board *nm=new Board();
posi move ;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
nm->set(i,j,mb->get(i,j));
}
}
vector<posi> gm=getMove(mb,tile);
if(depth==0){
for(int i=0;i<getMove(mb,tile).size();i++){
nm->set(gm[i].x,gm[i].y,tile);
if(evaluate(nm,hard)<best){
best=evaluate(nm,hard);move=gm[i];
}
nm->set(gm[i].x,gm[i].y,0);
}
return move;
}
for (int i = 0; i < getMove(mb,tile).size(); i++) {
beta = best<beta?best:beta;
if(alpha >= beta){
break;
}
posi next;
next=max(nm, depth - 1,alpha, beta, -tile, hard);
nm->set(gm[i].x,gm[i].y,tile);
nm->set(next.x,next.y,-tile);
int value = evaluate(nm,hard);
if (value < best) {
best = value;
move = gm[i];
}
nm->set(next.x,next.y,0);
nm->set(gm[i].x, gm[i].y,0);
}
return move;
}
int othello::evaluate(Board *board, int hard) {
int whiteEvaluate = 0;
int blackEvaluate = 0;
vector<posi>b,w;
int sw,sb;
int weight[5] = { 2, 4, 6, 10, 15 };
switch (hard) {
case 1:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 1;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 1;
}
}
}
break;
case 2:
case 3:
case 4:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if ((i == 0 || i == 7) && (j == 0 || j == 7)) {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 5;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 5;
}
} else if (i == 0 || i == 7 || j == 0 || j == 7) {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 2;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 2;
}
} else {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 1;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 1;
}
}
}
}
break;
case 5:
case 6:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if ((i == 0 || i == 7) && (j == 0 || j == 7)) {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 5;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 5;
}
} else if (i == 0 || i == 7 || j == 0 || j == 7) {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 2;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 2;
}
} else {
if (board->get(i,j) == Whitechess) {
whiteEvaluate += 1;
} else if (board->get(i,j) == Blackchess) {
blackEvaluate += 1;
}
}
}
}
b=getMove(board,Blackchess);
w=getMove(board,Whitechess);
blackEvaluate = blackEvaluate * 2 + b.size();
whiteEvaluate = whiteEvaluate * 2 + w.size();
break;
case 7:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board->get(i,j) == Whitechess) {
whiteEvaluate = whiteEvaluate + weight[getStability(board,posi(i, j))];
} else if (board->get(i,j) == Blackchess) {
blackEvaluate = blackEvaluate + weight[getStability(board, posi(i, j))];
}
}
}
b=getMove(board,Blackchess);
w=getMove(board, Whitechess);
sb=b.size();
sw=w.size();
blackEvaluate += sb;
whiteEvaluate += sw;
break;
}
return blackEvaluate - whiteEvaluate;
}
int othello::getStability(Board *b, posi p) {
int chessColor = b->get(p.x,p.y);
int drow[4][2]={ { 0, 0 }, { -1, 1 }, { -1, 1 }, { 1, -1 } }, dcol[4][2]={ { -1, 1 }, { 0, 0 }, { -1, 1 }, { -1, 1 } };
int row[2],col[2];
int degree = 0;
for (int k = 0; k < 4; k++) {
row[0] = row[1] = p.x;
col[0] = col[1] = p.y;
for (int i = 0; i < 2; i++) {
while (isOnBoard(row[i] + drow[k][i], col[i] + dcol[k][i])
&& b->get(row[i] + drow[k][i],col[i] + dcol[k][i]) == chessColor) {
row[i] += drow[k][i];
col[i] += dcol[k][i];
}
}
if (!isOnBoard(row[0] + drow[k][0], col[0] + dcol[k][0])
|| !isOnBoard(row[1] + drow[k][1], col[1] + dcol[k][1])) {
degree += 1;
} else if (b->get(row[0] + drow[k][0],col[0] + dcol[k][0]) == (-chessColor)
&& b->get(row[1] + drow[k][1],col[1] + dcol[k][1]) == (-chessColor)) {
degree += 1;
}
}
return degree;
}
| 28.962894 | 123 | 0.464096 | [
"vector"
] |
10005cd4782972d0bf5461fffd21ab3413aaa2b9 | 1,188 | cpp | C++ | GFG/Matrix/C++/Spirally traversing a matrix.cpp | C-a-thing/Code-Insight | b201bec522d47c82ae088d382e426074e279f500 | [
"MIT"
] | 10 | 2022-02-15T10:12:10.000Z | 2022-02-25T17:25:14.000Z | GFG/Matrix/C++/Spirally traversing a matrix.cpp | C-a-thing/Code-Insight | b201bec522d47c82ae088d382e426074e279f500 | [
"MIT"
] | 5 | 2022-02-24T16:22:41.000Z | 2022-03-04T13:29:00.000Z | GFG/Matrix/C++/Spirally traversing a matrix.cpp | C-a-thing/Code-Insight | b201bec522d47c82ae088d382e426074e279f500 | [
"MIT"
] | 5 | 2022-02-15T06:29:14.000Z | 2022-02-20T06:53:57.000Z | class Solution
{
public:
//Function to return a list of integers denoting spiral traversal of matrix.
vector<int> spirallyTraverse(vector<vector<int> > mat, int r, int c)
{
// code here
vector<int> v;
int r1=0,rn = r , c1 = 0 , cn = c ,i,count=0;
while(r1<rn && c1<cn){
//printing the first row
if(count>=r*c) break;
for(i=c1;i<cn;i++){
v.push_back(mat[r1][i]);
count++;
}
r1++;
if(count>=r*c) break;
// printing last column
for(i=r1;i<rn;i++){
v.push_back(mat[i][cn-1]);
count++;
}
cn--;
if(count>=r*c) break;
//printing last row
for(i=cn-1;i>=c1;i--){
v.push_back(mat[rn-1][i]);
count++;
}
rn--;
if(count>=r*c) break;
//printing first column
for(i=rn-1;i>=r1;i--){
v.push_back(mat[i][c1]);
count++;
}
c1++;
}
return v;
}
};
| 27 | 80 | 0.382997 | [
"vector"
] |
100112d1c6b45e3a2c99fb20317389b8f5d1fcec | 3,827 | cpp | C++ | cc/Messenger.cpp | PEQUI-VSSS/VSSS-EMC | 0c2b61e308f754ca91df52e46ba48828168223df | [
"MIT"
] | 9 | 2017-07-18T12:37:09.000Z | 2018-05-01T14:41:48.000Z | cc/Messenger.cpp | PEQUI-MEC/VSSS-EMC | 0c2b61e308f754ca91df52e46ba48828168223df | [
"MIT"
] | 31 | 2018-07-31T13:10:01.000Z | 2022-03-26T16:00:25.000Z | cc/Messenger.cpp | PEQUI-MEC/VSSS-EMC | 0c2b61e308f754ca91df52e46ba48828168223df | [
"MIT"
] | 2 | 2017-10-01T16:09:20.000Z | 2018-05-01T17:39:59.000Z | #include "Messenger.h"
using std::string;
using std::vector;
using Pose = Robot2::Pose;
using Command = Robot2::Command;
void Messenger::start_xbee(const string &port, int baud) {
xbee = new Xbee(port, baud);
add_robots();
}
void Messenger::stop_xbee() {
if (!xbee) return;
delete xbee;
xbee = nullptr;
}
void Messenger::add_robots() {
if (!xbee) return;
xbee->add_robot('A', 0x88a0);
xbee->add_robot('B', 0xb24a);
xbee->add_robot('C', 0x215c);
xbee->add_robot('D', 0x35f6);
xbee->add_robot('E', 0x97e7);
xbee->add_robot('F', 0x6b0d);
}
void Messenger::send_msg(char id, string msg) {
if (!xbee) return;
xbee->send(id, msg);
}
void Messenger::send_old_format(string cmd) {
if (!xbee) return;
char id = cmd[0];
string msg = cmd.substr(2, cmd.find('#') - 2);
xbee->send(id, msg);
}
void Messenger::send_commands(const std::array<Robot2*, 3> &robots) {
if (!xbee || ++send_cmd_count <= frameskip) return;
for (Robot2* robot : robots) {
send_command(robot->ID, robot->get_target(), robot->get_command(), robot->uvf_ref);
}
update_msg_time();
send_cmd_count = 0;
}
constexpr float robot_size = 0.0675f;
void Messenger::send_command(char id, Pose target, Command command, Geometry::Point uvf_ref) {
if(!xbee) return;
const string msg = [&] {
switch (command) {
case Command::Position:
return "P" + rounded_str(target.position.x * 100)
+ ";" + rounded_str(target.position.y * 100)
+ ";" + rounded_str(target.velocity);
case Command::Angular_Vel:
return rounded_str(target.angular_velocity*robot_size/2)
+ ";" + rounded_str(-target.angular_velocity*robot_size/2);
case Command::Vector:
return ("V" + rounded_str(target.orientation * 180.0f/M_PI)
+ ";" + rounded_str(target.velocity));
case Command::UVF:
return "U" + rounded_str(target.position.x * 100) + ";" + rounded_str(target.position.y * 100)
+ ";" + rounded_str(uvf_ref.x * 100) + ";" + rounded_str(uvf_ref.y * 100)
+ ";" + rounded_str(1.8) + ";" + rounded_str(target.velocity);
case Command::Orientation:
return "O" + rounded_str(target.orientation * 180/M_PI)
+ ";" + rounded_str(target.velocity);
default:
return string();
}
}();
if (!msg.empty()) {
xbee->send(id, msg);
// if(id == 'A') std::cout << msg << std::endl;
}
}
void Messenger::send_ekf_data(const Robot2 &robot) {
if(!xbee) return;
auto robot_pose = robot.get_pose();
string msg = "E" + rounded_str(robot_pose.position.x * 100) + ";"
+ rounded_str(robot_pose.position.y * 100)
+ ";" + rounded_str(robot_pose.orientation * 180/M_PI);
xbee->send(robot.get_ID(), msg);
// if(robot.get_ID() == 'A') std::cout << msg << std::endl;
}
double Messenger::get_battery(char id) {
if (!xbee) return -1;
string msg = xbee->send_get_answer(id, "B");
if (msg.empty() || msg[0] != 'B') return -1;
return ((stod(msg.substr(1)) - 6.4) / 2.0) * 100;
}
string Messenger::rounded_str(double num) {
double rounded_num = round(num * 100) / 100;
std::ostringstream ss;
ss << rounded_num;
return ss.str();
}
void Messenger::set_ack_enabled(bool enable) {
if (!xbee) return;
xbee->set_ack_enabled(enable);
}
ack_count Messenger::get_ack_count(char id) {
if (!xbee) return {-1, -1, -1};
else return xbee->get_ack_count(id);
}
void Messenger::reset_lost_acks() {
if (!xbee) return;
xbee->reset_lost_acks();
}
void Messenger::update_msg_time() {
auto now = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> time_diff = now - previous_msg_time;
time_between_msgs = time_diff.count();
previous_msg_time = now;
}
Messenger::Messenger()
// : ekf_data_file("ekf_data.csv")
{
setlocale(LC_ALL, "C");
send_cmd_count = 0;
frameskip = DEFAULT_FRAMESKIP;
previous_msg_time = std::chrono::system_clock::now();
time_between_msgs = 0;
}
| 27.934307 | 98 | 0.660047 | [
"geometry",
"vector"
] |
10011978c2977d34922726b5fc8a76bba4d5f0c4 | 163 | hpp | C++ | Iridium/Model/Graph/Graph.hpp | lordharambae/Iridium | 40997d7082f7f80e38338af358fdca2a5ac3af63 | [
"BSD-3-Clause"
] | null | null | null | Iridium/Model/Graph/Graph.hpp | lordharambae/Iridium | 40997d7082f7f80e38338af358fdca2a5ac3af63 | [
"BSD-3-Clause"
] | null | null | null | Iridium/Model/Graph/Graph.hpp | lordharambae/Iridium | 40997d7082f7f80e38338af358fdca2a5ac3af63 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#ifndef GRAPH_HPP
#define GRAPH_HPP
namespace Iridium {
namespace Model {
class Graph {};
} // namespace Model
} // namespace Iridium
#endif | 10.866667 | 22 | 0.705521 | [
"model"
] |
10078906820cff01cb92352ba1e98e9d7c8e64b0 | 596 | cpp | C++ | leetcode/539. Minimum Time Difference/s2.cpp | zhuohuwu0603/leetcode_cpp_lzl124631x | 6a579328810ef4651de00fde0505934d3028d9c7 | [
"Fair"
] | 787 | 2017-05-12T05:19:57.000Z | 2022-03-30T12:19:52.000Z | leetcode/539. Minimum Time Difference/s2.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 8 | 2020-03-16T05:55:38.000Z | 2022-03-09T17:19:17.000Z | leetcode/539. Minimum Time Difference/s2.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 247 | 2017-04-30T15:07:50.000Z | 2022-03-30T09:58:57.000Z | // OJ: https://leetcode.com/problems/minimum-time-difference
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
private:
inline int getKey(string &s) {
return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3, 2));
}
public:
int findMinDifference(vector<string>& timePoints) {
sort(timePoints.begin(), timePoints.end());
int ans = INT_MAX;
for (int i = timePoints.size() - 1; i >= 0 && ans; --i) {
ans = min(ans, getKey(timePoints[i]) - (i == 0 ? getKey(timePoints.back()) - 24 * 60 : getKey(timePoints[i - 1])));
}
return ans;
}
}; | 31.368421 | 121 | 0.612416 | [
"vector"
] |
1008673914dcefcde98e7cbc1c0ad71d6ed60f97 | 5,702 | cpp | C++ | tests/cpp/codegen/refine_coordinates_test.cpp | cruedo/taichi | 010e8b9aed96634cd257f803646ff2f7849b06c1 | [
"MIT"
] | null | null | null | tests/cpp/codegen/refine_coordinates_test.cpp | cruedo/taichi | 010e8b9aed96634cd257f803646ff2f7849b06c1 | [
"MIT"
] | null | null | null | tests/cpp/codegen/refine_coordinates_test.cpp | cruedo/taichi | 010e8b9aed96634cd257f803646ff2f7849b06c1 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include <memory>
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/BasicBlock.h"
#include "taichi/program/arch.h"
#include "taichi/program/program.h"
#include "taichi/struct/struct_llvm.h"
#include "taichi/ir/snode.h"
#include "taichi/program/compile_config.h"
#include "taichi/llvm/llvm_codegen_utils.h"
namespace taichi {
namespace lang {
namespace {
constexpr char kFuncName[] = "run_refine_coords";
class InvokeRefineCoordinatesBuilder : public LLVMModuleBuilder {
public:
// 1st arg: Value of the first parent physical coordiantes
// 2nd arg: The child index
// ret : Value of the first child physical coordinates
using FuncType = int (*)(int, int);
static FuncType build(const SNode *snode, TaichiLLVMContext *tlctx) {
InvokeRefineCoordinatesBuilder mb{tlctx};
mb.run_jit(snode);
tlctx->add_module(std::move(mb.module));
auto *fn = tlctx->lookup_function_pointer(kFuncName);
return reinterpret_cast<FuncType>(fn);
}
private:
InvokeRefineCoordinatesBuilder(TaichiLLVMContext *tlctx)
: LLVMModuleBuilder(tlctx->clone_struct_module(), tlctx) {
this->llvm_context = this->tlctx->get_this_thread_context();
this->builder = std::make_unique<llvm::IRBuilder<>>(*llvm_context);
}
void run_jit(const SNode *snode) {
// pseudo code:
//
// int run_refine_coords(int parent_coords_first_comp, int child_index) {
// PhysicalCoordinates parent_coords;
// PhysicalCoordinates child_coords;
// parent_coord.val[0] = parent_coords_first_comp;
// snode_refine_coordinates(&parent_coords, &child_coords, child_index);
// return child_coords.val[0];
// }
auto *const int32_ty = llvm::Type::getInt32Ty(*llvm_context);
auto *const func_ty =
llvm::FunctionType::get(int32_ty, {int32_ty, int32_ty},
/*isVarArg=*/false);
auto *const func = llvm::Function::Create(
func_ty, llvm::Function::ExternalLinkage, kFuncName, module.get());
std::vector<llvm::Value *> args;
for (auto &a : func->args()) {
args.push_back(&a);
}
auto *const parent_coords_first_component = args[0];
auto *const child_index = args[1];
this->entry_block = llvm::BasicBlock::Create(*llvm_context, "entry", func);
builder->SetInsertPoint(entry_block);
auto *const index0 = tlctx->get_constant(0);
RuntimeObject parent_coords{kLLVMPhysicalCoordinatesName, this,
builder.get()};
parent_coords.set("val", index0, parent_coords_first_component);
auto *refine_fn =
get_runtime_function(snode->refine_coordinates_func_name());
RuntimeObject child_coords{kLLVMPhysicalCoordinatesName, this,
builder.get()};
builder->CreateCall(refine_fn,
{parent_coords.ptr, child_coords.ptr, child_index});
auto *ret_val = child_coords.get("val", index0);
builder->CreateRet(ret_val);
llvm::verifyFunction(*func);
}
};
struct BitsRange {
int begin{0};
int end{0};
int extract(int v) const {
const unsigned mask = (1U << (end - begin)) - 1;
return (v >> begin) & mask;
}
};
constexpr int kPointerSize = 5;
constexpr int kDenseSize = 7;
class RefineCoordinatesTest : public ::testing::Test {
protected:
void SetUp() override {
arch_ = host_arch();
config_.packed = false;
config_.print_kernel_llvm_ir = false;
prog_ = std::make_unique<Program>(arch_);
tlctx_ = prog_->llvm_context_host.get();
root_snode_ = std::make_unique<SNode>(/*depth=*/0, /*t=*/SNodeType::root);
const std::vector<Axis> axes = {Axis{0}};
ptr_snode_ = &(root_snode_->pointer(axes, kPointerSize));
dense_snode_ = &(ptr_snode_->dense(axes, kDenseSize));
// Must end with a `place` SNode.
auto &leaf_snode = dense_snode_->insert_children(SNodeType::place);
leaf_snode.dt = PrimitiveType::f32;
auto sc = std::make_unique<StructCompilerLLVM>(
arch_, &config_, tlctx_, tlctx_->clone_runtime_module());
sc->run(*root_snode_);
}
Arch arch_;
CompileConfig config_;
// We shouldn't need a Program instance in this test. Unfortunately, a few
// places depend on the global |current_program|, so we have to.
// ¯\_(ツ)_/¯
std::unique_ptr<Program> prog_{nullptr};
TaichiLLVMContext *tlctx_{nullptr};
std::unique_ptr<SNode> root_snode_{nullptr};
SNode *ptr_snode_{nullptr};
SNode *dense_snode_{nullptr};
};
TEST_F(RefineCoordinatesTest, Basic) {
auto *refine_ptr_fn =
InvokeRefineCoordinatesBuilder::build(ptr_snode_, tlctx_);
auto *refine_dense_fn =
InvokeRefineCoordinatesBuilder::build(dense_snode_, tlctx_);
const BitsRange dense_bit_range{/*begin=*/0,
/*end=*/dense_snode_->extractors[0].num_bits};
const BitsRange ptr_bit_range{
/*begin=*/dense_bit_range.end,
/*end=*/dense_bit_range.end + ptr_snode_->extractors[0].num_bits};
constexpr int kRootPhyCoord = 0;
for (int i = 0; i < kPointerSize; ++i) {
const int ptr_phy_coord = refine_ptr_fn(kRootPhyCoord, i);
for (int j = 0; j < kDenseSize; ++j) {
const int loop_index = refine_dense_fn(ptr_phy_coord, j);
// TODO: This is basically doing a lower_scalar_ptr() manually.
// We should modularize that function, and use it to generate IRs that
// does the bit extraction procedure.
const int dense_portion = dense_bit_range.extract(loop_index);
const int ptr_portion = ptr_bit_range.extract(loop_index);
EXPECT_EQ(dense_portion, j);
EXPECT_EQ(ptr_portion, i);
}
}
}
} // namespace
} // namespace lang
} // namespace taichi
| 34.143713 | 80 | 0.681515 | [
"vector"
] |
100923d20a429e3c7c1c12876eb0cefd05a3682c | 3,849 | cpp | C++ | source/wrapper/WrapperCache.cpp | Jde-cpp/MarketLibrary | 2324e46b3a2a9de7385cb5bad66826693b65545a | [
"MIT"
] | null | null | null | source/wrapper/WrapperCache.cpp | Jde-cpp/MarketLibrary | 2324e46b3a2a9de7385cb5bad66826693b65545a | [
"MIT"
] | null | null | null | source/wrapper/WrapperCache.cpp | Jde-cpp/MarketLibrary | 2324e46b3a2a9de7385cb5bad66826693b65545a | [
"MIT"
] | 1 | 2021-06-04T16:45:33.000Z | 2021-06-04T16:45:33.000Z | #include "WrapperCache.h"
#include "../types/Exchanges.h"
#include <jde/markets/types/Contract.h>
#include "../../../Framework/source/Cache.h"
#include "../../../Framework/source/collections/Collections.h"
#define var const auto
namespace Jde::Markets
{
void WrapperCache::contractDetails( int reqId, const ::ContractDetails& contractDetails )noexcept
{
if( _cacheIds.Has(reqId) )
{
WrapperLog::contractDetails( reqId, contractDetails );
unique_lock l{_detailsMutex};
_details.try_emplace( reqId, sp<vector<::ContractDetails>>{ new vector<::ContractDetails>{} } ).first->second->push_back( contractDetails );
}
}
void WrapperCache::contractDetailsEnd( int reqId )noexcept
{
var pCacheId = _cacheIds.Find( reqId );
if( pCacheId )
{
WrapperLog::contractDetailsEnd( reqId );
unique_lock l{_detailsMutex};
var pDetails = _details.find( reqId );
var pResults = pDetails==_details.end() ? sp<vector<::ContractDetails>>{} : pDetails->second;
Cache::Set( *pCacheId, pResults );
_details.erase( reqId );
_cacheIds.erase( reqId );
}
}
// Proto::Results::ExchangeContracts WrapperCache::ToOptionParam( sv exchangeString, int underlyingConId, str tradingClass, str multiplier, const std::set<std::string>& expirations, const std::set<double>& strikes )noexcept
// {
// auto exchange = ToExchange( exchangeString );
// if( exchange==Exchanges::Smart && CIString{ "SMART"sv }!=exchangeString )
// exchange = Exchanges::UnknownExchange;
// Proto::Results::ExchangeContracts a; a.set_exchange( exchange ); a.set_multiplier( multiplier ); a.set_trading_class( tradingClass ); a.set_underlying_contract_id( underlyingConId );
// for( var strike : strikes )
// a.add_strikes( strike );
// for( var& expiration : expirations )
// a.add_expirations( Contract::ToDay(expiration) );
// return a;
// }
/* void WrapperCache::securityDefinitionOptionalParameter( int reqId, str exchange, int underlyingConId, str tradingClass, str multiplier, const std::set<std::string>& expirations, const std::set<double>& strikes )noexcept
{
var pCacheId = _cacheIds.Find( reqId );
if( pCacheId )
{
WrapperLog::securityDefinitionOptionalParameter( reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes );
DBG( "Caching {}"sv, exchange );
*Collections::InsertUnique( _optionParams, reqId )->add_exchanges() = ToOptionParam( exchange, underlyingConId, tradingClass, multiplier, expirations, strikes );
}
}
void WrapperCache::securityDefinitionOptionalParameterEnd( int reqId )noexcept
{
var pCacheId = _cacheIds.Find( reqId );
if( pCacheId )
{
WrapperLog::securityDefinitionOptionalParameterEnd( reqId );
var pParams = _optionParams.find( reqId );
auto pResults = pParams==_optionParams.end() ? make_unique<Proto::Results::OptionExchanges>() : move( pParams->second );
Cache::Set( *pCacheId, sp<Proto::Results::OptionExchanges>(pResults.release()) );
_optionParams.erase( reqId );
_cacheIds.erase( reqId );
}
}
*/
void WrapperCache::ToBar( const ::Bar& bar, Proto::Results::Bar& proto )noexcept
{
var time = bar.time.size()==8 ? DateTime{ (uint16)stoi(bar.time.substr(0,4)), (uint8)stoi(bar.time.substr(4,2)), (uint8)stoi(bar.time.substr(6,2)) } : DateTime( stoi(bar.time) );
proto.set_time( (int)time.TimeT() );
proto.set_high( bar.high );
proto.set_low( bar.low );
proto.set_open( bar.open );
proto.set_close( bar.close );
proto.set_wap( bar.wap );
proto.set_volume( bar.volume );
proto.set_count( bar.count );
}
void WrapperCache::historicalData( TickerId reqId, const ::Bar& bar )noexcept
{
WrapperLog::historicalData( reqId, bar );
}
void WrapperCache::historicalDataEnd( int reqId, str startDateStr, str endDateStr )noexcept
{
WrapperLog::historicalDataEnd( reqId, startDateStr, endDateStr );
}
} | 40.515789 | 224 | 0.717329 | [
"vector"
] |
1009d947e788f41cb9c2159f00db91608b5ebb2e | 13,082 | cpp | C++ | disabled_modules/gdnative/gdnative/array.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 8 | 2019-09-03T19:58:19.000Z | 2021-06-18T07:11:26.000Z | disabled_modules/gdnative/gdnative/array.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 24 | 2019-09-03T17:35:45.000Z | 2020-10-27T14:36:02.000Z | disabled_modules/gdnative/gdnative/array.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 6 | 2019-09-27T15:44:35.000Z | 2021-01-23T18:52:51.000Z | /*************************************************************************/
/* array.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "gdnative/array.h"
#include "core/array.h"
#include "core/os/memory.h"
#include "core/color.h"
#include "core/pool_vector.h"
#include "core/variant.h"
#include "core/math/aabb.h"
#include "core/math/basis.h"
#include "core/math/face3.h"
#include "core/math/plane.h"
#include "core/math/quat.h"
#include "core/math/transform.h"
#include "core/math/transform_2d.h"
#include "core/math/vector3.h"
#include "core/ustring.h"
#ifdef __cplusplus
extern "C" {
#endif
void GDAPI godot_array_new(godot_array *r_dest) {
Array *dest = (Array *)r_dest;
memnew_placement(dest, Array);
}
void GDAPI godot_array_new_copy(godot_array *r_dest, const godot_array *p_src) {
Array *dest = (Array *)r_dest;
const Array *src = (const Array *)p_src;
memnew_placement(dest, Array(*src));
}
void GDAPI godot_array_new_pool_color_array(godot_array *r_dest, const godot_pool_color_array *p_pca) {
Array *dest = (Array *)r_dest;
PoolVector<Color> *pca = (PoolVector<Color> *)p_pca;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_new_pool_vector3_array(godot_array *r_dest, const godot_pool_vector3_array *p_pv3a) {
Array *dest = (Array *)r_dest;
PoolVector<Vector3> *pca = (PoolVector<Vector3> *)p_pv3a;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_new_pool_vector2_array(godot_array *r_dest, const godot_pool_vector2_array *p_pv2a) {
Array *dest = (Array *)r_dest;
PoolVector<Vector2> *pca = (PoolVector<Vector2> *)p_pv2a;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_new_pool_string_array(godot_array *r_dest, const godot_pool_string_array *p_psa) {
Array *dest = (Array *)r_dest;
PoolVector<String> *pca = (PoolVector<String> *)p_psa;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_new_pool_real_array(godot_array *r_dest, const godot_pool_real_array *p_pra) {
Array *dest = (Array *)r_dest;
PoolVector<godot_real> *pca = (PoolVector<godot_real> *)p_pra;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_new_pool_int_array(godot_array *r_dest, const godot_pool_int_array *p_pia) {
Array *dest = (Array *)r_dest;
PoolVector<godot_int> *pca = (PoolVector<godot_int> *)p_pia;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_new_pool_byte_array(godot_array *r_dest, const godot_pool_byte_array *p_pba) {
Array *dest = (Array *)r_dest;
PoolVector<uint8_t> *pca = (PoolVector<uint8_t> *)p_pba;
memnew_placement(dest, Array);
dest->resize(pca->size());
for (int i = 0; i < dest->size(); i++) {
Variant v = pca->operator[](i);
dest->operator[](i) = v;
}
}
void GDAPI godot_array_set(godot_array *p_self, const godot_int p_idx, const godot_variant *p_value) {
Array *self = (Array *)p_self;
Variant *val = (Variant *)p_value;
self->operator[](p_idx) = *val;
}
godot_variant GDAPI godot_array_get(const godot_array *p_self, const godot_int p_idx) {
godot_variant raw_dest;
Variant *dest = (Variant *)&raw_dest;
const Array *self = (const Array *)p_self;
memnew_placement(dest, Variant(self->operator[](p_idx)));
return raw_dest;
}
godot_variant GDAPI *godot_array_operator_index(godot_array *p_self, const godot_int p_idx) {
Array *self = (Array *)p_self;
return (godot_variant *)&self->operator[](p_idx);
}
const godot_variant GDAPI *godot_array_operator_index_const(const godot_array *p_self, const godot_int p_idx) {
const Array *self = (const Array *)p_self;
return (const godot_variant *)&self->operator[](p_idx);
}
void GDAPI godot_array_append(godot_array *p_self, const godot_variant *p_value) {
Array *self = (Array *)p_self;
Variant *val = (Variant *)p_value;
self->append(*val);
}
void GDAPI godot_array_clear(godot_array *p_self) {
Array *self = (Array *)p_self;
self->clear();
}
godot_int GDAPI godot_array_count(const godot_array *p_self, const godot_variant *p_value) {
const Array *self = (const Array *)p_self;
const Variant *val = (const Variant *)p_value;
return self->count(*val);
}
godot_bool GDAPI godot_array_empty(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
return self->empty();
}
void GDAPI godot_array_erase(godot_array *p_self, const godot_variant *p_value) {
Array *self = (Array *)p_self;
const Variant *val = (const Variant *)p_value;
self->erase(*val);
}
godot_variant GDAPI godot_array_front(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
godot_variant v;
Variant *val = (Variant *)&v;
memnew_placement(val, Variant);
*val = self->front();
return v;
}
godot_variant GDAPI godot_array_back(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
godot_variant v;
Variant *val = (Variant *)&v;
memnew_placement(val, Variant);
*val = self->back();
return v;
}
godot_int GDAPI godot_array_find(const godot_array *p_self, const godot_variant *p_what, const godot_int p_from) {
const Array *self = (const Array *)p_self;
const Variant *val = (const Variant *)p_what;
return self->find(*val, p_from);
}
godot_int GDAPI godot_array_find_last(const godot_array *p_self, const godot_variant *p_what) {
const Array *self = (const Array *)p_self;
const Variant *val = (const Variant *)p_what;
return self->find_last(*val);
}
godot_bool GDAPI godot_array_has(const godot_array *p_self, const godot_variant *p_value) {
const Array *self = (const Array *)p_self;
const Variant *val = (const Variant *)p_value;
return self->contains(*val);
}
godot_int GDAPI godot_array_hash(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
return self->hash();
}
void GDAPI godot_array_insert(godot_array *p_self, const godot_int p_pos, const godot_variant *p_value) {
Array *self = (Array *)p_self;
const Variant *val = (const Variant *)p_value;
self->insert(p_pos, *val);
}
void GDAPI godot_array_invert(godot_array *p_self) {
Array *self = (Array *)p_self;
self->invert();
}
godot_variant GDAPI godot_array_pop_back(godot_array *p_self) {
Array *self = (Array *)p_self;
godot_variant v;
Variant *val = (Variant *)&v;
memnew_placement(val, Variant);
*val = self->pop_back();
return v;
}
godot_variant GDAPI godot_array_pop_front(godot_array *p_self) {
Array *self = (Array *)p_self;
godot_variant v;
Variant *val = (Variant *)&v;
memnew_placement(val, Variant);
*val = self->pop_front();
return v;
}
void GDAPI godot_array_push_back(godot_array *p_self, const godot_variant *p_value) {
Array *self = (Array *)p_self;
const Variant *val = (const Variant *)p_value;
self->push_back(*val);
}
void GDAPI godot_array_push_front(godot_array *p_self, const godot_variant *p_value) {
Array *self = (Array *)p_self;
const Variant *val = (const Variant *)p_value;
self->push_front(*val);
}
void GDAPI godot_array_remove(godot_array *p_self, const godot_int p_idx) {
Array *self = (Array *)p_self;
self->remove(p_idx);
}
void GDAPI godot_array_resize(godot_array *p_self, const godot_int p_size) {
Array *self = (Array *)p_self;
self->resize(p_size);
}
godot_int GDAPI godot_array_rfind(const godot_array *p_self, const godot_variant *p_what, const godot_int p_from) {
const Array *self = (const Array *)p_self;
const Variant *val = (const Variant *)p_what;
return self->rfind(*val, p_from);
}
godot_int GDAPI godot_array_size(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
return self->size();
}
void GDAPI godot_array_sort(godot_array *p_self) {
Array *self = (Array *)p_self;
self->sort();
}
void GDAPI godot_array_sort_custom(godot_array *p_self, godot_object *p_obj, const godot_string *p_func) {
Array *self = (Array *)p_self;
const String *func = (const String *)p_func;
self->sort_custom((Object *)p_obj, StringName(*func));
}
godot_int GDAPI godot_array_bsearch(godot_array *p_self, const godot_variant *p_value, const godot_bool p_before) {
Array *self = (Array *)p_self;
return self->bsearch(*(const Variant *)p_value, p_before);
}
godot_int GDAPI godot_array_bsearch_custom(godot_array *p_self, const godot_variant *p_value, godot_object *p_obj, const godot_string *p_func, const godot_bool p_before) {
Array *self = (Array *)p_self;
const String *func = (const String *)p_func;
return self->bsearch_custom(*(const Variant *)p_value, (Object *)p_obj, StringName(*func), p_before);
}
void GDAPI godot_array_destroy(godot_array *p_self) {
((Array *)p_self)->~Array();
}
godot_array GDAPI godot_array_duplicate(const godot_array *p_self, const godot_bool p_deep) {
const Array *self = (const Array *)p_self;
godot_array res;
Array *val = (Array *)&res;
memnew_placement(val, Array);
*val = self->duplicate(p_deep);
return res;
}
godot_array GDAPI godot_array_slice(const godot_array *p_self, const godot_int p_begin, const godot_int p_end, const godot_int p_step, const godot_bool p_deep) {
const Array *self = (const Array *)p_self;
godot_array res;
Array *val = (Array *)&res;
memnew_placement(val, Array);
*val = self->slice(p_begin, p_end, p_step, p_deep);
return res;
}
godot_variant GDAPI godot_array_max(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
godot_variant v;
Variant *val = (Variant *)&v;
memnew_placement(val, Variant);
*val = self->max();
return v;
}
godot_variant GDAPI godot_array_min(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
godot_variant v;
Variant *val = (Variant *)&v;
memnew_placement(val, Variant);
*val = self->min();
return v;
}
void GDAPI godot_array_shuffle(godot_array *p_self) {
Array *self = (Array *)p_self;
self->shuffle();
}
#ifdef __cplusplus
}
#endif
| 34.97861 | 171 | 0.641798 | [
"object",
"transform"
] |
100a706277a3956390a1061f6c29554939a3f58a | 18,559 | cpp | C++ | source/globjects/source/Texture.cpp | jakpam/globjects | b6390838d183e15f1a652cff26ee8d9b6d30fda9 | [
"MIT"
] | 486 | 2015-10-13T13:50:24.000Z | 2022-03-31T06:46:07.000Z | source/globjects/source/Texture.cpp | jakpam/globjects | b6390838d183e15f1a652cff26ee8d9b6d30fda9 | [
"MIT"
] | 90 | 2015-07-21T20:13:03.000Z | 2022-03-07T19:14:35.000Z | source/globjects/source/Texture.cpp | jakpam/globjects | b6390838d183e15f1a652cff26ee8d9b6d30fda9 | [
"MIT"
] | 56 | 2015-07-08T12:41:43.000Z | 2022-02-15T07:38:15.000Z |
#include <globjects/Texture.h>
#include <glbinding/gl/enum.h>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/boolean.h>
#include <glm/gtc/type_ptr.hpp>
#include <globjects/Buffer.h>
#include <globjects/TextureHandle.h>
#include "pixelformat.h"
#include <globjects/Resource.h>
#include "registry/ImplementationRegistry.h"
#include "implementations/AbstractTextureImplementation.h"
#include "implementations/AbstractTextureStorageImplementation.h"
#include "implementations/AbstractTextureStorageMultisampleImplementation.h"
using namespace gl;
namespace
{
const globjects::AbstractTextureImplementation & bindlessImplementation()
{
return globjects::ImplementationRegistry::current().textureBindlessImplementation();
}
const globjects::AbstractTextureStorageImplementation & storageImplementation()
{
return globjects::ImplementationRegistry::current().textureStorageImplementation();
}
const globjects::AbstractTextureStorageMultisampleImplementation & storageMultisampleImplementation()
{
return globjects::ImplementationRegistry::current().textureStorageMultisampleImplementation();
}
} // namespace
namespace globjects
{
void Texture::hintBindlessImplementation(BindlessImplementation impl)
{
ImplementationRegistry::current().initialize(impl);
}
void Texture::hintStorageImplementation(StorageImplementation impl)
{
ImplementationRegistry::current().initialize(impl);
}
Texture::Texture()
: Texture(GL_TEXTURE_2D)
{
}
Texture::Texture(const GLenum target)
: Object(std::unique_ptr<IDResource>(new TextureResource(target)))
, m_target(target)
{
#ifdef GLOBJECTS_CHECK_GL_ERRORS
if (id() == 0 && !m_resource->isExternal())
{
DebugMessage::insertMessage(
gl::GL_DEBUG_SOURCE_APPLICATION,
gl::GL_DEBUG_TYPE_ERROR,
0,
gl::GL_DEBUG_SEVERITY_NOTIFICATION,
"Texture object could not be created"
);
}
#endif
}
Texture::Texture(std::unique_ptr<IDResource> && resource, const GLenum target)
: Object(std::move(resource))
, m_target(target)
{
}
std::unique_ptr<Texture> Texture::fromId(const GLuint id, const GLenum target)
{
return std::unique_ptr<Texture>(new Texture(std::unique_ptr<IDResource>(new ExternalResource(id)), target));
}
Texture::~Texture()
{
}
std::unique_ptr<Texture> Texture::createDefault()
{
return createDefault(GL_TEXTURE_2D);
}
std::unique_ptr<Texture> Texture::createDefault(const GLenum target)
{
auto texture = Texture::create(target);
texture->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
texture->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
texture->setParameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
texture->setParameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
texture->setParameter(GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return texture;
}
void Texture::bind() const
{
glBindTexture(m_target, id());
}
void Texture::unbind() const
{
unbind(m_target);
}
void Texture::unbind(const GLenum target)
{
glBindTexture(target, 0);
}
void Texture::bindActive(const GLenum texture) const
{
bindActive(static_cast<unsigned int>(texture) - static_cast<unsigned int>(gl::GL_TEXTURE0));
}
void Texture::bindActive(unsigned int index) const
{
bindlessImplementation().bindActive(this, index);
}
void Texture::unbindActive(const GLenum texture) const
{
unbindActive(static_cast<unsigned int>(texture) - static_cast<unsigned int>(gl::GL_TEXTURE0));
}
void Texture::unbindActive(unsigned int index) const
{
bindlessImplementation().unbindActive(this, index);
}
GLenum Texture::target() const
{
return m_target;
}
void Texture::setParameter(const GLenum name, const GLenum value)
{
setParameter(name, static_cast<GLint>(value));
}
void Texture::setParameter(const GLenum name, const GLint value)
{
bindlessImplementation().setParameter(this, name, value);
}
void Texture::setParameter(const GLenum name, const GLfloat value)
{
bindlessImplementation().setParameter(this, name, value);
}
void Texture::setParameter(gl::GLenum name, const glm::vec4 & value)
{
bindlessImplementation().setParameter(this, name, value);
}
GLint Texture::getParameter(const GLenum pname) const
{
return bindlessImplementation().getParameter(this, pname);
}
GLint Texture::getLevelParameter(const GLint level, const GLenum pname) const
{
return bindlessImplementation().getLevelParameter(this, level, pname);
}
void Texture::getImage(const GLint level, const GLenum format, const GLenum type, GLvoid * image) const
{
bind();
glGetTexImage(m_target, level, format, type, image);
}
std::vector<unsigned char> Texture::getImage(const GLint level, const GLenum format, const GLenum type) const
{
GLint width = getLevelParameter(level, GL_TEXTURE_WIDTH);
GLint height = getLevelParameter(level, GL_TEXTURE_HEIGHT);
GLint depth = getLevelParameter(level, GL_TEXTURE_DEPTH);
int byteSize = imageSizeInBytes(width, height, depth, format, type);
std::vector<unsigned char> data(byteSize);
getImage(level, format, type, data.data());
return data;
}
void Texture::getCompressedImage(const GLint lod, GLvoid * image) const
{
bind();
glGetCompressedTexImage(m_target, lod, image);
}
std::vector<unsigned char> Texture::getCompressedImage(const GLint lod) const
{
GLint size = getLevelParameter(lod, GL_TEXTURE_COMPRESSED_IMAGE_SIZE);
std::vector<unsigned char> data(size);
getCompressedImage(lod, data.data());
return data;
}
void Texture::image1D(const GLint level, const GLenum internalFormat, const GLsizei width, const GLint border, const GLenum format, const GLenum type, const GLvoid * data)
{
bindlessImplementation().image1D(this, level, internalFormat, width, border, format, type, data);
}
void Texture::compressedImage1D(const GLint level, const GLenum internalFormat, const GLsizei width, const GLint border, const GLsizei imageSize, const GLvoid * data)
{
bindlessImplementation().compressedImage1D(this, level, internalFormat, width, border, imageSize, data);
}
void Texture::subImage1D(const GLint level, const GLint xOffset, const GLsizei width, const GLenum format, const GLenum type, const GLvoid * data)
{
bindlessImplementation().subImage1D(this, level, xOffset, width, format, type, data);
}
void Texture::image2D(const GLint level, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLint border, const GLenum format, const GLenum type, const GLvoid* data)
{
bindlessImplementation().image2D(this, level, internalFormat, width, height, border, format, type, data);
}
void Texture::image2D(const GLint level, const GLenum internalFormat, const glm::ivec2 & size, const GLint border, const GLenum format, const GLenum type, const GLvoid* data)
{
image2D(level, internalFormat, size.x, size.y, border, format, type, data);
}
void Texture::compressedImage2D(const GLint level, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLint border, const GLsizei imageSize, const GLvoid * data)
{
bindlessImplementation().compressedImage2D(this, level, internalFormat, width, height, border, imageSize, data);
}
void Texture::compressedImage2D(const GLint level, const GLenum internalFormat, const glm::ivec2 & size, const GLint border, const GLsizei imageSize, const GLvoid * data)
{
compressedImage2D(level, internalFormat, size.x, size.y, border, imageSize, data);
}
void Texture::subImage2D(const GLint level, const GLint xOffset, const GLint yOffset, const GLsizei width, const GLsizei height, const GLenum format, const GLenum type, const GLvoid * data)
{
bindlessImplementation().subImage2D(this, level, xOffset, yOffset, width, height, format, type, data);
}
void Texture::subImage2D(const GLint level, const glm::ivec2& offset, const glm::ivec2& size, const GLenum format, const GLenum type, const GLvoid * data)
{
subImage2D(level, offset.x, offset.y, size.x, size.y, format, type, data);
}
void Texture::image3D(const GLint level, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLsizei depth, const GLint border, const GLenum format, const GLenum type, const GLvoid* data)
{
bindlessImplementation().image3D(this, level, internalFormat, width, height, depth, border, format, type, data);
}
void Texture::image3D(const GLint level, const GLenum internalFormat, const glm::ivec3 & size, const GLint border, const GLenum format, const GLenum type, const GLvoid* data)
{
image3D(level, internalFormat, size.x, size.y, size.z, border, format, type, data);
}
void Texture::compressedImage3D(const GLint level, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLsizei depth, const GLint border, const GLsizei imageSize, const GLvoid * data)
{
bindlessImplementation().compressedImage3D(this, level, internalFormat, width, height, depth, border, imageSize, data);
}
void Texture::compressedImage3D(GLint level, GLenum internalFormat, const glm::ivec3 & size, GLint border, GLsizei imageSize, const GLvoid * data)
{
compressedImage3D(level, internalFormat, size.x, size.y, size.z, border, imageSize, data);
}
void Texture::subImage3D(const GLint level, const GLint xOffset, const GLint yOffset, const GLint zOffset, const GLsizei width, const GLsizei height, const GLsizei depth, const GLenum format, const GLenum type, const GLvoid * data)
{
bindlessImplementation().subImage3D(this, level, xOffset, yOffset, zOffset, width, height, depth, format, type, data);
}
void Texture::subImage3D(const GLint level, const glm::ivec3& offset, const glm::ivec3& size, const GLenum format, const GLenum type, const GLvoid * data)
{
subImage3D(level, offset.x, offset.y, offset.z, size.x, size.y, size.z, format, type, data);
}
void Texture::image2DMultisample(const GLsizei samples, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLboolean fixedSamplesLocations)
{
bindlessImplementation().image2DMultisample(this, samples, internalFormat, width, height, fixedSamplesLocations);
}
void Texture::image2DMultisample(const GLsizei samples, const GLenum internalFormat, const glm::ivec2 & size, const GLboolean fixedSamplesLocations)
{
image2DMultisample(samples, internalFormat, size.x, size.y, fixedSamplesLocations);
}
void Texture::image3DMultisample(const GLsizei samples, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLsizei depth, const GLboolean fixedSamplesLocations)
{
bindlessImplementation().image3DMultisample(this, samples, internalFormat, width, height, depth, fixedSamplesLocations);
}
void Texture::image3DMultisample(const GLsizei samples, const GLenum internalFormat, const glm::ivec3 & size, const GLboolean fixedSamplesLocations)
{
image3DMultisample(samples, internalFormat, size.x, size.y, size.z, fixedSamplesLocations);
}
void Texture::storage1D(const GLsizei levels, const GLenum internalFormat, const GLsizei width)
{
storageImplementation().storage1D(this, levels, internalFormat, width);
}
void Texture::storage2D(const GLsizei levels, const GLenum internalFormat, const GLsizei width, const GLsizei height)
{
storageImplementation().storage2D(this, levels, internalFormat, width, height);
}
void Texture::storage2D(const GLsizei levels, const GLenum internalFormat, const glm::ivec2 & size)
{
storage2D(levels, internalFormat, size.x, size.y);
}
void Texture::storage3D(const GLsizei levels, const GLenum internalFormat, const GLsizei width, const GLsizei height, const GLsizei depth)
{
storageImplementation().storage3D(this, levels, internalFormat, width, height, depth);
}
void Texture::storage3D(const GLsizei levels, const GLenum internalFormat, const glm::ivec3 & size)
{
storage3D(levels, internalFormat, size.x, size.y, size.z);
}
void Texture::storage2DMultisample(GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSamplesLocations)
{
storageMultisampleImplementation().storage2DMultisample(this, samples, internalFormat, width, height, fixedSamplesLocations);
}
void Texture::storage2DMultisample(GLsizei samples, GLenum internalFormat, const glm::ivec2 & size, GLboolean fixedSamplesLocations)
{
storage2DMultisample(samples, internalFormat, size.x, size.y, fixedSamplesLocations);
}
void Texture::storage3DMultisample(GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSamplesLocations)
{
storageMultisampleImplementation().storage3DMultisample(this, samples, internalFormat, width, height, depth, fixedSamplesLocations);
}
void Texture::storage3DMultisample(GLsizei samples, GLenum internalFormat, const glm::ivec3 & size, GLboolean fixedSamplesLocations)
{
storage3DMultisample(samples, internalFormat, size.x, size.y, size.z, fixedSamplesLocations);
}
void Texture::textureView(const GLuint originalTexture, const GLenum internalFormat, const GLuint minLevel, const GLuint numLevels, const GLuint minLayer, const GLuint numLayers)
{
glTextureView(id(), m_target, originalTexture, internalFormat, minLevel, numLevels, minLayer, numLayers);
}
void Texture::texBuffer(const GLenum internalFormat, Buffer * buffer)
{
bindlessImplementation().texBuffer(this, internalFormat, buffer);
}
void Texture::texBufferRange(const GLenum internalFormat, Buffer * buffer, const GLintptr offset, const GLsizeiptr size)
{
bindlessImplementation().texBufferRange(this, internalFormat, buffer, offset, size);
}
void Texture::clearImage(const GLint level, const GLenum format, const GLenum type, const void * data)
{
glClearTexImage(id(), level, format, type, data);
}
void Texture::clearImage(const GLint level, const GLenum format, const GLenum type, const glm::vec4 & value)
{
clearImage(level, format, type, glm::value_ptr(value));
}
void Texture::clearImage(const GLint level, const GLenum format, const GLenum type, const glm::ivec4 & value)
{
clearImage(level, format, type, glm::value_ptr(value));
}
void Texture::clearImage(const GLint level, const GLenum format, const GLenum type, const glm::uvec4 & value)
{
clearImage(level, format, type, glm::value_ptr(value));
}
void Texture::clearSubImage(const GLint level, const GLint xOffset, const GLint yOffset, const GLint zOffset, const GLsizei width, const GLsizei height, const GLsizei depth, const GLenum format, const GLenum type, const void * data)
{
glClearTexSubImage(id(), level, xOffset, yOffset, zOffset, width, height, depth, format, type, data);
}
void Texture::clearSubImage(const GLint level, const glm::ivec3 & offset, const glm::ivec3 & size, const GLenum format, const GLenum type, const void * data)
{
clearSubImage(level, offset.x, offset.y, offset.z, size.x, size.y, size.z, format, type, data);
}
void Texture::clearSubImage(const GLint level, const glm::ivec3 & offset, const glm::ivec3 & size, const GLenum format, const GLenum type, const glm::vec4 & value)
{
clearSubImage(level, offset, size, format, type, glm::value_ptr(value));
}
void Texture::clearSubImage(const GLint level, const glm::ivec3 & offset, const glm::ivec3 & size, const GLenum format, const GLenum type, const glm::ivec4 & value)
{
clearSubImage(level, offset, size, format, type, glm::value_ptr(value));
}
void Texture::clearSubImage(const GLint level, const glm::ivec3 & offset, const glm::ivec3 & size, const GLenum format, const GLenum type, const glm::uvec4 & value)
{
clearSubImage(level, offset, size, format, type, glm::value_ptr(value));
}
void Texture::invalidateImage(GLint level) const
{
glInvalidateTexImage(id(), level);
}
void Texture::invalidateSubImage(GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth)
{
glInvalidateTexSubImage(id(), level, xoffset, yoffset, zoffset, width, height, depth);
}
void Texture::invalidateSubImage(GLint level, const glm::ivec3& offset, const glm::ivec3 size)
{
invalidateSubImage(level, offset.x, offset.y, offset.z, size.x, size.y, size.z);
}
void Texture::bindImageTexture(const GLuint unit, const GLint level, const GLboolean layered, const GLint layer, const GLenum access, const GLenum format) const
{
glBindImageTexture(unit, id(), level, layered, layer, access, format);
}
void Texture::unbindImageTexture(const GLuint unit)
{
// the concrete parameters (except unit & texture) don't seem to matter, as long as their values are valid
glBindImageTexture(unit, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8);
}
void Texture::generateMipmap()
{
bindlessImplementation().generateMipMap(this);
}
void Texture::cubeMapImage(gl::GLint level, gl::GLenum internalFormat, gl::GLsizei width, gl::GLsizei height, gl::GLint border, gl::GLenum format, gl::GLenum type, const gl::GLvoid * data)
{
bindlessImplementation().cubeMapImage(this, level, internalFormat, width, height, border, format, type, data);
}
void Texture::cubeMapImage(gl::GLint level, gl::GLenum internalFormat, const glm::ivec2 & size, gl::GLint border, gl::GLenum format, gl::GLenum type, const gl::GLvoid * data)
{
cubeMapImage(level, internalFormat, size.x, size.y, border, format, type, data);
}
TextureHandle Texture::textureHandle() const
{
return TextureHandle(this);
}
TextureHandle Texture::textureHandle(Sampler * sampler) const
{
return TextureHandle(this, sampler);
}
void Texture::pageCommitment(const GLint level, const GLint xOffset, const GLint yOffset, const GLint zOffset, const GLsizei width, const GLsizei height, const GLsizei depth, const GLboolean commit) const
{
bindlessImplementation().pageCommitment(this, level, xOffset, yOffset, zOffset, width, height, depth, commit);
}
void Texture::pageCommitment(const GLint level, const glm::ivec3& offset, const glm::ivec3& size, const GLboolean commit) const
{
pageCommitment(level, offset.x, offset.y, offset.z, size.x, size.y, size.z, commit);
}
GLenum Texture::objectType() const
{
return GL_TEXTURE;
}
} // namespace globjects
| 37.568826 | 233 | 0.742066 | [
"object",
"vector"
] |
100dacdcc3c4b5e9e7f10fe2811e639d3ad62a41 | 22,887 | cc | C++ | chrome/browser/extensions/external_provider_impl.cc | rzr/chromium-crosswalk | d391344809adf7b4f39764ac0e15c378169b805f | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | chrome/browser/extensions/external_provider_impl.cc | rzr/chromium-crosswalk | d391344809adf7b4f39764ac0e15c378169b805f | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/external_provider_impl.cc | rzr/chromium-crosswalk | d391344809adf7b4f39764ac0e15c378169b805f | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/external_provider_impl.h"
#include <set>
#include <vector>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/app_mode/app_mode_utils.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_management.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_component_loader.h"
#include "chrome/browser/extensions/external_policy_loader.h"
#include "chrome/browser/extensions/external_pref_loader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/crx_file/id_util.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/external_provider_interface.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
#include "chrome/browser/chromeos/customization/customization_document.h"
#include "chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/device_local_account.h"
#include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "components/user_manager/user.h"
#else
#include "chrome/browser/extensions/default_apps.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/extensions/external_registry_loader_win.h"
#endif
using content::BrowserThread;
namespace extensions {
// Constants for keeping track of extension preferences in a dictionary.
const char ExternalProviderImpl::kInstallParam[] = "install_parameter";
const char ExternalProviderImpl::kExternalCrx[] = "external_crx";
const char ExternalProviderImpl::kExternalVersion[] = "external_version";
const char ExternalProviderImpl::kExternalUpdateUrl[] = "external_update_url";
const char ExternalProviderImpl::kIsBookmarkApp[] = "is_bookmark_app";
const char ExternalProviderImpl::kIsFromWebstore[] = "is_from_webstore";
const char ExternalProviderImpl::kKeepIfPresent[] = "keep_if_present";
const char ExternalProviderImpl::kWasInstalledByOem[] = "was_installed_by_oem";
const char ExternalProviderImpl::kSupportedLocales[] = "supported_locales";
const char ExternalProviderImpl::kMayBeUntrusted[] = "may_be_untrusted";
ExternalProviderImpl::ExternalProviderImpl(
VisitorInterface* service,
const scoped_refptr<ExternalLoader>& loader,
Profile* profile,
Manifest::Location crx_location,
Manifest::Location download_location,
int creation_flags)
: crx_location_(crx_location),
download_location_(download_location),
service_(service),
ready_(false),
loader_(loader),
profile_(profile),
creation_flags_(creation_flags),
auto_acknowledge_(false) {
loader_->Init(this);
}
ExternalProviderImpl::~ExternalProviderImpl() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
loader_->OwnerShutdown();
}
void ExternalProviderImpl::VisitRegisteredExtension() {
// The loader will call back to SetPrefs.
loader_->StartLoading();
}
void ExternalProviderImpl::SetPrefs(base::DictionaryValue* prefs) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Check if the service is still alive. It is possible that it went
// away while |loader_| was working on the FILE thread.
if (!service_) return;
prefs_.reset(prefs);
ready_ = true; // Queries for extensions are allowed from this point.
// Set of unsupported extensions that need to be deleted from prefs_.
std::set<std::string> unsupported_extensions;
// Notify ExtensionService about all the extensions this provider has.
for (base::DictionaryValue::Iterator i(*prefs_); !i.IsAtEnd(); i.Advance()) {
const std::string& extension_id = i.key();
const base::DictionaryValue* extension = NULL;
if (!crx_file::id_util::IdIsValid(extension_id)) {
LOG(WARNING) << "Malformed extension dictionary: key "
<< extension_id.c_str() << " is not a valid id.";
continue;
}
if (!i.value().GetAsDictionary(&extension)) {
LOG(WARNING) << "Malformed extension dictionary: key "
<< extension_id.c_str()
<< " has a value that is not a dictionary.";
continue;
}
base::FilePath::StringType external_crx;
const base::Value* external_version_value = NULL;
std::string external_version;
std::string external_update_url;
bool has_external_crx = extension->GetString(kExternalCrx, &external_crx);
bool has_external_version = false;
if (extension->Get(kExternalVersion, &external_version_value)) {
if (external_version_value->IsType(base::Value::TYPE_STRING)) {
external_version_value->GetAsString(&external_version);
has_external_version = true;
} else {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". " << kExternalVersion
<< " value must be a string.";
continue;
}
}
bool has_external_update_url = extension->GetString(kExternalUpdateUrl,
&external_update_url);
if (has_external_crx != has_external_version) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". " << kExternalCrx
<< " and " << kExternalVersion << " must be used together.";
continue;
}
if (has_external_crx == has_external_update_url) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Exactly one of the "
<< "followng keys should be used: " << kExternalCrx
<< ", " << kExternalUpdateUrl << ".";
continue;
}
// Check that extension supports current browser locale.
const base::ListValue* supported_locales = NULL;
if (extension->GetList(kSupportedLocales, &supported_locales)) {
std::vector<std::string> browser_locales;
l10n_util::GetParentLocales(g_browser_process->GetApplicationLocale(),
&browser_locales);
size_t num_locales = supported_locales->GetSize();
bool locale_supported = false;
for (size_t j = 0; j < num_locales; j++) {
std::string current_locale;
if (supported_locales->GetString(j, ¤t_locale) &&
l10n_util::IsValidLocaleSyntax(current_locale)) {
current_locale = l10n_util::NormalizeLocale(current_locale);
if (std::find(browser_locales.begin(), browser_locales.end(),
current_locale) != browser_locales.end()) {
locale_supported = true;
break;
}
} else {
LOG(WARNING) << "Unrecognized locale '" << current_locale
<< "' found as supported locale for extension: "
<< extension_id;
}
}
if (!locale_supported) {
unsupported_extensions.insert(extension_id);
VLOG(1) << "Skip installing (or uninstall) external extension: "
<< extension_id << " because the extension doesn't support "
<< "the browser locale.";
continue;
}
}
int creation_flags = creation_flags_;
bool is_bookmark_app;
if (extension->GetBoolean(kIsBookmarkApp, &is_bookmark_app) &&
is_bookmark_app) {
creation_flags |= Extension::FROM_BOOKMARK;
}
bool is_from_webstore = false;
if (extension->GetBoolean(kIsFromWebstore, &is_from_webstore) &&
is_from_webstore) {
creation_flags |= Extension::FROM_WEBSTORE;
}
bool keep_if_present = false;
if (extension->GetBoolean(kKeepIfPresent, &keep_if_present) &&
keep_if_present && profile_) {
ExtensionServiceInterface* extension_service =
ExtensionSystem::Get(profile_)->extension_service();
const Extension* extension = extension_service ?
extension_service->GetExtensionById(extension_id, true) : NULL;
if (!extension) {
VLOG(1) << "Skip installing (or uninstall) external extension: "
<< extension_id << " because the extension should be kept "
<< "only if it is already installed.";
continue;
}
}
bool was_installed_by_oem = false;
if (extension->GetBoolean(kWasInstalledByOem, &was_installed_by_oem) &&
was_installed_by_oem) {
creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
}
bool may_be_untrusted = false;
if (extension->GetBoolean(kMayBeUntrusted, &may_be_untrusted) &&
may_be_untrusted) {
creation_flags |= Extension::MAY_BE_UNTRUSTED;
}
std::string install_parameter;
extension->GetString(kInstallParam, &install_parameter);
if (has_external_crx) {
if (crx_location_ == Manifest::INVALID_LOCATION) {
LOG(WARNING) << "This provider does not support installing external "
<< "extensions from crx files.";
continue;
}
if (external_crx.find(base::FilePath::kParentDirectory) !=
base::StringPiece::npos) {
LOG(WARNING) << "Path traversal not allowed in path: "
<< external_crx.c_str();
continue;
}
// If the path is relative, and the provider has a base path,
// build the absolute path to the crx file.
base::FilePath path(external_crx);
if (!path.IsAbsolute()) {
base::FilePath base_path = loader_->GetBaseCrxFilePath();
if (base_path.empty()) {
LOG(WARNING) << "File path " << external_crx.c_str()
<< " is relative. An absolute path is required.";
continue;
}
path = base_path.Append(external_crx);
}
Version version(external_version);
if (!version.IsValid()) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Invalid version string \""
<< external_version << "\".";
continue;
}
service_->OnExternalExtensionFileFound(extension_id, &version, path,
crx_location_, creation_flags,
auto_acknowledge_);
} else { // if (has_external_update_url)
CHECK(has_external_update_url); // Checking of keys above ensures this.
if (download_location_ == Manifest::INVALID_LOCATION) {
LOG(WARNING) << "This provider does not support installing external "
<< "extensions from update URLs.";
continue;
}
GURL update_url(external_update_url);
if (!update_url.is_valid()) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Key " << kExternalUpdateUrl
<< " has value \"" << external_update_url
<< "\", which is not a valid URL.";
continue;
}
service_->OnExternalExtensionUpdateUrlFound(extension_id,
install_parameter,
update_url,
download_location_,
creation_flags,
auto_acknowledge_);
}
}
for (std::set<std::string>::iterator it = unsupported_extensions.begin();
it != unsupported_extensions.end(); ++it) {
// Remove extension for the list of know external extensions. The extension
// will be uninstalled later because provider doesn't provide it anymore.
prefs_->Remove(*it, NULL);
}
service_->OnExternalProviderReady(this);
}
void ExternalProviderImpl::ServiceShutdown() {
service_ = NULL;
}
bool ExternalProviderImpl::IsReady() const {
return ready_;
}
bool ExternalProviderImpl::HasExtension(
const std::string& id) const {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(prefs_.get());
CHECK(ready_);
return prefs_->HasKey(id);
}
bool ExternalProviderImpl::GetExtensionDetails(
const std::string& id, Manifest::Location* location,
scoped_ptr<Version>* version) const {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(prefs_.get());
CHECK(ready_);
base::DictionaryValue* extension = NULL;
if (!prefs_->GetDictionary(id, &extension))
return false;
Manifest::Location loc = Manifest::INVALID_LOCATION;
if (extension->HasKey(kExternalUpdateUrl)) {
loc = download_location_;
} else if (extension->HasKey(kExternalCrx)) {
loc = crx_location_;
std::string external_version;
if (!extension->GetString(kExternalVersion, &external_version))
return false;
if (version)
version->reset(new Version(external_version));
} else {
NOTREACHED(); // Chrome should not allow prefs to get into this state.
return false;
}
if (location)
*location = loc;
return true;
}
// static
void ExternalProviderImpl::CreateExternalProviders(
VisitorInterface* service,
Profile* profile,
ProviderCollection* provider_list) {
scoped_refptr<ExternalLoader> external_loader;
scoped_refptr<ExternalLoader> external_recommended_loader;
extensions::Manifest::Location crx_location = Manifest::INVALID_LOCATION;
#if defined(OS_CHROMEOS)
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
bool is_chrome_os_public_session = false;
const user_manager::User* user =
chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
policy::DeviceLocalAccount::Type account_type;
if (user &&
connector->IsEnterpriseManaged() &&
policy::IsDeviceLocalAccountUser(user->email(), &account_type)) {
if (account_type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)
is_chrome_os_public_session = true;
policy::DeviceLocalAccountPolicyBroker* broker =
connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
user->email());
if (broker) {
external_loader = broker->extension_loader();
crx_location = Manifest::EXTERNAL_POLICY;
} else {
NOTREACHED();
}
} else {
external_loader = new ExternalPolicyLoader(
ExtensionManagementFactory::GetForBrowserContext(profile),
ExternalPolicyLoader::FORCED);
external_recommended_loader = new ExternalPolicyLoader(
ExtensionManagementFactory::GetForBrowserContext(profile),
ExternalPolicyLoader::RECOMMENDED);
}
#else
external_loader = new ExternalPolicyLoader(
ExtensionManagementFactory::GetForBrowserContext(profile),
ExternalPolicyLoader::FORCED);
external_recommended_loader = new ExternalPolicyLoader(
ExtensionManagementFactory::GetForBrowserContext(profile),
ExternalPolicyLoader::RECOMMENDED);
#endif
// Policies are mandatory so they can't be skipped with command line flag.
if (external_loader.get()) {
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(
service,
external_loader,
profile,
crx_location,
Manifest::EXTERNAL_POLICY_DOWNLOAD,
Extension::NO_FLAGS)));
}
// Load the KioskAppExternalProvider when running in kiosk mode.
if (chrome::IsRunningInForcedAppMode()) {
#if defined(OS_CHROMEOS)
chromeos::KioskAppManager* kiosk_app_manager =
chromeos::KioskAppManager::Get();
DCHECK(kiosk_app_manager);
if (kiosk_app_manager && !kiosk_app_manager->external_loader_created()) {
provider_list->push_back(linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(service,
kiosk_app_manager->CreateExternalLoader(),
profile,
Manifest::EXTERNAL_PREF,
Manifest::INVALID_LOCATION,
Extension::NO_FLAGS)));
}
#endif
return;
}
// Extensions provided by recommended policies.
if (external_recommended_loader.get()) {
provider_list->push_back(linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(service,
external_recommended_loader,
profile,
crx_location,
Manifest::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
}
// In tests don't install extensions from default external sources.
// It would only slowdown tests and make them flaky.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableDefaultApps))
return;
// On Mac OS, items in /Library/... should be written by the superuser.
// Check that all components of the path are writable by root only.
ExternalPrefLoader::Options check_admin_permissions_on_mac;
#if defined(OS_MACOSX)
check_admin_permissions_on_mac =
ExternalPrefLoader::ENSURE_PATH_CONTROLLED_BY_ADMIN;
#else
check_admin_permissions_on_mac = ExternalPrefLoader::NONE;
#endif
#if !defined(OS_WIN)
int bundled_extension_creation_flags = Extension::NO_FLAGS;
#endif
#if defined(OS_CHROMEOS)
bundled_extension_creation_flags = Extension::FROM_WEBSTORE |
Extension::WAS_INSTALLED_BY_DEFAULT;
if (!is_chrome_os_public_session) {
int external_apps_path_id = profile->IsSupervised() ?
chrome::DIR_SUPERVISED_USERS_DEFAULT_APPS :
chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS;
ExternalPrefLoader::Options pref_load_flags = profile->IsNewProfile() ?
ExternalPrefLoader::DELAY_LOAD_UNTIL_PRIORITY_SYNC :
ExternalPrefLoader::NONE;
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(new ExternalProviderImpl(
service,
new ExternalPrefLoader(external_apps_path_id,
pref_load_flags,
profile),
profile,
Manifest::EXTERNAL_PREF,
Manifest::EXTERNAL_PREF_DOWNLOAD,
bundled_extension_creation_flags)));
// OEM default apps.
int oem_extension_creation_flags =
bundled_extension_creation_flags | Extension::WAS_INSTALLED_BY_OEM;
chromeos::ServicesCustomizationDocument* customization =
chromeos::ServicesCustomizationDocument::GetInstance();
provider_list->push_back(linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(service,
customization->CreateExternalLoader(profile),
profile,
Manifest::EXTERNAL_PREF,
Manifest::EXTERNAL_PREF_DOWNLOAD,
oem_extension_creation_flags)));
}
#elif defined(OS_LINUX)
if (!profile->IsSupervised()) {
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(
service,
new ExternalPrefLoader(
chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS,
ExternalPrefLoader::NONE,
NULL),
profile,
Manifest::EXTERNAL_PREF,
Manifest::EXTERNAL_PREF_DOWNLOAD,
bundled_extension_creation_flags)));
}
#endif
if (!profile->IsSupervised()) {
#if defined(OS_WIN)
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(
service,
new ExternalRegistryLoader,
profile,
Manifest::EXTERNAL_REGISTRY,
Manifest::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
#else
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(
service,
new ExternalPrefLoader(chrome::DIR_EXTERNAL_EXTENSIONS,
check_admin_permissions_on_mac,
NULL),
profile,
Manifest::EXTERNAL_PREF,
Manifest::EXTERNAL_PREF_DOWNLOAD,
bundled_extension_creation_flags)));
// Define a per-user source of external extensions.
#if defined(OS_MACOSX)
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(
service,
new ExternalPrefLoader(chrome::DIR_USER_EXTERNAL_EXTENSIONS,
ExternalPrefLoader::NONE,
NULL),
profile,
Manifest::EXTERNAL_PREF,
Manifest::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
#endif
#endif
#if !defined(OS_CHROMEOS)
// The default apps are installed as INTERNAL but use the external
// extension installer codeflow.
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new default_apps::Provider(
profile,
service,
new ExternalPrefLoader(chrome::DIR_DEFAULT_APPS,
ExternalPrefLoader::NONE,
NULL),
Manifest::INTERNAL,
Manifest::INTERNAL,
Extension::FROM_WEBSTORE |
Extension::WAS_INSTALLED_BY_DEFAULT)));
#endif
provider_list->push_back(
linked_ptr<ExternalProviderInterface>(
new ExternalProviderImpl(
service,
new ExternalComponentLoader(profile),
profile,
Manifest::INVALID_LOCATION,
Manifest::EXTERNAL_COMPONENT,
Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT)));
}
}
} // namespace extensions
| 38.791525 | 91 | 0.649845 | [
"vector"
] |
100e7753c684bfdfc38ff33729ccdbfb93a1e87d | 4,469 | cpp | C++ | src/RecognitionSystem/XmlRecognition/source/XmlUtils.cpp | iago-suarez/TFG | 68315e6c48659231a6bd217f1fc2979ea8299e55 | [
"Apache-2.0"
] | null | null | null | src/RecognitionSystem/XmlRecognition/source/XmlUtils.cpp | iago-suarez/TFG | 68315e6c48659231a6bd217f1fc2979ea8299e55 | [
"Apache-2.0"
] | null | null | null | src/RecognitionSystem/XmlRecognition/source/XmlUtils.cpp | iago-suarez/TFG | 68315e6c48659231a6bd217f1fc2979ea8299e55 | [
"Apache-2.0"
] | null | null | null | //#include <iostream>
//#include <fstream>
//
//#include "../header/XmlUtils.h"
//#include "../../BehaviorLib/header/Detection.h"
//
//#include <opencv/cv.h>
//
//using namespace std;
//
//string detectionToXml(DetectionDto detection){
//
// stringstream result;
//
// int id = ((int) detection.id[0])*1000000 + ((int) detection.id[1])*1000 +
// ((int) detection.id[2]);
//
// result << "<object id=\"" << id << "\">" <<
// // "<orientation>45</orientation>
// "<box h=\"" << detection.position.height <<
// "\" w=\"" << detection.position.width <<
// "\" xc=\"" << detection.position.x <<
// "\" yc=\"" << detection.position.y << "\"/>" <<
//// <appearance>visible</appearance>
//// <hypothesislist>
//// <hypothesis evaluation="1.0" id="1" prev="1.0">
//// <movement evaluation="1.0">walking</movement>
//// <role evaluation="1.0">walker</role>
//// <context evaluation="1.0">immobile</context>
//// <situation evaluation="1.0">moving</situation>
//// </hypothesis>
//// </hypothesislist>
// "</object>";
//
// return result.str();
//}
//
//string frameToXml(cv::vector<DetectionDto> fPoints, int nFrame){
//
// stringstream result;
//
// result << "<frame number=\"" << nFrame << "\">" << "<objectlist>";
// for (int i=0; i < (int) fPoints.size(); i++) {
// //Print Detection
// result << detectionToXml(fPoints[i]);
// }
// //Print frame tail
// result << "</objectlist>" << "<grouplist/>" <<
// "</frame>" << std::endl;
//
// result << std::endl;
//
// return result.str();
//}
//
//
//string pathsToXml(std::map<int, DetectionDto> pathsMap){
//
// stringstream result;
// std::map<int, DetectionDto>::iterator iter = pathsMap.begin();
//
//
// result << "<trajectories>" << endl;
//
// while(iter != pathsMap.end()){
//
// result << " <trajectory id=\"" << iter->first << "\">" << endl;
//
// for (int i=0; i<iter->second.path.size(); i++){
// result << "\t<point frame=\"" << iter->second.path[i].nframe << "\" ";
// result << "abnormality=\"" << iter->second.path[i].abnormal_path_rate << "\" ";
// result << "x=\"" << iter->second.path[i].point.x << "\" ";
// result << "y=\"" << iter->second.path[i].point.y << "\"></point>" << endl;
// }
//
// result << " </trajectory>" << endl;
//
// iter++;
// }
// result << "</trajectories>" << endl;
//
// return result.str();
//}
//
//string getXmlFileHeader(){
// stringstream result;
// result << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> \n";
// result << "<!DOCTYPE dataset [\n";
// result << " <!ELEMENT dataset (objects,trajectories)>\n";
// result << " <!ELEMENT objects (frame*)>\n";
//
// result << " <!ELEMENT frame (objectlist, grouplist?)>\n";
// result << " <!ELEMENT objectlist (object*)>\n";
// result << " <!ELEMENT object (box, orientation?)>\n";
// result << " <!ELEMENT orientation (#PCDATA)>\n";
// result << " <!ELEMENT box EMPTY>\n";
// result << " <!ELEMENT grouplist (#PCDATA)>\n";
//
// result << " <!ELEMENT trajectories (trajectory*)>\n";
// result << " <!ELEMENT trajectory (point*)>\n";
// result << " <!ELEMENT point EMPTY>\n";
//
// result << " <!ATTLIST frame number CDATA #REQUIRED>\n";
// result << " <!ATTLIST object id CDATA #REQUIRED>\n";
//
// result << " <!ATTLIST box h CDATA #REQUIRED>\n";
// result << " <!ATTLIST box w CDATA #REQUIRED>\n";
// result << " <!ATTLIST box xc CDATA #REQUIRED>\n";
// result << " <!ATTLIST box yc CDATA #REQUIRED>\n";
//
// result << " <!ATTLIST trajectory id CDATA #REQUIRED>\n";
// result << " <!ATTLIST point abnormality CDATA #REQUIRED>\n";
// result << " <!ATTLIST point frame CDATA #REQUIRED>\n";
// result << " <!ATTLIST point x CDATA #REQUIRED>\n";
// result << " <!ATTLIST point y CDATA #REQUIRED>\n";
// result << " ]>\n";
//
// result << "<dataset>\n";
//
// return result.str();
//}
//
//string getXmlFileTail(){
// return "</dataset>\n";
//} | 35.752 | 93 | 0.488924 | [
"object",
"vector"
] |
1010334e96c948939ffac809deec49753ca26411 | 1,285 | cpp | C++ | POI/3/wie.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | 1 | 2018-12-14T07:51:26.000Z | 2018-12-14T07:51:26.000Z | POI/3/wie.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | null | null | null | POI/3/wie.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | 1 | 2019-06-23T10:34:19.000Z | 2019-06-23T10:34:19.000Z | #include <iostream>
#include <cstdio>
#include <vector>
#include <set>
using namespace std;
const int maxn = int(3e3)+5;
int n, A[maxn][4];
pair<int, int> loc[maxn];
vector<pair<int, int> > start[maxn];
void solve(int type)
{
set<pair<int, int> > active;
for(int i = 0;i < n;i++)
{
start[i].clear();
if(type) loc[i].second = -1;
else loc[i].first = -1;
}
for(int i = 0;i < n;i++)
{
start[A[i][type]].push_back(make_pair(A[i][type+2], i));
}
for(int x = 0;x < n;x++)
{
for(vector<pair<int, int> >::iterator it = start[x].begin();it != start[x].end();it++) active.insert(*it);
if(!active.empty())
{
while(!active.empty() && active.begin()->first < x) active.erase(active.begin());
pair<int, int> top = *active.begin();
active.erase(active.begin());
if(type) loc[top.second].second = x;
else loc[top.second].first = x;
}
}
}
void rekt()
{
printf("NIE\n");
exit(0);
}
int main(void)
{
scanf("%d", &n);
for(int i = 0;i < n;i++)
{
scanf("%d%d%d%d", &A[i][0], &A[i][1], &A[i][2], &A[i][3]);
A[i][0]--, A[i][1]--, A[i][2]--, A[i][3]--;
}
solve(0); solve(1);
for(int i = 0;i < n;i++)
{
if(loc[i].first == -1 || loc[i].second == -1) rekt();
}
for(int i = 0;i < n;i++)
{
printf("%d %d\n", loc[i].first+1, loc[i].second+1);
}
} | 19.469697 | 108 | 0.536965 | [
"vector"
] |
101161dfb565619dba221c47ff42c5b100142db0 | 20,592 | cpp | C++ | applications/mne_x/plugins/tmsi/tmsidriver.cpp | yvnxs/mne-cpp | 29c90a86f49c843b5f0ca8f9180cb38e0e774176 | [
"BSD-3-Clause"
] | 1 | 2021-05-18T08:33:44.000Z | 2021-05-18T08:33:44.000Z | applications/mne_x/plugins/tmsi/tmsidriver.cpp | yvnxs/mne-cpp | 29c90a86f49c843b5f0ca8f9180cb38e0e774176 | [
"BSD-3-Clause"
] | null | null | null | applications/mne_x/plugins/tmsi/tmsidriver.cpp | yvnxs/mne-cpp | 29c90a86f49c843b5f0ca8f9180cb38e0e774176 | [
"BSD-3-Clause"
] | null | null | null | //=============================================================================================================
/**
* @file tmsidriver.cpp
* @author Lorenz Esch <lorenz.esch@tu-ilmenau.de>;
* Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date September, 2013
*
* @section LICENSE
*
* Copyright (C) 2013, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Contains the implementation of the TMSIDriver class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "tmsidriver.h"
#include "tmsiproducer.h"
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace TMSIPlugin;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
TMSIDriver::TMSIDriver(TMSIProducer* pTMSIProducer)
: m_pTMSIProducer(pTMSIProducer)
, m_bDllLoaded(true)
, m_bInitDeviceSuccess(false)
, m_uiNumberOfChannels(138)
, m_uiSamplingFrequency(1024)
, m_uiSamplesPerBlock(1)
, m_bUseChExponent(false)
, m_bUseUnitGain(false)
, m_bUseUnitOffset(false)
, m_bWriteDriverDebugToFile(false)
, m_sOutputFilePath("/mne_x_plugins/resources/tmsi")
, m_bUseCommonAverage(false)
, m_bMeasureImpedances(false)
{
//Initialise NULL pointers
m_oLibHandle = NULL ;
m_HandleMaster = NULL;
m_PSPDPMasterDevicePath = NULL;
m_lSignalBuffer = NULL;
//Open library
// TCHAR Path[MAX_PATH];
// GetSystemDirectory(Path, sizeof(Path) / sizeof(TCHAR) );
// lstrcat(Path, _T("\\TMSiSDK.dll"));
// m_oLibHandle = LoadLibrary(Path);
//Check which driver dll to take: TMSiSDK.dll oder TMSiSDK32bit.dll
// if(TMSISDK)
#ifdef TAKE_TMSISDK_DLL //32 bit system & 64 bit (with 64 bit compiler)
m_oLibHandle = ::LoadLibrary(L"C:\\Windows\\System32\\TMSiSDK.dll");
#elif TAKE_TMSISDK_32_DLL //64 bit (with 32 bit compiler)
// if(TMSISDK32)
m_oLibHandle = ::LoadLibrary(L"C:\\Windows\\SysWOW64\\TMSiSDK32bit.dll");
#endif
//If dll can't be open return
if( m_oLibHandle == NULL)
{
cout << "Plugin TMSI - ERROR - Couldn't load DLL - Check if the driver for the TMSi USB Fiber Connector installed in the system dir" << endl;
m_bDllLoaded = false;
return;
}
//Load DLL methods for initializing the driver
__load_dll_func__(m_oFpOpen, POPEN, "Open");
__load_dll_func__(m_oFpClose, PCLOSE, "Close");
__load_dll_func__(m_oFpStart, PSTART, "Start");
__load_dll_func__(m_oFpStop, PSTOP, "Stop");
__load_dll_func__(m_oFpGetSignalFormat, PGETSIGNALFORMAT, "GetSignalFormat");
__load_dll_func__(m_oFpSetSignalBuffer, PSETSIGNALBUFFER, "SetSignalBuffer");
__load_dll_func__(m_oFpGetSamples, PGETSAMPLES, "GetSamples");
__load_dll_func__(m_oFpGetBufferInfo, PGETBUFFERINFO, "GetBufferInfo");
__load_dll_func__(m_oFpFree, PFREE, "Free");
__load_dll_func__(m_oFpLibraryInit, PLIBRARYINIT, "LibraryInit");
__load_dll_func__(m_oFpLibraryExit, PLIBRARYEXIT, "LibraryExit");
__load_dll_func__(m_oFpGetDeviceList, PGETDEVICELIST, "GetDeviceList");
__load_dll_func__(m_oFpGetFrontEndInfo, PGETFRONTENDINFO, "GetFrontEndInfo");
__load_dll_func__(m_oFpSetRefCalculation, PSETREFCALCULATION, "SetRefCalculation");
__load_dll_func__(m_oFpSetMeasuringMode, PSETMEASURINGMODE, "SetMeasuringMode");
__load_dll_func__(m_oFpGetErrorCode, PGETERRORCODE, "GetErrorCode");
cout << "Plugin TMSI - INFO - TMSIDriver() - Successfully loaded all DLL functions" << endl;
}
//*************************************************************************************************************
TMSIDriver::~TMSIDriver()
{
//cout << "TMSIDriver::~TMSIDriver()" << endl;
}
//*************************************************************************************************************
bool TMSIDriver::initDevice(int iNumberOfChannels,
int iSamplingFrequency,
int iSamplesPerBlock,
bool bUseChExponent,
bool bUseUnitGain,
bool bUseUnitOffset,
bool bWriteDriverDebugToFile,
QString sOutpuFilePath,
bool bUseCommonAverage,
bool bMeasureImpedance)
{
//Check if the driver DLL was loaded
if(!m_bDllLoaded)
return false;
//Set global variables
m_uiNumberOfChannels = iNumberOfChannels;
m_uiSamplingFrequency = iSamplingFrequency;
m_uiSamplesPerBlock = iSamplesPerBlock;
m_bUseChExponent = bUseChExponent;
m_bUseUnitGain = bUseUnitGain;
m_bUseUnitOffset = bUseUnitOffset;
m_bWriteDriverDebugToFile = bWriteDriverDebugToFile;
m_sOutputFilePath = sOutpuFilePath;
m_bUseCommonAverage = bUseCommonAverage;
m_bMeasureImpedances = bMeasureImpedance;
//Open file to write to
if(m_bWriteDriverDebugToFile)
m_outputFileStream.open("mne_x_plugins/resources/tmsi/TMSi_Driver_Debug.txt", ios::trunc); //ios::trunc deletes old file data
//Check if device handler already exists and a connection was established before
// if(m_HandleMaster != NULL)
// {
// m_oFpClose(m_HandleMaster);
// m_HandleMaster = NULL;
// }
int ErrorCode = 0;
m_HandleMaster = m_oFpLibraryInit(TMSiConnectionUSB, &ErrorCode);
if( ErrorCode != 0 )
{
cout << "Plugin TMSI - ERROR - initDevice() - Can not initialize library" << endl;
return false;
}
//Get the device list of connected devices
char **DeviceList = NULL;
int NrOfDevices=0;
DeviceList = m_oFpGetDeviceList(m_HandleMaster, &NrOfDevices);
if( NrOfDevices == 0 )
{
cout << "Plugin TMSI - ERROR - initDevice() - Frontend list NOT available - Maybe no devices are connected" << endl;
m_oFpLibraryExit(m_HandleMaster);
return false;
}
//Open device
BOOLEAN Status;
char *DeviceLocator = DeviceList[0] ;
Status = m_oFpOpen(m_HandleMaster, DeviceLocator);
//Stop the device from sampling. Just in case the device was not stopped correctly after the last sampling process
m_oFpStop(m_HandleMaster);
if(!Status)
{
cout << "Plugin TMSI - ERROR - initDevice() - Failed to open connected device" << endl;
m_oFpLibraryExit(m_HandleMaster);
return false;
}
// Turn on the impendance mode
ULONG impedanceMode = 3;
ULONG normalMode = 0;
if(m_bMeasureImpedances)
{
if(m_oFpSetMeasuringMode(m_HandleMaster, impedanceMode, 1))
cout << "Plugin TMSI - INFO - Now measuring impedances" << endl;
else
{
int ErrorCode = m_oFpGetErrorCode(m_HandleMaster);
cout << "Unable to set Measuremode impedance, errorcode = " << ErrorCode << endl;
}
}
else
m_oFpSetMeasuringMode(m_HandleMaster, normalMode, 0);
//Get information about the connected device
FRONTENDINFO FrontEndInfo;
Status = m_oFpGetFrontEndInfo(m_HandleMaster, &FrontEndInfo);
unsigned short serial, hwVersion, swVersion, baseSf, maxRS232, nrOfChannels;
if(!Status)
cout << "Plugin TMSI - ERROR - initDevice() - FrontendInfo NOT available" << endl;
else
{
serial = FrontEndInfo.Serial;
hwVersion = FrontEndInfo.HwVersion;
swVersion = FrontEndInfo.SwVersion;
baseSf = FrontEndInfo.BaseSf;
maxRS232 = FrontEndInfo.maxRS232;
nrOfChannels = FrontEndInfo.NrOfChannels;
}
// Set Ref Calculation
if(m_bUseCommonAverage)
{
BOOLEAN setRefCalculation = m_oFpSetRefCalculation(m_HandleMaster, 1);
if(setRefCalculation)
cout << "Plugin TMSI - INFO - initDevice() - Common average now active" << endl;
else
cout << "Plugin TMSI - INFO - initDevice() - Common average is inactive (Could not be initiated)" << endl;
}
//Get information about the signal format created by the device - UnitExponent, UnitGain, UnitOffSet
PSIGNAL_FORMAT pSignalFormat = m_oFpGetSignalFormat(m_HandleMaster, NULL);
if(pSignalFormat != NULL)
{
wcscpy_s(m_wcDeviceName, pSignalFormat->PortName);
m_ulSerialNumber = pSignalFormat->SerialNumber;
m_uiNumberOfAvailableChannels = pSignalFormat[0].Elements;
if(m_bWriteDriverDebugToFile)
m_outputFileStream << "Found "<< m_wcDeviceName << " device (" << m_ulSerialNumber << ") with " << m_uiNumberOfAvailableChannels << " available channels" << endl << endl;
for(uint i = 0 ; i < m_uiNumberOfAvailableChannels; i++ )
{
m_vExponentChannel.push_back(pSignalFormat[i].UnitExponent);
m_vUnitGain.push_back(pSignalFormat[i].UnitGain);
m_vUnitOffSet.push_back(pSignalFormat[i].UnitOffSet);
if(m_bWriteDriverDebugToFile)
m_outputFileStream << "Channel number: " << i << " has type " << pSignalFormat[i].Type << " , format " << pSignalFormat[i].Format << " exponent " << pSignalFormat[i].UnitExponent << " gain " << pSignalFormat[i].UnitGain << " offset " << pSignalFormat[i].UnitOffSet << endl;
}
if(m_bWriteDriverDebugToFile)
m_outputFileStream << endl;
}
//Initialise and set up (sample rate/frequency and buffer size) the internal driver signal buffer which is used by the driver to store the value
ULONG iSamplingFrequencyMilliHertz = m_uiSamplingFrequency*1000; //Times 1000 because the driver works in millihertz
ULONG iBufferSize = MAX_BUFFER_SIZE; //see TMSi doc file for more info. This size is not defined in bytes but in the number of elements which are to be sampled. A sample in this case is one conversion result for all input channels..
if(!m_oFpSetSignalBuffer(m_HandleMaster, &iSamplingFrequencyMilliHertz, &iBufferSize))
{
cout << "Plugin TMSI - ERROR - initDevice() - Failed to allocate signal buffer" << endl;
m_oFpLibraryExit(m_HandleMaster);
return false;
}
//Start the sampling process
bool start = m_oFpStart(m_HandleMaster);
if(!start)
{
cout << "Plugin TMSI - ERROR - initDevice() - Failed to start the sampling procedure" << endl;
m_oFpLibraryExit(m_HandleMaster);
return false;
}
//Create the buffers
//The sampling frequency is not needed here because it is only used to specify the internal buffer size used by the driver with setSignalBuffer()
m_lSignalBufferSize = m_uiSamplesPerBlock*m_uiNumberOfAvailableChannels*4;
m_lSignalBuffer = new LONG[m_lSignalBufferSize];
cout << "Plugin TMSI - INFO - initDevice() - The device has been connected and initialised successfully" << endl;
m_bInitDeviceSuccess = true;
return true;
}
//*************************************************************************************************************
bool TMSIDriver::uninitDevice()
{
//Clear the buffer which is used to store the received samples
m_vSampleBlockBuffer.clear();
//Check if the device was initialised
if(!m_bInitDeviceSuccess)
{
cout << "Plugin TMSI - ERROR - uninitDevice() - Device was not initialised - therefore can not be uninitialised" << endl;
return false;
}
//Check if the driver DLL was loaded
if(!m_bDllLoaded)
{
cout << "Plugin TMSI - ERROR - uninitDevice() - Driver DLL was not loaded" << endl;
return false;
}
//Close the output stream/file
if(m_outputFileStream.is_open() && m_bWriteDriverDebugToFile)
{
m_outputFileStream.close();
m_outputFileStream.clear();
}
if(!m_oFpStop(m_HandleMaster))
{
cout << "Plugin TMSI - ERROR - uninitDevice() - Failed to stop the device" << endl;
return false;
}
if(!m_oFpClose(m_HandleMaster))
{
cout << "Plugin TMSI - ERROR - uninitDevice() - Failed to close the device" << endl;
return false;
}
m_oFpLibraryExit(m_HandleMaster);
//Reset to NULL pointers
m_oLibHandle = NULL ;
m_HandleMaster = NULL;
m_PSPDPMasterDevicePath = NULL;
m_lSignalBuffer = NULL;
cout << "Plugin TMSI - INFO - uninitDevice() - Successfully uninitialised the device" << endl;
return true;
}
//*************************************************************************************************************
bool TMSIDriver::getSampleMatrixValue(MatrixXf& sampleMatrix)
{
//Check if the driver DLL was loaded
if(!m_bDllLoaded)
return false;
//Check if device was initialised and connected correctly
if(!m_bInitDeviceSuccess)
{
cout << "Plugin TMSI - ERROR - getSampleMatrixValue() - Cannot start to get samples from device because device was not initialised correctly" << endl;
return false;
}
sampleMatrix.setZero(); // Clear matrix - set all elements to zero
uint iSamplesWrittenToMatrix = 0;
int channelMax = 0;
int sampleMax = 0;
int sampleIterator = 0;
//get samples from device until the complete matrix is filled, i.e. the samples per block size is met
while(iSamplesWrittenToMatrix < m_uiSamplesPerBlock)
{
//Get sample block from device
LONG ulSizeSamples = m_oFpGetSamples(m_HandleMaster, (PULONG)m_lSignalBuffer, m_lSignalBufferSize);
LONG ulNumSamplesReceived = ulSizeSamples/(m_uiNumberOfAvailableChannels*4);
//Only do the next steps if there was at least one sample received, otherwise skip and wait until at least one sample was received
if(ulNumSamplesReceived > 0)
{
int actualSamplesWritten = 0; //Holds the number of samples which are actually written to the matrix in this while procedure
//Write the received samples to an extra buffer, so that they are not getting lost if too many samples were received. These are then written to the next matrix (block)
for(int i=0; i<ulNumSamplesReceived; i++)
{
for(uint j=i*m_uiNumberOfAvailableChannels; j<(i*m_uiNumberOfAvailableChannels)+m_uiNumberOfChannels; j++)
m_vSampleBlockBuffer.push_back((double)m_lSignalBuffer[j]);
}
//If the number of available channels is smaller than the number defined by the user -> set the channelMax to the smaller number
if(m_uiNumberOfAvailableChannels < m_uiNumberOfChannels)
channelMax = m_uiNumberOfAvailableChannels;
else
channelMax = m_uiNumberOfChannels;
//If the number of the samples which were already written to the matrix plus the last received number of samples is larger then the defined block size
//-> only fill until the matrix is completeley filled with samples. The other (unused) samples are still stored in the vector buffer m_vSampleBlockBuffer and will be used in the next matrix which is to be sent to the circular buffer
if(iSamplesWrittenToMatrix + ulNumSamplesReceived > m_uiSamplesPerBlock)
sampleMax = m_uiSamplesPerBlock - iSamplesWrittenToMatrix + sampleIterator;
else
sampleMax = ulNumSamplesReceived + sampleIterator;
//Read the needed number of samples from the vector buffer to store them in the matrix
for(; sampleIterator < sampleMax; sampleIterator++)
{
for(int channelIterator = 0; channelIterator < channelMax; channelIterator++)
{
sampleMatrix(channelIterator, sampleIterator) = ((m_vSampleBlockBuffer.first() * (m_bUseUnitGain ? m_vUnitGain[channelIterator] : 1)) + (m_bUseUnitOffset ? m_vUnitOffSet[channelIterator] : 0)) * (m_bUseChExponent ? pow(10., (double)m_vExponentChannel[channelIterator]) : 1);
m_vSampleBlockBuffer.pop_front();
}
actualSamplesWritten ++;
}
iSamplesWrittenToMatrix = iSamplesWrittenToMatrix + actualSamplesWritten;
}
if(m_outputFileStream.is_open() && m_bWriteDriverDebugToFile)
{
m_outputFileStream << "samples in buffer: " << m_vSampleBlockBuffer.size()/m_uiNumberOfChannels << endl;
m_outputFileStream << "ulSizeSamples: " << ulSizeSamples << endl;
m_outputFileStream << "ulNumSamplesReceived: " << ulNumSamplesReceived << endl;
m_outputFileStream << "sampleMax: " << sampleMax << endl;
m_outputFileStream << "sampleIterator: " << sampleIterator << endl;
m_outputFileStream << "iSamplesWrittenToMatrix: " << iSamplesWrittenToMatrix << endl << endl;
}
}
if(/*m_outputFileStream.is_open() &&*/ m_bWriteDriverDebugToFile)
{
//Get device buffer info
ULONG ulOverflow;
ULONG ulPercentFull;
m_oFpGetBufferInfo(m_HandleMaster, &ulOverflow, &ulPercentFull);
m_outputFileStream << "Unit offset: " << endl;
for(int w = 0; w<<m_vUnitOffSet.size(); w++)
cout << float(m_vUnitOffSet[w]) << " ";
m_outputFileStream << endl << endl;
m_outputFileStream << "Unit gain: " << endl;
for(int w = 0; w<<m_vUnitGain.size(); w++)
m_outputFileStream << float(m_vUnitGain[w]) << " ";
m_outputFileStream << endl << endl;
m_outputFileStream << "----------<See output file for sample matrix>----------" <<endl<<endl;
m_outputFileStream << "----------<Internal driver buffer is "<<ulPercentFull<<" full>----------"<<endl;
m_outputFileStream << "----------<Internal driver overflow is "<<ulOverflow<< ">----------"<<endl;
}
return true;
}
| 44.094218 | 295 | 0.609654 | [
"vector"
] |
10147d85f23720b7b1c5e9b9689a29d2fac401ce | 681 | hpp | C++ | plugins/community/repos/Bogaudio/src/Noise.hpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/Bogaudio/src/Noise.hpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/Bogaudio/src/Noise.hpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | #pragma once
#include "bogaudio.hpp"
#include "dsp/noise.hpp"
using namespace bogaudio::dsp;
extern Model* modelNoise;
namespace bogaudio {
struct Noise : Module {
enum ParamsIds {
NUM_PARAMS
};
enum InputsIds {
ABS_INPUT,
NUM_INPUTS
};
enum OutputsIds {
WHITE_OUTPUT,
PINK_OUTPUT,
RED_OUTPUT,
GAUSS_OUTPUT,
ABS_OUTPUT,
BLUE_OUTPUT,
NUM_OUTPUTS
};
enum LightsIds {
NUM_LIGHTS
};
BlueNoiseGenerator _blue;
WhiteNoiseGenerator _white;
PinkNoiseGenerator _pink;
RedNoiseGenerator _red;
GaussianNoiseGenerator _gauss;
Noise() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {}
void step() override;
};
} // namespace bogaudio
| 14.1875 | 69 | 0.734214 | [
"model"
] |
10152aaab360be5d9831e4f31771dd972832cffa | 12,824 | cpp | C++ | visa/Passes/InstCombine.cpp | ConiKost/intel-graphics-compiler | f5227c9658da35d08d7f711552ebcb12638ebc18 | [
"Intel",
"MIT"
] | 1 | 2020-09-03T17:11:47.000Z | 2020-09-03T17:11:47.000Z | visa/Passes/InstCombine.cpp | ConiKost/intel-graphics-compiler | f5227c9658da35d08d7f711552ebcb12638ebc18 | [
"Intel",
"MIT"
] | null | null | null | visa/Passes/InstCombine.cpp | ConiKost/intel-graphics-compiler | f5227c9658da35d08d7f711552ebcb12638ebc18 | [
"Intel",
"MIT"
] | null | null | null | /*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "InstCombine.hpp"
#include <functional>
#include <unordered_set>
using namespace vISA;
class InstCombiner
{
IR_Builder& builder;
// G4_Kernel& kernel;
FlowGraph& fg;
// Mem_Manager& mem;
// In occasions where we need to force GRF alignment of a scalar register
// (e.g. for targeting send payloads) we don't want to blow up register
// allocation; so we limit ourselves to just a few we should distinguish
// between variables that are global and those that are local.
static const int MAX_FORCE_ALIGNS = 2;
//
int forceAlignsLeft = MAX_FORCE_ALIGNS;
public:
InstCombiner(IR_Builder& _builder, FlowGraph& _fg)
: builder(_builder), fg(_fg)
{
}
void run();
private:
bool tryInstPropagate(INST_LIST_ITER iitr, INST_LIST_ITER eitr);
}; // InstCombiner
void vISA::InstCombine(
IR_Builder& builder,
FlowGraph& fg)
{
InstCombiner ic(builder, fg);
ic.run();
}
void InstCombiner::run()
{
for (BB_LIST_ITER bitr = fg.begin(); bitr != fg.end(); ++bitr) {
G4_BB* bb = *bitr;
bb->resetLocalIds();
INST_LIST_ITER iitr = bb->begin(), eitr = bb->end();
while (iitr != eitr)
{
G4_INST *defInst = *iitr;
G4_Operand *defDst = defInst->getDst();
if (!defDst) {
iitr++;
continue;
}
builder.doConsFolding(defInst);
builder.doSimplification(defInst);
if (tryInstPropagate(iitr, eitr)) {
INST_LIST_ITER tmp = iitr;
iitr++;
bb->erase(tmp);
} else {
iitr++;
}
} // for insts in bb
} // for blocks
}
// TMP = def (...) A, B
// ...
// A = op ... (prevents us from propagating: A and B)
// ...
// ... = use ... TMP
//
// prevents us from forwarding
static bool hasAntiDependenceBetweenLastUse(
INST_LIST_ITER iitr, INST_LIST_ITER eitr)
{
// find the furthest use
G4_INST* inst = *iitr;
G4_INST* lastUse = inst->use_front().first;
for (USE_EDGE_LIST_ITER iter = inst->use_begin(),
uend = inst->use_end(); iter != uend; ++iter)
{
G4_INST* useInst = iter->first;
if (useInst->getLocalId() > lastUse->getLocalId()) {
lastUse = useInst;
}
}
INST_LIST_ITER forwardIter = iitr;
forwardIter++;
while (forwardIter != eitr && *forwardIter != lastUse) {
if ((*forwardIter)->isWARdep(inst)) {
return true;
}
forwardIter++;
}
MUST_BE_TRUE(forwardIter != eitr, "hit end of block without finding use");
return false;
}
// Returns true sure there is a lifetime.end for any of the sources of the
// defining inst.
//
// add T, A, B
// ...
// lifetime.end A << cannot propagate A past this
// ...
// op ..., T, ...
//
static bool hasLifetimeEndBetweenLastUse(
INST_LIST_ITER iitr,
INST_LIST_ITER eitr,
const G4_INST *useInst,
const G4_Operand *defSrc0,
const G4_Operand *defSrc1 = nullptr,
const G4_Operand *defSrc2 = nullptr)
{
auto findDecl = [&](const G4_Operand *defSrc) {
const G4_SrcRegRegion *defSrcRegRgn =
defSrc && defSrc->isSrcRegRegion() ? defSrc->asSrcRegRegion() : nullptr;
const G4_Declare* currInstDclSrc =
defSrcRegRgn ? defSrcRegRgn->getBaseRegVarRootDeclare() : nullptr;
return currInstDclSrc;
};
const G4_Declare* currInstDclSrc0 = findDecl(defSrc0);
const G4_Declare* currInstDclSrc1 = findDecl(defSrc1);
const G4_Declare* currInstDclSrc2 = findDecl(defSrc2);
INST_LIST_ITER cpIter = iitr;
cpIter++;
while (*cpIter != useInst)
{
if ((*cpIter)->isLifeTimeEnd()) {
// Check whether lifetime end is for same opnd
const G4_Declare* lifetimeEndTopDcl = GetTopDclFromRegRegion((*cpIter)->getSrc(0));
if (lifetimeEndTopDcl == currInstDclSrc0 ||
lifetimeEndTopDcl == currInstDclSrc1 ||
lifetimeEndTopDcl == currInstDclSrc2)
{
return true;
}
}
cpIter++;
if (cpIter == eitr) // end of block
return false;
}
return false;
}
// integer folds:
// add T, s0, s1; add *, *, T ==> add3 *, s0, s1, T
// add T, s0, s1; add *, T, * ==> add3 *, T, s0, s1
//
// add T, s0, immA; add *, T, immB ==> add *, s0, (immA+immB)
// (we could do this via add3 and reduction again)
//
// TODO:
// mul T, s0, s1 -> add *, T, * ==> mad *, *, s0, s1
// mul T, s0, s1 -> add *, *, T ==> mad *, s0, s1, *
//
// shl T, s0 << N -> add *, X, T ==> mad X, s0, 2^n
//
// logic -> logic ==> bfn
bool InstCombiner::tryInstPropagate(
INST_LIST_ITER iitr, INST_LIST_ITER eitr)
{
G4_INST *defInst = *iitr;
if (!defInst->canPropagateBinaryToTernary()) {
return false;
} else if (defInst->use_size() == 0) {
return false; // probably unreachable, but keep for sanity sake
} else if (hasAntiDependenceBetweenLastUse(iitr, eitr)) {
return false; // someone clobbers one of the def() sources before the use()
}
bool canFoldAdd3 = getGenxPlatform() >= XeHP_SDV;
// defer folding until we can prove all uses can be done
std::vector<std::function<void()>> applyUses;
//
std::unordered_set<G4_Declare*> grfForcedAlignments;
std::unordered_set<G4_INST *> usedAddsTargetedToAdd3;
G4_Operand *defSrc0 = defInst->getSrc(0);
G4_Operand *defSrc1 = defInst->getSrc(1);
bool defIsSimd1WrEn = defInst->getExecSize() == 1 && defInst->isWriteEnableInst();
// OKAY
// def (E)
// use (E)
//
// (W) def (1)
// use (E)
//
// (W) def (E)
// (W) use (E)
auto execInfoCanCanPropagate = [&](const G4_INST *useInst) {
return defIsSimd1WrEn ||
(defInst->isWriteEnableInst() == useInst->isWriteEnableInst() &&
defInst->getExecLaneMask() == useInst->getExecLaneMask());
};
// copy def[fromDefSrcIx] to toUseInst[toUseSrcIx]
auto copyOperand = [&](
Gen4_Operand_Number fromDefSrcIx,
G4_INST *toUseInst,
Gen4_Operand_Number toUseSrcIx)
{
G4_Operand *oldUseSrc = toUseInst->getSrc(toUseSrcIx - 1);
if (oldUseSrc) {
toUseInst->removeDefUse(toUseSrcIx);
}
G4_Operand *defSrc = defInst->getSrc(fromDefSrcIx - 1);
G4_Operand *newUseSrc = builder.duplicateOperand(defSrc);
toUseInst->setSrc(newUseSrc, toUseSrcIx - 1);
// for all defs of defInst targeting defSrcIx copy those defs over
defInst->copyDef(toUseInst, fromDefSrcIx, toUseSrcIx);
};
// check if each use can be combined
for (USE_EDGE_LIST_ITER uitr = defInst->use_begin();
uitr != defInst->use_end();
uitr++)
{
G4_INST *useInst = uitr->first;
// copies toUseSrcA from def
auto copyOperandsToUseSrcs = [&](
Gen4_Operand_Number toUseSrcA,
Gen4_Operand_Number toUseSrcB)
{
copyOperand(Opnd_src0, useInst, toUseSrcA);
copyOperand(Opnd_src1, useInst, toUseSrcB);
};
if (hasLifetimeEndBetweenLastUse(iitr, eitr, useInst, defSrc0, defSrc1)) {
return false;
}
auto opsAre = [&] (G4_opcode defOp, G4_opcode useOp) {
return defInst->opcode() == defOp && useInst->opcode() == useOp;
};
G4_Operand *useSrcOpnd = nullptr, *useOtherSrcOpnd = nullptr;
if (uitr->second == Opnd_src0) {
useSrcOpnd = useInst->getSrc(0);
useOtherSrcOpnd = useInst->getSrc(1);
} else if (uitr->second == Opnd_src1) {
useSrcOpnd = useInst->getSrc(1);
useOtherSrcOpnd = useInst->getSrc(0);
} else {
return false;
}
// similar criteria from G4_INST::canPropagateTo
if (useSrcOpnd->getType() != defInst->getDst()->getType()) {
return false; // don't bother with type conversion
} else if (useInst->isLifeTimeEnd()) {
return false;
} else if (useInst->getPredicate()) {
return false; // punt on predication (could match predicates)
} else if (useInst->getDst() == nullptr) {
return false; // e.g. G4_pseudo_fcall
} else if (!execInfoCanCanPropagate(useInst)) {
return false; // e.g. oddball ExecSize/NoMask combinations
}
const bool ENABLE_ADD_FOLD = false; // TODO: incrementally enable
if (ENABLE_ADD_FOLD && opsAre(G4_add, G4_add)) {
// see if we can reassociate the source operands
// add T, s0, immA
// add dst, T, immB
// =>
// add dst, s0, (immA + immB)
// (there's an older reassoc pass, but we need to do it
// here since other folds in this pass can generate the pattern
// and we don't want to ping/pong between these passes)
const Gen4_Operand_Number useSrcIx = (*uitr).second;
bool foldedChainedAdds = false;
if ((defSrc0->isImm() || defSrc1->isImm()) && useOtherSrcOpnd->isImm())
{
int64_t imm = useOtherSrcOpnd->asImm()->getImm();
Gen4_Operand_Number defVarSrcIx = Opnd_src0;
if (defSrc0->isImm()) {
imm += defSrc0->asImm()->getImm();
defVarSrcIx = Opnd_src1;
} else {
imm += defSrc1->asImm()->getImm();
defVarSrcIx = Opnd_src0;
}
if (imm >= std::numeric_limits<int32_t>::min() ||
imm <= std::numeric_limits<int32_t>::max())
{
foldedChainedAdds = true;
applyUses.emplace_back(
[&]() {
copyOperand(defVarSrcIx, useInst, useSrcIx);
G4_Imm *foldedImm =
builder.createImmWithLowerType(imm, useInst->getExecType());
unsigned ix = (useSrcIx == Opnd_src0 ? Opnd_src1 : Opnd_src0) - 1;
useInst->setSrc(foldedImm, ix);
});
}
} // chained add
// if that fails, but we have an add3 operation then we can make
// add T, s0, s1
// add dst, T, s2
// =>
// add3 dst, s0, s1, s2
if (!foldedChainedAdds && canFoldAdd3) {
if (usedAddsTargetedToAdd3.find(useInst) != usedAddsTargetedToAdd3.end()) {
// FIXME: this needs to handle folding to the same target add
// add D2 = D0 D1
// add ... = D2 D2
// This will show up as dual uses (src0 and src1)
// and will want to expand around both slots.
// So it will become (assume use in src0 slot folds first):
// add3 ... = D0 D2 D1
// then the next application clobbers this...
//
// TODO: apply a better identity here (turn into a mad)
return false;
}
usedAddsTargetedToAdd3.insert(useInst);
applyUses.emplace_back(
[&]() {
// promote the second add to an add3;
// replace src2 and the transitive operand
// (which can be either src0 or src1)
useInst->setOpcode(G4_add3);
if (useSrcIx == Opnd_src1) {
copyOperandsToUseSrcs(Opnd_src1, Opnd_src2);
defInst->copyDef(useInst, Opnd_src1, Opnd_src1);
} else {
copyOperandsToUseSrcs(Opnd_src0, Opnd_src2);
}
});
}
} else {
// unsupported pattern
return false;
}
} // for uses
// commit the changes
for (auto &apply : applyUses) {
apply();
}
// unlink our def and use pairs (defInst is being removed)
defInst->removeDefUse(Opnd_src0);
defInst->removeDefUse(Opnd_src1);
forceAlignsLeft -= (int)grfForcedAlignments.size();
return true;
} | 34.659459 | 95 | 0.541173 | [
"vector"
] |
101828496ccee40c2238d7f0d7dfcacccc0caa1d | 13,349 | cpp | C++ | test/module/irohad/validation/stateful_validator_test.cpp | artyom-yurin/iroha-archive | 1ad3a149d21d30e99c650a9a4bad88b2792d751d | [
"Apache-2.0"
] | 31 | 2019-04-17T19:32:05.000Z | 2022-02-05T01:35:02.000Z | test/module/irohad/validation/stateful_validator_test.cpp | artyom-yurin/iroha-archive | 1ad3a149d21d30e99c650a9a4bad88b2792d751d | [
"Apache-2.0"
] | 1 | 2021-06-01T23:38:54.000Z | 2021-06-01T23:38:54.000Z | test/module/irohad/validation/stateful_validator_test.cpp | artyom-yurin/iroha-archive | 1ad3a149d21d30e99c650a9a4bad88b2792d751d | [
"Apache-2.0"
] | 12 | 2019-06-03T10:31:31.000Z | 2021-12-13T12:17:15.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "validation/impl/stateful_validator_impl.hpp"
#include <gtest/gtest.h>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm_ext/push_back.hpp>
#include "backend/protobuf/proto_proposal_factory.hpp"
#include "common/result.hpp"
#include "cryptography/crypto_provider/crypto_defaults.hpp"
#include "framework/test_logger.hpp"
#include "interfaces/iroha_internal/batch_meta.hpp"
#include "interfaces/iroha_internal/transaction_batch_parser_impl.hpp"
#include "interfaces/transaction.hpp"
#include "module/irohad/ametsuchi/ametsuchi_mocks.hpp"
#include "module/shared_model/builders/protobuf/test_proposal_builder.hpp"
#include "module/shared_model/builders/protobuf/test_transaction_builder.hpp"
#include "module/shared_model/interface_mocks.hpp"
#include "validation/utils.hpp"
using namespace iroha::validation;
using namespace shared_model::crypto;
using ::testing::_;
using ::testing::A;
using ::testing::ByMove;
using ::testing::ByRef;
using ::testing::Eq;
using ::testing::Return;
using ::testing::ReturnArg;
class SignaturesSubset : public testing::Test {
public:
std::vector<PublicKey> keys{PublicKey("a"), PublicKey("b"), PublicKey("c")};
};
/**
* @given three different keys and three signatures with the same keys
* @when signaturesSubset is executed
* @then returned true
*/
TEST_F(SignaturesSubset, Equal) {
std::array<MockSignature, 3> signatures;
for (size_t i = 0; i < signatures.size(); ++i) {
EXPECT_CALL(signatures[i], publicKey())
.WillRepeatedly(testing::ReturnRef(keys[i]));
}
ASSERT_TRUE(signaturesSubset(signatures, keys));
}
/**
* @given two different keys and two signatures with the same keys plus
* additional one
* @when signaturesSubset is executed
* @then returned false
*/
TEST_F(SignaturesSubset, Lesser) {
std::vector<PublicKey> subkeys{keys.begin(), keys.end() - 1};
std::array<MockSignature, 3> signatures;
for (size_t i = 0; i < signatures.size(); ++i) {
EXPECT_CALL(signatures[i], publicKey())
.WillRepeatedly(testing::ReturnRef(keys[i]));
}
ASSERT_FALSE(signaturesSubset(signatures, subkeys));
}
/**
* @given three different keys and two signatures with the first pair of keys
* @when signaturesSubset is executed
* @then returned true
*/
TEST_F(SignaturesSubset, StrictSubset) {
std::array<MockSignature, 2> signatures;
for (size_t i = 0; i < signatures.size(); ++i) {
EXPECT_CALL(signatures[i], publicKey())
.WillRepeatedly(testing::ReturnRef(keys[i]));
}
ASSERT_TRUE(signaturesSubset(signatures, keys));
}
/**
* @given two same keys and two signatures with different keys
* @when signaturesSubset is executed
* @then returned false
*/
TEST_F(SignaturesSubset, PublickeyUniqueness) {
std::vector<PublicKey> repeated_keys{2, keys[0]};
std::array<MockSignature, 2> signatures;
for (size_t i = 0; i < signatures.size(); ++i) {
EXPECT_CALL(signatures[i], publicKey())
.WillRepeatedly(testing::ReturnRef(keys[i]));
}
ASSERT_FALSE(signaturesSubset(signatures, repeated_keys));
}
class Validator : public testing::Test {
public:
void SetUp() override {
factory = std::make_unique<shared_model::proto::ProtoProposalFactory<
shared_model::validation::DefaultProposalValidator>>();
parser =
std::make_shared<shared_model::interface::TransactionBatchParserImpl>();
sfv = std::make_shared<StatefulValidatorImpl>(
std::move(factory),
std::move(parser),
getTestLogger("StatefulValidator"));
temp_wsv_mock = std::make_shared<iroha::ametsuchi::MockTemporaryWsv>();
}
auto createBatch(std::vector<std::string> creators,
shared_model::interface::types::BatchType batch_type) {
std::vector<shared_model::interface::types::HashType> reduced_hashes;
std::vector<shared_model::proto::Transaction> txs;
auto current_time = iroha::time::now();
for (size_t i = 0; i < creators.size(); ++i) {
auto tx = TestTransactionBuilder()
.creatorAccountId(creators[i])
.createdTime(current_time + i)
.quorum(1)
.createAsset("doge", "coin", 1)
.build();
reduced_hashes.push_back(tx.reducedHash());
}
for (size_t i = 0; i < creators.size(); ++i) {
txs.push_back(TestTransactionBuilder()
.creatorAccountId(creators[i])
.createdTime(current_time + i)
.quorum(1)
.createAsset("doge", "coin", 1)
.batchMeta(batch_type, reduced_hashes)
.build());
}
return txs;
}
std::shared_ptr<StatefulValidator> sfv;
std::unique_ptr<shared_model::interface::UnsafeProposalFactory> factory;
std::shared_ptr<iroha::ametsuchi::MockTemporaryWsv> temp_wsv_mock;
std::shared_ptr<shared_model::interface::TransactionBatchParser> parser;
const uint32_t sample_error_code = 2;
const std::string sample_error_extra = "account_id: doge@account";
};
/**
* @given several valid transactions
* @when statefully validating these transactions
* @then all of them will appear in verified proposal @and errors will be empty
*/
TEST_F(Validator, AllTxsValid) {
std::vector<shared_model::proto::Transaction> txs;
txs.push_back(TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("doge", "coin", 1)
.build());
txs.push_back(TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("doge", "coin", 1)
.build());
txs.push_back(TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("doge", "coin", 1)
.build());
auto proposal = TestProposalBuilder()
.createdTime(iroha::time::now())
.height(3)
.transactions(txs)
.build();
EXPECT_CALL(*temp_wsv_mock, apply(_))
.WillRepeatedly(Return(iroha::expected::Value<void>({})));
auto verified_proposal_and_errors = sfv->validate(proposal, *temp_wsv_mock);
ASSERT_EQ(
verified_proposal_and_errors->verified_proposal->transactions().size(),
3);
ASSERT_TRUE(verified_proposal_and_errors->rejected_transactions.empty());
}
/**
* @given several valid and a couple of invalid transactions
* @when statefully validating these transactions
* @then valid transactions will appear in verified proposal @and invalid ones
* will appear in errors
*/
TEST_F(Validator, SomeTxsFail) {
std::vector<shared_model::proto::Transaction> txs;
// valid tx
txs.push_back(TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("doge", "coin", 1)
.build());
// invalid tx
txs.push_back(TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("cate", "coin", 1)
.build());
// valid tx
txs.push_back(TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("doge", "coin", 1)
.build());
auto proposal = TestProposalBuilder()
.createdTime(iroha::time::now())
.height(3)
.transactions(txs)
.build();
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs.at(0)))))
.WillRepeatedly(Return(iroha::expected::Value<void>({})));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs.at(1)))))
.WillOnce(Return(iroha::expected::makeError(
CommandError{"", sample_error_code, sample_error_extra, true})));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs.at(2)))))
.WillRepeatedly(Return(iroha::expected::Value<void>({})));
auto verified_proposal_and_errors = sfv->validate(proposal, *temp_wsv_mock);
ASSERT_EQ(
verified_proposal_and_errors->verified_proposal->transactions().size(),
2);
ASSERT_EQ(verified_proposal_and_errors->rejected_transactions.size(), 1);
EXPECT_EQ(verified_proposal_and_errors->rejected_transactions.begin()
->error.error_code,
sample_error_code);
EXPECT_EQ(verified_proposal_and_errors->rejected_transactions.begin()
->error.error_extra,
sample_error_extra);
}
/**
* @given two atomic batches @and one ordered @and several single transactions
* @when failing one of the atomic batched @and transaction from ordered batch
* @and transaction from single group
* @then verified proposal will contain transactions from non-failed atomic
* batch, non-failed part of ordered batch, non-failed transactions from single
* group @and errors will contain exactly one error (for failed atomic batch)
*/
TEST_F(Validator, Batches) {
auto single_tx = TestTransactionBuilder()
.creatorAccountId("doge@master")
.createdTime(iroha::time::now())
.quorum(1)
.createAsset("doge", "coin", 1)
.build();
auto success_atomic_batch =
createBatch(std::vector<std::string>{"creator@d1", "creator@d2"},
shared_model::interface::types::BatchType::ATOMIC);
auto failed_atomic_batch =
createBatch(std::vector<std::string>{"creator@d3", "creator@d4"},
shared_model::interface::types::BatchType::ATOMIC);
auto ordered_batch =
createBatch(std::vector<std::string>{"creator@d5", "creator@d6"},
shared_model::interface::types::BatchType::ORDERED);
std::vector<shared_model::proto::Transaction> txs;
txs.push_back(std::move(single_tx));
txs.push_back(ordered_batch[0]);
txs.push_back(ordered_batch[1]);
txs.push_back(failed_atomic_batch[0]);
txs.push_back(failed_atomic_batch[1]);
txs.push_back(success_atomic_batch[0]);
txs.push_back(success_atomic_batch[1]);
auto proposal = TestProposalBuilder()
.createdTime(iroha::time::now())
.height(1)
.transactions(txs)
.build();
// calls to create savepoints, one per each atomic batch
EXPECT_CALL(*temp_wsv_mock,
createSavepoint("batch_" + failed_atomic_batch[0].hash().hex()))
.WillOnce(Return(
ByMove(std::make_unique<
iroha::ametsuchi::MockTemporaryWsvSavepointWrapper>())));
EXPECT_CALL(*temp_wsv_mock,
createSavepoint("batch_" + success_atomic_batch[0].hash().hex()))
.WillOnce(Return(
ByMove(std::make_unique<
iroha::ametsuchi::MockTemporaryWsvSavepointWrapper>())));
// calls to validate transactions, one per each transaction except those,
// which are in failed atomic batch - there only calls before the failed
// transaction are needed
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs[0]))))
.WillOnce(Return(iroha::expected::Value<void>({})));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs[1]))))
.WillOnce(Return(iroha::expected::Value<void>({})));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs[2]))))
.WillOnce(Return(iroha::expected::Value<void>({})));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs[3]))))
.WillOnce(Return(iroha::expected::makeError(
CommandError({"", sample_error_code, sample_error_extra, false}))));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs[5]))))
.WillOnce(Return(iroha::expected::Value<void>({})));
EXPECT_CALL(*temp_wsv_mock, apply(Eq(ByRef(txs[6]))))
.WillOnce(Return(iroha::expected::Value<void>({})));
auto verified_proposal_and_errors = sfv->validate(proposal, *temp_wsv_mock);
ASSERT_EQ(
verified_proposal_and_errors->verified_proposal->transactions().size(),
5);
ASSERT_EQ(verified_proposal_and_errors->rejected_transactions.size(),
failed_atomic_batch.size());
EXPECT_EQ(
verified_proposal_and_errors->rejected_transactions[0].error.error_code,
sample_error_code);
EXPECT_EQ(
verified_proposal_and_errors->rejected_transactions[0].error.error_extra,
sample_error_extra);
EXPECT_EQ(verified_proposal_and_errors->rejected_transactions[0].tx_hash,
txs[3].hash());
EXPECT_EQ(
verified_proposal_and_errors->rejected_transactions[1].error.error_code,
1);
EXPECT_EQ(
verified_proposal_and_errors->rejected_transactions[1].error.error_extra,
"Another transaction failed the batch");
EXPECT_EQ(verified_proposal_and_errors->rejected_transactions[1].tx_hash,
txs[4].hash());
}
| 39.146628 | 80 | 0.65136 | [
"vector"
] |
101889a5c9ec1b89fb697f8c5bb0f587fa1ca153 | 8,679 | cpp | C++ | Furiosity/Svg/Canvas.cpp | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 7 | 2015-05-14T18:36:18.000Z | 2020-08-30T19:09:33.000Z | Furiosity/Svg/Canvas.cpp | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 1 | 2015-10-23T14:24:08.000Z | 2015-10-23T14:24:08.000Z | Furiosity/Svg/Canvas.cpp | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 1 | 2020-07-31T23:34:49.000Z | 2020-07-31T23:34:49.000Z | ////////////////////////////////////////////////////////////////////////////////
// Canvas.cpp
//
// Created by Gerard Meier on 7/19/13.
// Copyright (c) 2013 Game Oven. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#include "Canvas.h"
#include <limits>
#include "Triangulate.h"
using namespace Furiosity;
Canvas::Canvas()
{
vbo[0] = vbo[1] = -1;
// Default Canvas does nothing, nor can it be rendered.
}
Canvas::~Canvas()
{
glDeleteBuffers(2, vbo);
vbo[0] = vbo[1] = -1;
}
bool Canvas::IsValid() {
return glIsBuffer(vbo[0] && glIsBuffer(vbo[1]));
}
void Canvas::Invalidate()
{
glDeleteBuffers(2, vbo);
vbo[0] = vbo[1] = -1;
}
void Canvas::Compile()
{
if(vbo[0] != -1 || vbo[1] != -1)
{
ERROR("vgResource::Compile() - the VBOs are already uploaded. Cannot call twice.");
return;
}
if(vertices.empty()) {
ERROR("Cannot upload canvas without vertices.");
return;
}
if(indices.empty()) {
ERROR("Cannot upload canvas without indices.");
return;
}
// From this point onwards, we upload all vertices:
glGenBuffers(2, &vbo[0]);
GL_GET_ERROR();
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
GL_GET_ERROR();
// Copy into VBO:
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexPosition2DColor) * vertices.size(), &vertices[0], GL_STATIC_DRAW);
GL_GET_ERROR();
glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind buffer
GL_GET_ERROR();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[1]);
GL_GET_ERROR();
// Copy into VBO:
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * indices.size(), &indices[0], GL_STATIC_DRAW);
GL_GET_ERROR();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // unbind buffer
GL_GET_ERROR();
}
void Canvas::GenerateVertices(std::vector<Vector2>& buffer,
const Color& a,
const Color& b,
const float& angle)
{
// TODO: Create simple logic for these special cases:
// angle == 0
// a == b
// angle == Pi
//
// TODO: Perhaps we can rotate the gradient instead of each vertex?
// Storage container for the rotated vertices:
std::vector<Vector2> rotated;
rotated.reserve(buffer.size());
Matrix33 m;
m.SetRotation(angle);
// Initial extreme values.
float max = std::numeric_limits<float>::min();
float min = std::numeric_limits<float>::max();
// Rotate, and find minima / maxima
for(size_t i = 0; i < buffer.size(); ++i)
{
// Rotate vector to the gradient's angle:
Vector2 p = buffer.at(i);
m.TransformVector2(p);
rotated.push_back(p);
// Find extremes:
max = std::max(max, p.y);
min = std::min(min, p.y);
}
// This works b.c. "minus minus" equals "plus".
const float height = fabs(max - min);
// Optimize common calculation:
const float oneOverHeight = 1.0f / height;
// Account for negative coordinates:
const float o = (min < 0) ? oneOverHeight * fabs(min) : 0;
// Translate the position:
// const float oneOverMin = oneOverHeight * min;
for(size_t i = 0; i < buffer.size(); ++i)
{
// We only interpolate over the Y axis, since the vertices
// have been rotated. I bet there are better ways.
float delta = oneOverHeight * rotated.at(i).y + o;// - oneOverMin;
// The actual vertex that the GPU's shader expects:
VertexPosition2DColor v = { buffer.at(i), Lerp(a, b, delta) };
if(delta < 0 || delta > 1)
{
LOG("Color lerp delta not in [0..1]");
LOG("delta: %f a: #%x, b: #%x, lerp: #%x", delta, a.integervalue, b.integervalue, v.color.integervalue);
LOG("Polygon min: %f, max: %f, height: %f oneover: %f, overmin: %f", min, max, height, oneOverHeight, oneOverHeight * min);
}
vertices.push_back(v);
}
}
void Canvas::Reload()
{
ERROR("Sorry Android, this isn't programmed yet.");
// TODO: re add all vertices, then call:
// Compile();
}
////////////////////////////////////////////////////////////////////////////////
/// Calls for some sort of some ad-hoc drawing API.
////////////////////////////////////////////////////////////////////////////////
/// Start a new polygon
Canvas& Canvas::Begin()
{
// Clear the work-in-progress buffer:
buffer.clear();
return *this;
}
/// Draw a directline
Canvas& Canvas::Vertex(const Vector2& p)
{
// Detect duplicate values, the triangulation code fails if there
// are any.
for(const Vector2& v : buffer)
{
if(v == p)
{
return *this;
}
}
buffer.push_back(p);
return *this;
}
/// Fill with a solid color:
Canvas& Canvas::Fill(const Color& color)
{
return Fill(color, color, 0);
}
/// Fill with a linear gradient:
Canvas& Canvas::Fill(const Color& a, const Color& b, const float& angle)
{
if(buffer.empty())
{
ERROR("There are no vertices to be rendered.");
}
// Offset, required for the indices.
const size_t offset = vertices.size();
// Triangulate and append the indices back into "all the indices":
for(const unsigned short i : Triangulate::Process(buffer))
{
indices.push_back(i + offset);
}
// Colorize:
GenerateVertices(buffer, a, b, angle);
return *this;
}
Canvas& Canvas::Stroke(const float& border, const Color& a, const float& angle)
{
return Stroke(border, a, a, angle);
}
Canvas& Canvas::Stroke(const float& border, const Color& colorBegin, const Color& colorEnd, const float& angle)
{ //return *this;
// To hold the shrunk polygon:
std::vector<Vector2> shrunk;
// Flip, that way the border is on the inside.
const float w = border * -1;
for(size_t i = 0; i < buffer.size(); ++i)
{
// Vertices:
const Vector2& a = (i == 0) ? buffer.at(buffer.size() - 1) : buffer.at(i - 1);
const Vector2& b = buffer[i];
const Vector2& c = (i == buffer.size() - 1) ? buffer.at(0) : buffer.at(i + 1);
// Direction of each edge:
const Vector2 ab = b - a;
const Vector2 bc = c - b;
Vector2 perp1 = ab.Perpendicular(); perp1.Normalize(); perp1 *= w;
Vector2 perp2 = bc.Perpendicular(); perp2.Normalize(); perp2 *= w;
// Runs from A to B.
const Vector2 beam1A = a + perp1;
const Vector2 beam1B = b + perp1;
// B to C
const Vector2 beam2A = b + perp2;
const Vector2 beam2B = c + perp2;
const Vector2 cross = LineIntersection(beam1A, beam1B, beam2A, beam2B);
shrunk.push_back(cross);
//LOG("a = segment(%f, %f, %f, %f)", beam1A.x, beam1A.y, beam1B.x, beam1B.y);
//LOG("b = segment(%f, %f, %f, %f)", beam2A.x, beam2A.y, beam2B.x, beam2B.y);
//LOG("Crossing: x:%f y:%f", cross.x, cross.y);
}
std::vector<Vector2> result;
// Generate triangles from the shrunk shape:
for(size_t i = 0; i < shrunk.size(); ++i)
{
// Vertices:
const Vector2& a = (i == 0) ? buffer.at(buffer.size() - 1) : buffer.at(i - 1);
const Vector2& b = buffer.at(i);
const Vector2& cross = shrunk[i];
const Vector2& nextCross = (i == shrunk.size() - 1) ? shrunk.at(0) : shrunk.at(i + 1);
// TODO: we're pushing _some_ vertices double. Later on we could
// optimize this.
result.push_back(a); // 0
result.push_back(b); // 1
result.push_back(cross); // 2
result.push_back(nextCross); // 3
// Desired index sequence:
// 0 1 2 2 3 1
const unsigned short offset = i * 4 + vertices.size();
indices.push_back(offset + 0);
indices.push_back(offset + 1);
indices.push_back(offset + 2);
indices.push_back(offset + 2);
indices.push_back(offset + 3);
indices.push_back(offset + 1);
}
GenerateVertices(result, colorBegin, colorEnd, angle); // TODO: angle.
return *this;
}
Canvas& Canvas::Bezier(const std::vector<Vector2>& points)
{
// TODO: fancy interval calculation.
const float interval = 1.0f / 30.0f;
for(float i = interval; i <= 1; i += interval) {
Vertex(
BezierCurve(points, i)
);
}
return *this;
}
| 27.817308 | 135 | 0.546031 | [
"shape",
"vector",
"solid"
] |
1018e68346e533e941b19a405130e1271597ce51 | 1,499 | cpp | C++ | 323. Number of Connected Components in an Undirected Graph.cpp | rajeev-ranjan-au6/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | 3 | 2020-12-30T00:29:59.000Z | 2021-01-24T22:43:04.000Z | 323. Number of Connected Components in an Undirected Graph.cpp | rajeevranjancom/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | null | null | null | 323. Number of Connected Components in an Undirected Graph.cpp | rajeevranjancom/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | null | null | null | // DFS
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<vector<int>>graph(n);
vector<int>visited(n);
for(auto x: edges){
graph[x.first].push_back(x.second);
graph[x.second].push_back(x.first);
}
int label = 0;
for(int i = 0; i < n; i++){
if(visited[i]) continue;
label++;
DFS(graph, i, visited);
}
return label;
}
void DFS(vector<vector<int>>& graph, int root, vector<int>& visited){
if(visited[root]) return;
visited[root] = 1;
for(auto neigh: graph[root])
if(!visited[neigh]) DFS(graph, neigh, visited);
}
};
// BFS
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<vector<int>>graph(n);
vector<int>visited(n);
for(auto x: edges){
graph[x.first].push_back(x.second);
graph[x.second].push_back(x.first);
}
int label = 0;
for(int i = 0; i < n; i++){
if(visited[i]) continue;
label++;
deque<int>q;
q.push_back(i);
while(!q.empty()){
int node = q.front();
q.pop_front();
visited[node] = 1;
for(auto neigh: graph[node])
if(!visited[neigh]) q.push_back(neigh);
}
}
return label;
}
};
| 27.254545 | 73 | 0.477652 | [
"vector"
] |
10196fee64ab8e4822a0bacc6ccfae05e12ac420 | 14,165 | hpp | C++ | vegastrike/boost/1_28/boost/math/common_factor.hpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/boost/1_28/boost/math/common_factor.hpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/boost/1_28/boost/math/common_factor.hpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | // Boost common_factor.hpp header file -------------------------------------//
// (C) Copyright Daryle Walker, Stephen Cleary, Paul Moore 2001. Permission
// to copy, use, modify, sell and distribute this software is granted provided
// this copyright notice appears in all copies. This software is provided "as
// is" without express or implied warranty, and with no claim as to its
// suitability for any purpose.
// See http://www.boost.org for updates, documentation, and revision history.
#ifndef BOOST_MATH_COMMON_FACTOR_HPP
#define BOOST_MATH_COMMON_FACTOR_HPP
#include <boost/math_fwd.hpp> // self include
#include <boost/config.hpp> // for BOOST_STATIC_CONSTANT, etc.
#include <boost/limits.hpp> // for std::numeric_limits
namespace boost
{
namespace math
{
// Forward declarations for function templates -----------------------------//
template < typename IntegerType >
IntegerType gcd( IntegerType const &a, IntegerType const &b );
template < typename IntegerType >
IntegerType lcm( IntegerType const &a, IntegerType const &b );
// Greatest common divisor evaluator class declaration ---------------------//
template < typename IntegerType >
class gcd_evaluator
{
public:
// Types
typedef IntegerType result_type, first_argument_type, second_argument_type;
// Function object interface
result_type operator ()( first_argument_type const &a,
second_argument_type const &b ) const;
}; // boost::math::gcd_evaluator
// Least common multiple evaluator class declaration -----------------------//
template < typename IntegerType >
class lcm_evaluator
{
public:
// Types
typedef IntegerType result_type, first_argument_type, second_argument_type;
// Function object interface
result_type operator ()( first_argument_type const &a,
second_argument_type const &b ) const;
}; // boost::math::lcm_evaluator
// Implementation details --------------------------------------------------//
namespace detail
{
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// Build GCD with Euclid's recursive algorithm
template < unsigned long Value1, unsigned long Value2 >
struct static_gcd_helper_t
{
private:
BOOST_STATIC_CONSTANT( unsigned long, new_value1 = Value2 );
BOOST_STATIC_CONSTANT( unsigned long, new_value2 = Value1 % Value2 );
#ifndef __BORLANDC__
#define BOOST_DETAIL_GCD_HELPER_VAL(Value) Value
#else
typedef static_gcd_helper_t self_type;
#define BOOST_DETAIL_GCD_HELPER_VAL(Value) (self_type:: Value )
#endif
typedef static_gcd_helper_t< BOOST_DETAIL_GCD_HELPER_VAL(new_value1),
BOOST_DETAIL_GCD_HELPER_VAL(new_value2) > next_step_type;
#undef BOOST_DETAIL_GCD_HELPER_VAL
public:
BOOST_STATIC_CONSTANT( unsigned long, value = next_step_type::value );
};
// Non-recursive case
template < unsigned long Value1 >
struct static_gcd_helper_t< Value1, 0UL >
{
BOOST_STATIC_CONSTANT( unsigned long, value = Value1 );
};
#else
// Use inner class template workaround from Peter Dimov
template < unsigned long Value1 >
struct static_gcd_helper2_t
{
template < unsigned long Value2 >
struct helper
{
BOOST_STATIC_CONSTANT( unsigned long, value
= static_gcd_helper2_t<Value2>::helper<Value1 % Value2>::value );
};
template < >
struct helper< 0UL >
{
BOOST_STATIC_CONSTANT( unsigned long, value = Value1 );
};
};
// Special case
template < >
struct static_gcd_helper2_t< 0UL >
{
template < unsigned long Value2 >
struct helper
{
BOOST_STATIC_CONSTANT( unsigned long, value = Value2 );
};
};
// Build the GCD from the above template(s)
template < unsigned long Value1, unsigned long Value2 >
struct static_gcd_helper_t
{
BOOST_STATIC_CONSTANT( unsigned long, value
= static_gcd_helper2_t<Value1>::BOOST_NESTED_TEMPLATE
helper<Value2>::value );
};
#endif
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// Build the LCM from the GCD
template < unsigned long Value1, unsigned long Value2 >
struct static_lcm_helper_t
{
typedef static_gcd_helper_t<Value1, Value2> gcd_type;
BOOST_STATIC_CONSTANT( unsigned long, value = Value1 / gcd_type::value
* Value2 );
};
// Special case for zero-GCD values
template < >
struct static_lcm_helper_t< 0UL, 0UL >
{
BOOST_STATIC_CONSTANT( unsigned long, value = 0UL );
};
#else
// Adapt GCD's inner class template workaround for LCM
template < unsigned long Value1 >
struct static_lcm_helper2_t
{
template < unsigned long Value2 >
struct helper
{
typedef static_gcd_helper_t<Value1, Value2> gcd_type;
BOOST_STATIC_CONSTANT( unsigned long, value = Value1
/ gcd_type::value * Value2 );
};
template < >
struct helper< 0UL >
{
BOOST_STATIC_CONSTANT( unsigned long, value = 0UL );
};
};
// Special case
template < >
struct static_lcm_helper2_t< 0UL >
{
template < unsigned long Value2 >
struct helper
{
BOOST_STATIC_CONSTANT( unsigned long, value = 0UL );
};
};
// Build the LCM from the above template(s)
template < unsigned long Value1, unsigned long Value2 >
struct static_lcm_helper_t
{
BOOST_STATIC_CONSTANT( unsigned long, value
= static_lcm_helper2_t<Value1>::BOOST_NESTED_TEMPLATE
helper<Value2>::value );
};
#endif
// Greatest common divisor for rings (including unsigned integers)
template < typename RingType >
RingType
gcd_euclidean
(
RingType a,
RingType b
)
{
// Avoid repeated construction
#ifndef __BORLANDC__
RingType const zero = static_cast<RingType>( 0 );
#else
RingType zero = static_cast<RingType>( 0 );
#endif
// Reduce by GCD-remainder property [GCD(a,b) == GCD(b,a MOD b)]
while ( true )
{
if ( a == zero )
return b;
b %= a;
if ( b == zero )
return a;
a %= b;
}
}
// Greatest common divisor for (signed) integers
template < typename IntegerType >
inline
IntegerType
gcd_integer
(
IntegerType const & a,
IntegerType const & b
)
{
// Avoid repeated construction
IntegerType const zero = static_cast<IntegerType>( 0 );
IntegerType const result = gcd_euclidean( a, b );
return ( result < zero ) ? -result : result;
}
// Least common multiple for rings (including unsigned integers)
template < typename RingType >
inline
RingType
lcm_euclidean
(
RingType const & a,
RingType const & b
)
{
RingType const zero = static_cast<RingType>( 0 );
RingType const temp = gcd_euclidean( a, b );
return ( temp != zero ) ? ( a / temp * b ) : zero;
}
// Least common multiple for (signed) integers
template < typename IntegerType >
inline
IntegerType
lcm_integer
(
IntegerType const & a,
IntegerType const & b
)
{
// Avoid repeated construction
IntegerType const zero = static_cast<IntegerType>( 0 );
IntegerType const result = lcm_euclidean( a, b );
return ( result < zero ) ? -result : result;
}
// Function objects to find the best way of computing GCD or LCM
#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
template < typename T, bool IsSpecialized, bool IsSigned >
struct gcd_optimal_evaluator_helper_t
{
T operator ()( T const &a, T const &b )
{
return gcd_euclidean( a, b );
}
};
template < typename T >
struct gcd_optimal_evaluator_helper_t< T, true, true >
{
T operator ()( T const &a, T const &b )
{
return gcd_integer( a, b );
}
};
#else
template < bool IsSpecialized, bool IsSigned >
struct gcd_optimal_evaluator_helper2_t
{
template < typename T >
struct helper
{
T operator ()( T const &a, T const &b )
{
return gcd_euclidean( a, b );
}
};
};
template < >
struct gcd_optimal_evaluator_helper2_t< true, true >
{
template < typename T >
struct helper
{
T operator ()( T const &a, T const &b )
{
return gcd_integer( a, b );
}
};
};
template < typename T, bool IsSpecialized, bool IsSigned >
struct gcd_optimal_evaluator_helper_t
: gcd_optimal_evaluator_helper2_t<IsSpecialized, IsSigned>
::BOOST_NESTED_TEMPLATE helper<T>
{
};
#endif
template < typename T >
struct gcd_optimal_evaluator
{
T operator ()( T const &a, T const &b )
{
typedef ::std::numeric_limits<T> limits_type;
typedef gcd_optimal_evaluator_helper_t<T,
limits_type::is_specialized, limits_type::is_signed> helper_type;
helper_type solver;
return solver( a, b );
}
};
#else // BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
template < typename T >
struct gcd_optimal_evaluator
{
T operator ()( T const &a, T const &b )
{
return gcd_integer( a, b );
}
};
#endif
#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
template < typename T, bool IsSpecialized, bool IsSigned >
struct lcm_optimal_evaluator_helper_t
{
T operator ()( T const &a, T const &b )
{
return lcm_euclidean( a, b );
}
};
template < typename T >
struct lcm_optimal_evaluator_helper_t< T, true, true >
{
T operator ()( T const &a, T const &b )
{
return lcm_integer( a, b );
}
};
#else
template < bool IsSpecialized, bool IsSigned >
struct lcm_optimal_evaluator_helper2_t
{
template < typename T >
struct helper
{
T operator ()( T const &a, T const &b )
{
return lcm_euclidean( a, b );
}
};
};
template < >
struct lcm_optimal_evaluator_helper2_t< true, true >
{
template < typename T >
struct helper
{
T operator ()( T const &a, T const &b )
{
return lcm_integer( a, b );
}
};
};
template < typename T, bool IsSpecialized, bool IsSigned >
struct lcm_optimal_evaluator_helper_t
: lcm_optimal_evaluator_helper2_t<IsSpecialized, IsSigned>
::BOOST_NESTED_TEMPLATE helper<T>
{
};
#endif
template < typename T >
struct lcm_optimal_evaluator
{
T operator ()( T const &a, T const &b )
{
typedef ::std::numeric_limits<T> limits_type;
typedef lcm_optimal_evaluator_helper_t<T,
limits_type::is_specialized, limits_type::is_signed> helper_type;
helper_type solver;
return solver( a, b );
}
};
#else // BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
template < typename T >
struct lcm_optimal_evaluator
{
T operator ()( T const &a, T const &b )
{
return lcm_integer( a, b );
}
};
#endif
// Functions to find the GCD or LCM in the best way
template < typename T >
inline
T
gcd_optimal
(
T const & a,
T const & b
)
{
gcd_optimal_evaluator<T> solver;
return solver( a, b );
}
template < typename T >
inline
T
lcm_optimal
(
T const & a,
T const & b
)
{
lcm_optimal_evaluator<T> solver;
return solver( a, b );
}
} // namespace detail
// Compile-time greatest common divisor evaluator class declaration --------//
template < unsigned long Value1, unsigned long Value2 >
struct static_gcd
{
BOOST_STATIC_CONSTANT( unsigned long, value
= (detail::static_gcd_helper_t<Value1, Value2>::value) );
}; // boost::math::static_gcd
// Compile-time least common multiple evaluator class declaration ----------//
template < unsigned long Value1, unsigned long Value2 >
struct static_lcm
{
BOOST_STATIC_CONSTANT( unsigned long, value
= (detail::static_lcm_helper_t<Value1, Value2>::value) );
}; // boost::math::static_lcm
// Greatest common divisor evaluator member function definition ------------//
template < typename IntegerType >
inline
typename gcd_evaluator<IntegerType>::result_type
gcd_evaluator<IntegerType>::operator ()
(
first_argument_type const & a,
second_argument_type const & b
) const
{
return detail::gcd_optimal( a, b );
}
// Least common multiple evaluator member function definition --------------//
template < typename IntegerType >
inline
typename lcm_evaluator<IntegerType>::result_type
lcm_evaluator<IntegerType>::operator ()
(
first_argument_type const & a,
second_argument_type const & b
) const
{
return detail::lcm_optimal( a, b );
}
// Greatest common divisor and least common multiple function definitions --//
template < typename IntegerType >
inline
IntegerType
gcd
(
IntegerType const & a,
IntegerType const & b
)
{
gcd_evaluator<IntegerType> solver;
return solver( a, b );
}
template < typename IntegerType >
inline
IntegerType
lcm
(
IntegerType const & a,
IntegerType const & b
)
{
lcm_evaluator<IntegerType> solver;
return solver( a, b );
}
} // namespace math
} // namespace boost
#endif // BOOST_MATH_COMMON_FACTOR_HPP
| 25.249554 | 80 | 0.608966 | [
"object"
] |
101aa23f552f54302860cecbc1c6c80bc1e0e681 | 58,343 | cpp | C++ | src/mongo/dbtests/querytests.cpp | bjori/mongo | c0e293d88a9946e9b3395b2445589c6db8c067f7 | [
"Apache-2.0"
] | 1 | 2019-05-15T03:41:50.000Z | 2019-05-15T03:41:50.000Z | src/mongo/dbtests/querytests.cpp | bjori/mongo | c0e293d88a9946e9b3395b2445589c6db8c067f7 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/querytests.cpp | bjori/mongo | c0e293d88a9946e9b3395b2445589c6db8c067f7 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include <boost/optional.hpp>
#include <iostream>
#include "mongo/client/dbclientcursor.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/client.h"
#include "mongo/db/clientcursor.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/exec/queued_data_stage.h"
#include "mongo/db/json.h"
#include "mongo/db/lasterror.h"
#include "mongo/db/logical_clock.h"
#include "mongo/db/logical_time.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/query/find.h"
#include "mongo/db/service_context.h"
#include "mongo/db/service_context_d.h"
#include "mongo/dbtests/dbtests.h"
#include "mongo/util/timer.h"
namespace {
namespace QueryTests {
using std::unique_ptr;
using std::endl;
using std::string;
using std::vector;
class Base {
public:
Base() : _lk(&_opCtx), _context(&_opCtx, ns()) {
{
WriteUnitOfWork wunit(&_opCtx);
_database = _context.db();
_collection = _database->getCollection(&_opCtx, ns());
if (_collection) {
_database->dropCollection(&_opCtx, ns());
}
_collection = _database->createCollection(&_opCtx, ns());
wunit.commit();
}
addIndex(IndexSpec().addKey("a").unique(false));
}
~Base() {
try {
WriteUnitOfWork wunit(&_opCtx);
uassertStatusOK(_database->dropCollection(&_opCtx, ns()));
wunit.commit();
} catch (...) {
FAIL("Exception while cleaning up collection");
}
}
protected:
static const char* ns() {
return "unittests.querytests";
}
void addIndex(const IndexSpec& spec) {
DBDirectClient client(&_opCtx);
client.createIndex(ns(), spec);
client.getLastError();
}
void insert(const char* s) {
insert(fromjson(s));
}
void insert(const BSONObj& o) {
WriteUnitOfWork wunit(&_opCtx);
OpDebug* const nullOpDebug = nullptr;
if (o["_id"].eoo()) {
BSONObjBuilder b;
OID oid;
oid.init();
b.appendOID("_id", &oid);
b.appendElements(o);
_collection->insertDocument(&_opCtx, b.obj(), nullOpDebug, false);
} else {
_collection->insertDocument(&_opCtx, o, nullOpDebug, false);
}
wunit.commit();
}
const ServiceContext::UniqueOperationContext _opCtxPtr = cc().makeOperationContext();
OperationContext& _opCtx = *_opCtxPtr;
Lock::GlobalWrite _lk;
OldClientContext _context;
Database* _database;
Collection* _collection;
};
class FindOneOr : public Base {
public:
void run() {
addIndex(IndexSpec().addKey("b").unique(false));
addIndex(IndexSpec().addKey("c").unique(false));
insert(BSON("b" << 2 << "_id" << 0));
insert(BSON("c" << 3 << "_id" << 1));
BSONObj query = fromjson("{$or:[{b:2},{c:3}]}");
BSONObj ret;
// Check findOne() returning object.
ASSERT(Helpers::findOne(&_opCtx, _collection, query, ret, true));
ASSERT_EQUALS(string("b"), ret.firstElement().fieldName());
// Cross check with findOne() returning location.
ASSERT_BSONOBJ_EQ(
ret,
_collection->docFor(&_opCtx, Helpers::findOne(&_opCtx, _collection, query, true))
.value());
}
};
class FindOneRequireIndex : public Base {
public:
void run() {
insert(BSON("b" << 2 << "_id" << 0));
BSONObj query = fromjson("{b:2}");
BSONObj ret;
// Check findOne() returning object, allowing unindexed scan.
ASSERT(Helpers::findOne(&_opCtx, _collection, query, ret, false));
// Check findOne() returning location, allowing unindexed scan.
ASSERT_BSONOBJ_EQ(
ret,
_collection->docFor(&_opCtx, Helpers::findOne(&_opCtx, _collection, query, false))
.value());
// Check findOne() returning object, requiring indexed scan without index.
ASSERT_THROWS(Helpers::findOne(&_opCtx, _collection, query, ret, true),
MsgAssertionException);
// Check findOne() returning location, requiring indexed scan without index.
ASSERT_THROWS(Helpers::findOne(&_opCtx, _collection, query, true), MsgAssertionException);
addIndex(IndexSpec().addKey("b").unique(false));
// Check findOne() returning object, requiring indexed scan with index.
ASSERT(Helpers::findOne(&_opCtx, _collection, query, ret, true));
// Check findOne() returning location, requiring indexed scan with index.
ASSERT_BSONOBJ_EQ(
ret,
_collection->docFor(&_opCtx, Helpers::findOne(&_opCtx, _collection, query, true))
.value());
}
};
class FindOneEmptyObj : public Base {
public:
void run() {
// We don't normally allow empty objects in the database, but test that we can find
// an empty object (one might be allowed inside a reserved namespace at some point).
Lock::GlobalWrite lk(&_opCtx);
OldClientContext ctx(&_opCtx, "unittests.querytests");
{
WriteUnitOfWork wunit(&_opCtx);
Database* db = ctx.db();
if (db->getCollection(&_opCtx, ns())) {
_collection = NULL;
db->dropCollection(&_opCtx, ns());
}
_collection = db->createCollection(&_opCtx, ns(), CollectionOptions(), false);
wunit.commit();
}
ASSERT(_collection);
DBDirectClient cl(&_opCtx);
BSONObj info;
bool ok = cl.runCommand("unittests",
BSON("godinsert"
<< "querytests"
<< "obj"
<< BSONObj()),
info);
ASSERT(ok);
insert(BSONObj());
BSONObj query;
BSONObj ret;
ASSERT(Helpers::findOne(&_opCtx, _collection, query, ret, false));
ASSERT(ret.isEmpty());
ASSERT_BSONOBJ_EQ(
ret,
_collection->docFor(&_opCtx, Helpers::findOne(&_opCtx, _collection, query, false))
.value());
}
};
class ClientBase {
public:
ClientBase() : _client(&_opCtx) {
mongo::LastError::get(_opCtx.getClient()).reset();
}
virtual ~ClientBase() {
mongo::LastError::get(_opCtx.getClient()).reset();
}
protected:
void insert(const char* ns, BSONObj o) {
_client.insert(ns, o);
}
void update(const char* ns, BSONObj q, BSONObj o, bool upsert = 0) {
_client.update(ns, Query(q), o, upsert);
}
bool error() {
return !_client.getPrevError().getField("err").isNull();
}
const ServiceContext::UniqueOperationContext _opCtxPtr = cc().makeOperationContext();
OperationContext& _opCtx = *_opCtxPtr;
DBDirectClient _client;
};
class BoundedKey : public ClientBase {
public:
~BoundedKey() {
_client.dropCollection("unittests.querytests.BoundedKey");
}
void run() {
const char* ns = "unittests.querytests.BoundedKey";
insert(ns, BSON("a" << 1));
BSONObjBuilder a;
a.appendMaxKey("$lt");
BSONObj limit = a.done();
ASSERT(!_client.findOne(ns, QUERY("a" << limit)).isEmpty());
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
ASSERT(!_client.findOne(ns, QUERY("a" << limit).hint(BSON("a" << 1))).isEmpty());
}
};
class GetMore : public ClientBase {
public:
~GetMore() {
_client.dropCollection("unittests.querytests.GetMore");
}
void run() {
const char* ns = "unittests.querytests.GetMore";
insert(ns, BSON("a" << 1));
insert(ns, BSON("a" << 2));
insert(ns, BSON("a" << 3));
unique_ptr<DBClientCursor> cursor = _client.query(ns, BSONObj(), 2);
long long cursorId = cursor->getCursorId();
cursor->decouple();
cursor.reset();
{
// Check internal server handoff to getmore.
OldClientWriteContext ctx(&_opCtx, ns);
auto pinnedCursor = unittest::assertGet(
ctx.getCollection()->getCursorManager()->pinCursor(&_opCtx, cursorId));
ASSERT_EQUALS(2, pinnedCursor.getCursor()->pos());
}
cursor = _client.getMore(ns, cursorId);
ASSERT(cursor->more());
ASSERT_EQUALS(3, cursor->next().getIntField("a"));
}
};
/**
* An exception triggered during a get more request destroys the ClientCursor used by the get
* more, preventing further iteration of the cursor in subsequent get mores.
*/
class GetMoreKillOp : public ClientBase {
public:
~GetMoreKillOp() {
getGlobalServiceContext()->unsetKillAllOperations();
_client.dropCollection("unittests.querytests.GetMoreKillOp");
}
void run() {
// Create a collection with some data.
const char* ns = "unittests.querytests.GetMoreKillOp";
for (int i = 0; i < 1000; ++i) {
insert(ns, BSON("a" << i));
}
// Create a cursor on the collection, with a batch size of 200.
unique_ptr<DBClientCursor> cursor = _client.query(ns, "", 0, 0, 0, 0, 200);
CursorId cursorId = cursor->getCursorId();
// Count 500 results, spanning a few batches of documents.
for (int i = 0; i < 500; ++i) {
ASSERT(cursor->more());
cursor->next();
}
// Set the killop kill all flag, forcing the next get more to fail with a kill op
// exception.
getGlobalServiceContext()->setKillAllOperations();
while (cursor->more()) {
cursor->next();
}
// Revert the killop kill all flag.
getGlobalServiceContext()->unsetKillAllOperations();
// Check that the cursor has been removed.
{
AutoGetCollectionForReadCommand ctx(&_opCtx, NamespaceString(ns));
ASSERT(0 == ctx.getCollection()->getCursorManager()->numCursors());
}
ASSERT_FALSE(CursorManager::eraseCursorGlobal(&_opCtx, cursorId));
// Check that a subsequent get more fails with the cursor removed.
ASSERT_THROWS(_client.getMore(ns, cursorId), UserException);
}
};
/**
* A get more exception caused by an invalid or unauthorized get more request does not cause
* the get more's ClientCursor to be destroyed. This prevents an unauthorized user from
* improperly killing a cursor by issuing an invalid get more request.
*/
class GetMoreInvalidRequest : public ClientBase {
public:
~GetMoreInvalidRequest() {
getGlobalServiceContext()->unsetKillAllOperations();
_client.dropCollection("unittests.querytests.GetMoreInvalidRequest");
}
void run() {
// Create a collection with some data.
const char* ns = "unittests.querytests.GetMoreInvalidRequest";
for (int i = 0; i < 1000; ++i) {
insert(ns, BSON("a" << i));
}
// Create a cursor on the collection, with a batch size of 200.
unique_ptr<DBClientCursor> cursor = _client.query(ns, "", 0, 0, 0, 0, 200);
CursorId cursorId = cursor->getCursorId();
// Count 500 results, spanning a few batches of documents.
int count = 0;
for (int i = 0; i < 500; ++i) {
ASSERT(cursor->more());
cursor->next();
++count;
}
// Send a get more with a namespace that is incorrect ('spoofed') for this cursor id.
// This is the invalaid get more request described in the comment preceding this class.
_client.getMore("unittests.querytests.GetMoreInvalidRequest_WRONG_NAMESPACE_FOR_CURSOR",
cursor->getCursorId());
// Check that the cursor still exists
{
AutoGetCollectionForReadCommand ctx(&_opCtx, NamespaceString(ns));
ASSERT(1 == ctx.getCollection()->getCursorManager()->numCursors());
ASSERT_OK(
ctx.getCollection()->getCursorManager()->pinCursor(&_opCtx, cursorId).getStatus());
}
// Check that the cursor can be iterated until all documents are returned.
while (cursor->more()) {
cursor->next();
++count;
}
ASSERT_EQUALS(1000, count);
}
};
class PositiveLimit : public ClientBase {
public:
const char* ns;
PositiveLimit() : ns("unittests.querytests.PositiveLimit") {}
~PositiveLimit() {
_client.dropCollection(ns);
}
void testLimit(int limit) {
ASSERT_EQUALS(_client.query(ns, BSONObj(), limit)->itcount(), limit);
}
void run() {
for (int i = 0; i < 1000; i++)
insert(ns, BSON(GENOID << "i" << i));
ASSERT_EQUALS(_client.query(ns, BSONObj(), 1)->itcount(), 1);
ASSERT_EQUALS(_client.query(ns, BSONObj(), 10)->itcount(), 10);
ASSERT_EQUALS(_client.query(ns, BSONObj(), 101)->itcount(), 101);
ASSERT_EQUALS(_client.query(ns, BSONObj(), 999)->itcount(), 999);
ASSERT_EQUALS(_client.query(ns, BSONObj(), 1000)->itcount(), 1000);
ASSERT_EQUALS(_client.query(ns, BSONObj(), 1001)->itcount(), 1000);
ASSERT_EQUALS(_client.query(ns, BSONObj(), 0)->itcount(), 1000);
}
};
class TailNotAtEnd : public ClientBase {
public:
~TailNotAtEnd() {
_client.dropCollection("unittests.querytests.TailNotAtEnd");
}
void run() {
const char* ns = "unittests.querytests.TailNotAtEnd";
_client.createCollection(ns, 2047, true);
insert(ns, BSON("a" << 0));
insert(ns, BSON("a" << 1));
insert(ns, BSON("a" << 2));
unique_ptr<DBClientCursor> c = _client.query(
ns, Query().hint(BSON("$natural" << 1)), 2, 0, 0, QueryOption_CursorTailable);
ASSERT(0 != c->getCursorId());
while (c->more())
c->next();
ASSERT(0 != c->getCursorId());
insert(ns, BSON("a" << 3));
insert(ns, BSON("a" << 4));
insert(ns, BSON("a" << 5));
insert(ns, BSON("a" << 6));
ASSERT(c->more());
ASSERT_EQUALS(3, c->next().getIntField("a"));
}
};
class EmptyTail : public ClientBase {
public:
~EmptyTail() {
_client.dropCollection("unittests.querytests.EmptyTail");
}
void run() {
const char* ns = "unittests.querytests.EmptyTail";
_client.createCollection(ns, 1900, true);
unique_ptr<DBClientCursor> c = _client.query(
ns, Query().hint(BSON("$natural" << 1)), 2, 0, 0, QueryOption_CursorTailable);
ASSERT_EQUALS(0, c->getCursorId());
ASSERT(c->isDead());
insert(ns, BSON("a" << 0));
c = _client.query(
ns, QUERY("a" << 1).hint(BSON("$natural" << 1)), 2, 0, 0, QueryOption_CursorTailable);
ASSERT(0 != c->getCursorId());
ASSERT(!c->isDead());
}
};
class TailableDelete : public ClientBase {
public:
~TailableDelete() {
_client.dropCollection("unittests.querytests.TailableDelete");
}
void run() {
const char* ns = "unittests.querytests.TailableDelete";
_client.createCollection(ns, 8192, true, 2);
insert(ns, BSON("a" << 0));
insert(ns, BSON("a" << 1));
unique_ptr<DBClientCursor> c = _client.query(
ns, Query().hint(BSON("$natural" << 1)), 2, 0, 0, QueryOption_CursorTailable);
c->next();
c->next();
ASSERT(!c->more());
insert(ns, BSON("a" << 2));
insert(ns, BSON("a" << 3));
// We have overwritten the previous cursor position and should encounter a dead cursor.
if (c->more()) {
ASSERT_THROWS(c->nextSafe(), AssertionException);
}
}
};
class TailableDelete2 : public ClientBase {
public:
~TailableDelete2() {
_client.dropCollection("unittests.querytests.TailableDelete");
}
void run() {
const char* ns = "unittests.querytests.TailableDelete";
_client.createCollection(ns, 8192, true, 2);
insert(ns, BSON("a" << 0));
insert(ns, BSON("a" << 1));
unique_ptr<DBClientCursor> c = _client.query(
ns, Query().hint(BSON("$natural" << 1)), 2, 0, 0, QueryOption_CursorTailable);
c->next();
c->next();
ASSERT(!c->more());
insert(ns, BSON("a" << 2));
insert(ns, BSON("a" << 3));
insert(ns, BSON("a" << 4));
// We have overwritten the previous cursor position and should encounter a dead cursor.
if (c->more()) {
ASSERT_THROWS(c->nextSafe(), AssertionException);
}
}
};
class TailableInsertDelete : public ClientBase {
public:
~TailableInsertDelete() {
_client.dropCollection("unittests.querytests.TailableInsertDelete");
}
void run() {
const char* ns = "unittests.querytests.TailableInsertDelete";
_client.createCollection(ns, 1330, true);
insert(ns, BSON("a" << 0));
insert(ns, BSON("a" << 1));
unique_ptr<DBClientCursor> c = _client.query(
ns, Query().hint(BSON("$natural" << 1)), 2, 0, 0, QueryOption_CursorTailable);
c->next();
c->next();
ASSERT(!c->more());
insert(ns, BSON("a" << 2));
_client.remove(ns, QUERY("a" << 1));
ASSERT(c->more());
ASSERT_EQUALS(2, c->next().getIntField("a"));
ASSERT(!c->more());
}
};
class TailCappedOnly : public ClientBase {
public:
~TailCappedOnly() {
_client.dropCollection("unittest.querytests.TailCappedOnly");
}
void run() {
const char* ns = "unittests.querytests.TailCappedOnly";
_client.insert(ns, BSONObj());
unique_ptr<DBClientCursor> c =
_client.query(ns, BSONObj(), 0, 0, 0, QueryOption_CursorTailable);
ASSERT(c->isDead());
}
};
class TailableQueryOnId : public ClientBase {
public:
~TailableQueryOnId() {
_client.dropCollection("unittests.querytests.TailableQueryOnId");
}
void insertA(const char* ns, int a) {
BSONObjBuilder b;
b.appendOID("_id", 0, true);
b.appendOID("value", 0, true);
b.append("a", a);
insert(ns, b.obj());
}
void run() {
const char* ns = "unittests.querytests.TailableQueryOnId";
BSONObj info;
_client.runCommand("unittests",
BSON("create"
<< "querytests.TailableQueryOnId"
<< "capped"
<< true
<< "size"
<< 8192
<< "autoIndexId"
<< true),
info);
insertA(ns, 0);
insertA(ns, 1);
unique_ptr<DBClientCursor> c1 =
_client.query(ns, QUERY("a" << GT << -1), 0, 0, 0, QueryOption_CursorTailable);
OID id;
id.init("000000000000000000000000");
unique_ptr<DBClientCursor> c2 =
_client.query(ns, QUERY("value" << GT << id), 0, 0, 0, QueryOption_CursorTailable);
c1->next();
c1->next();
ASSERT(!c1->more());
c2->next();
c2->next();
ASSERT(!c2->more());
insertA(ns, 2);
ASSERT(c1->more());
ASSERT_EQUALS(2, c1->next().getIntField("a"));
ASSERT(!c1->more());
ASSERT(c2->more());
ASSERT_EQUALS(2, c2->next().getIntField("a")); // SERVER-645
ASSERT(!c2->more());
ASSERT(!c2->isDead());
}
};
class OplogReplayMode : public ClientBase {
public:
~OplogReplayMode() {
_client.dropCollection("unittests.querytests.OplogReplayMode");
}
void run() {
const char* ns = "unittests.querytests.OplogReplayMode";
// Create a capped collection of size 10.
_client.dropCollection(ns);
_client.createCollection(ns, 10, true);
insert(ns, BSON("ts" << 0));
insert(ns, BSON("ts" << 1));
insert(ns, BSON("ts" << 2));
unique_ptr<DBClientCursor> c =
_client.query(ns,
QUERY("ts" << GT << 1).hint(BSON("$natural" << 1)),
0,
0,
0,
QueryOption_OplogReplay);
ASSERT(c->more());
ASSERT_EQUALS(2, c->next().getIntField("ts"));
ASSERT(!c->more());
insert(ns, BSON("ts" << 3));
c = _client.query(ns,
QUERY("ts" << GT << 1).hint(BSON("$natural" << 1)),
0,
0,
0,
QueryOption_OplogReplay);
ASSERT(c->more());
ASSERT_EQUALS(2, c->next().getIntField("ts"));
ASSERT(c->more());
}
};
class OplogReplaySlaveReadTill : public ClientBase {
public:
~OplogReplaySlaveReadTill() {
_client.dropCollection("unittests.querytests.OplogReplaySlaveReadTill");
}
void run() {
const char* ns = "unittests.querytests.OplogReplaySlaveReadTill";
// Create a capped collection of size 10.
_client.dropCollection(ns);
_client.createCollection(ns, 10, true);
Lock::DBLock lk(&_opCtx, "unittests", MODE_X);
OldClientContext ctx(&_opCtx, ns);
BSONObj info;
_client.runCommand("unittests",
BSON("create"
<< "querytests.OplogReplaySlaveReadTill"
<< "capped"
<< true
<< "size"
<< 8192),
info);
Date_t one = Date_t::fromMillisSinceEpoch(
LogicalClock::get(&_opCtx)->reserveTicks(1).asTimestamp().asLL());
Date_t two = Date_t::fromMillisSinceEpoch(
LogicalClock::get(&_opCtx)->reserveTicks(1).asTimestamp().asLL());
Date_t three = Date_t::fromMillisSinceEpoch(
LogicalClock::get(&_opCtx)->reserveTicks(1).asTimestamp().asLL());
insert(ns, BSON("ts" << one));
insert(ns, BSON("ts" << two));
insert(ns, BSON("ts" << three));
unique_ptr<DBClientCursor> c =
_client.query(ns,
QUERY("ts" << GTE << two).hint(BSON("$natural" << 1)),
0,
0,
0,
QueryOption_OplogReplay | QueryOption_CursorTailable);
ASSERT(c->more());
ASSERT_EQUALS(two, c->next()["ts"].Date());
long long cursorId = c->getCursorId();
auto pinnedCursor = unittest::assertGet(
ctx.db()->getCollection(&_opCtx, ns)->getCursorManager()->pinCursor(&_opCtx, cursorId));
ASSERT_EQUALS(three.toULL(), pinnedCursor.getCursor()->getSlaveReadTill().asULL());
}
};
class OplogReplayExplain : public ClientBase {
public:
~OplogReplayExplain() {
_client.dropCollection("unittests.querytests.OplogReplayExplain");
}
void run() {
const char* ns = "unittests.querytests.OplogReplayExplain";
// Create a capped collection of size 10.
_client.dropCollection(ns);
_client.createCollection(ns, 10, true);
insert(ns, BSON("ts" << 0));
insert(ns, BSON("ts" << 1));
insert(ns, BSON("ts" << 2));
unique_ptr<DBClientCursor> c =
_client.query(ns,
QUERY("ts" << GT << 1).hint(BSON("$natural" << 1)).explain(),
0,
0,
0,
QueryOption_OplogReplay);
ASSERT(c->more());
// Check number of results and filterSet flag in explain.
// filterSet is not available in oplog replay mode.
BSONObj explainObj = c->next();
ASSERT(explainObj.hasField("executionStats"));
BSONObj execStats = explainObj["executionStats"].Obj();
ASSERT_EQUALS(1, execStats.getIntField("nReturned"));
ASSERT(!c->more());
}
};
class BasicCount : public ClientBase {
public:
~BasicCount() {
_client.dropCollection("unittests.querytests.BasicCount");
}
void run() {
const char* ns = "unittests.querytests.BasicCount";
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
count(0);
insert(ns, BSON("a" << 3));
count(0);
insert(ns, BSON("a" << 4));
count(1);
insert(ns, BSON("a" << 5));
count(1);
insert(ns, BSON("a" << 4));
count(2);
}
private:
void count(unsigned long long c) {
ASSERT_EQUALS(c, _client.count("unittests.querytests.BasicCount", BSON("a" << 4)));
}
};
class ArrayId : public ClientBase {
public:
~ArrayId() {
_client.dropCollection("unittests.querytests.ArrayId");
}
void run() {
const char* ns = "unittests.querytests.ArrayId";
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("_id" << 1)));
ASSERT(!error());
_client.insert(ns, fromjson("{'_id':[1,2]}"));
ASSERT(error());
}
};
class UnderscoreNs : public ClientBase {
public:
~UnderscoreNs() {
_client.dropCollection("unittests.querytests._UnderscoreNs");
}
void run() {
ASSERT(!error());
const char* ns = "unittests.querytests._UnderscoreNs";
ASSERT(_client.findOne(ns, "{}").isEmpty());
_client.insert(ns, BSON("a" << 1));
ASSERT_EQUALS(1, _client.findOne(ns, "{}").getIntField("a"));
ASSERT(!error());
}
};
class EmptyFieldSpec : public ClientBase {
public:
~EmptyFieldSpec() {
_client.dropCollection("unittests.querytests.EmptyFieldSpec");
}
void run() {
const char* ns = "unittests.querytests.EmptyFieldSpec";
_client.insert(ns, BSON("a" << 1));
ASSERT(!_client.findOne(ns, "").isEmpty());
BSONObj empty;
ASSERT(!_client.findOne(ns, "", &empty).isEmpty());
}
};
class MultiNe : public ClientBase {
public:
~MultiNe() {
_client.dropCollection("unittests.querytests.Ne");
}
void run() {
const char* ns = "unittests.querytests.Ne";
_client.insert(ns, fromjson("{a:[1,2]}"));
ASSERT(_client.findOne(ns, fromjson("{a:{$ne:1}}")).isEmpty());
BSONObj spec = fromjson("{a:{$ne:1,$ne:2}}");
ASSERT(_client.findOne(ns, spec).isEmpty());
}
};
class EmbeddedNe : public ClientBase {
public:
~EmbeddedNe() {
_client.dropCollection("unittests.querytests.NestedNe");
}
void run() {
const char* ns = "unittests.querytests.NestedNe";
_client.insert(ns, fromjson("{a:[{b:1},{b:2}]}"));
ASSERT(_client.findOne(ns, fromjson("{'a.b':{$ne:1}}")).isEmpty());
}
};
class EmbeddedNumericTypes : public ClientBase {
public:
~EmbeddedNumericTypes() {
_client.dropCollection("unittests.querytests.NumericEmbedded");
}
void run() {
const char* ns = "unittests.querytests.NumericEmbedded";
_client.insert(ns, BSON("a" << BSON("b" << 1)));
ASSERT(!_client.findOne(ns, BSON("a" << BSON("b" << 1.0))).isEmpty());
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
ASSERT(!_client.findOne(ns, BSON("a" << BSON("b" << 1.0))).isEmpty());
}
};
class AutoResetIndexCache : public ClientBase {
public:
~AutoResetIndexCache() {
_client.dropCollection("unittests.querytests.AutoResetIndexCache");
}
static const char* ns() {
return "unittests.querytests.AutoResetIndexCache";
}
void index() {
ASSERT_EQUALS(2u, _client.getIndexSpecs(ns()).size());
}
void noIndex() {
ASSERT_EQUALS(0u, _client.getIndexSpecs(ns()).size());
}
void checkIndex() {
ASSERT_OK(dbtests::createIndex(&_opCtx, ns(), BSON("a" << 1)));
index();
}
void run() {
_client.dropDatabase("unittests");
noIndex();
checkIndex();
_client.dropCollection(ns());
noIndex();
checkIndex();
_client.dropDatabase("unittests");
noIndex();
checkIndex();
}
};
class UniqueIndex : public ClientBase {
public:
~UniqueIndex() {
_client.dropCollection("unittests.querytests.UniqueIndex");
}
void run() {
const char* ns = "unittests.querytests.UniqueIndex";
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1), true));
_client.insert(ns, BSON("a" << 4 << "b" << 2));
_client.insert(ns, BSON("a" << 4 << "b" << 3));
ASSERT_EQUALS(1U, _client.count(ns, BSONObj()));
_client.dropCollection(ns);
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("b" << 1), true));
_client.insert(ns, BSON("a" << 4 << "b" << 2));
_client.insert(ns, BSON("a" << 4 << "b" << 3));
ASSERT_EQUALS(2U, _client.count(ns, BSONObj()));
}
};
class UniqueIndexPreexistingData : public ClientBase {
public:
~UniqueIndexPreexistingData() {
_client.dropCollection("unittests.querytests.UniqueIndexPreexistingData");
}
void run() {
const char* ns = "unittests.querytests.UniqueIndexPreexistingData";
_client.insert(ns, BSON("a" << 4 << "b" << 2));
_client.insert(ns, BSON("a" << 4 << "b" << 3));
ASSERT_EQUALS(ErrorCodes::DuplicateKey,
dbtests::createIndex(&_opCtx, ns, BSON("a" << 1), true));
ASSERT_EQUALS(
0U,
_client.count("unittests.system.indexes", BSON("ns" << ns << "name" << NE << "_id_")));
}
};
class SubobjectInArray : public ClientBase {
public:
~SubobjectInArray() {
_client.dropCollection("unittests.querytests.SubobjectInArray");
}
void run() {
const char* ns = "unittests.querytests.SubobjectInArray";
_client.insert(ns, fromjson("{a:[{b:{c:1}}]}"));
ASSERT(!_client.findOne(ns, BSON("a.b.c" << 1)).isEmpty());
ASSERT(!_client.findOne(ns, fromjson("{'a.c':null}")).isEmpty());
}
};
class Size : public ClientBase {
public:
~Size() {
_client.dropCollection("unittests.querytests.Size");
}
void run() {
const char* ns = "unittests.querytests.Size";
_client.insert(ns, fromjson("{a:[1,2,3]}"));
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
ASSERT(_client.query(ns, QUERY("a" << mongo::BSIZE << 3).hint(BSON("a" << 1)))->more());
}
};
class FullArray : public ClientBase {
public:
~FullArray() {
_client.dropCollection("unittests.querytests.IndexedArray");
}
void run() {
const char* ns = "unittests.querytests.IndexedArray";
_client.insert(ns, fromjson("{a:[1,2,3]}"));
ASSERT(_client.query(ns, Query("{a:[1,2,3]}"))->more());
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
ASSERT(_client.query(ns, Query("{a:{$in:[1,[1,2,3]]}}").hint(BSON("a" << 1)))->more());
ASSERT(_client.query(ns, Query("{a:[1,2,3]}").hint(BSON("a" << 1)))->more()); // SERVER-146
}
};
class InsideArray : public ClientBase {
public:
~InsideArray() {
_client.dropCollection("unittests.querytests.InsideArray");
}
void run() {
const char* ns = "unittests.querytests.InsideArray";
_client.insert(ns, fromjson("{a:[[1],2]}"));
check("$natural");
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
check("a"); // SERVER-146
}
private:
void check(const string& hintField) {
const char* ns = "unittests.querytests.InsideArray";
ASSERT(_client.query(ns, Query("{a:[[1],2]}").hint(BSON(hintField << 1)))->more());
ASSERT(_client.query(ns, Query("{a:[1]}").hint(BSON(hintField << 1)))->more());
ASSERT(_client.query(ns, Query("{a:2}").hint(BSON(hintField << 1)))->more());
ASSERT(!_client.query(ns, Query("{a:1}").hint(BSON(hintField << 1)))->more());
}
};
class IndexInsideArrayCorrect : public ClientBase {
public:
~IndexInsideArrayCorrect() {
_client.dropCollection("unittests.querytests.IndexInsideArrayCorrect");
}
void run() {
const char* ns = "unittests.querytests.IndexInsideArrayCorrect";
_client.insert(ns, fromjson("{'_id':1,a:[1]}"));
_client.insert(ns, fromjson("{'_id':2,a:[[1]]}"));
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
ASSERT_EQUALS(
1, _client.query(ns, Query("{a:[1]}").hint(BSON("a" << 1)))->next().getIntField("_id"));
}
};
class SubobjArr : public ClientBase {
public:
~SubobjArr() {
_client.dropCollection("unittests.querytests.SubobjArr");
}
void run() {
const char* ns = "unittests.querytests.SubobjArr";
_client.insert(ns, fromjson("{a:[{b:[1]}]}"));
check("$natural");
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1)));
check("a");
}
private:
void check(const string& hintField) {
const char* ns = "unittests.querytests.SubobjArr";
ASSERT(_client.query(ns, Query("{'a.b':1}").hint(BSON(hintField << 1)))->more());
ASSERT(_client.query(ns, Query("{'a.b':[1]}").hint(BSON(hintField << 1)))->more());
}
};
class MinMax : public ClientBase {
public:
MinMax() : ns("unittests.querytests.MinMax") {}
~MinMax() {
_client.dropCollection("unittests.querytests.MinMax");
}
void run() {
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("a" << 1 << "b" << 1)));
_client.insert(ns, BSON("a" << 1 << "b" << 1));
_client.insert(ns, BSON("a" << 1 << "b" << 2));
_client.insert(ns, BSON("a" << 2 << "b" << 1));
_client.insert(ns, BSON("a" << 2 << "b" << 2));
ASSERT_EQUALS(4, count(_client.query(ns, BSONObj())));
BSONObj hints[] = {BSONObj(), BSON("a" << 1 << "b" << 1)};
for (int i = 0; i < 2; ++i) {
check(0, 0, 3, 3, 4, hints[i]);
check(1, 1, 2, 2, 3, hints[i]);
check(1, 2, 2, 2, 2, hints[i]);
check(1, 2, 2, 1, 1, hints[i]);
unique_ptr<DBClientCursor> c = query(1, 2, 2, 2, hints[i]);
BSONObj obj = c->next();
ASSERT_EQUALS(1, obj.getIntField("a"));
ASSERT_EQUALS(2, obj.getIntField("b"));
obj = c->next();
ASSERT_EQUALS(2, obj.getIntField("a"));
ASSERT_EQUALS(1, obj.getIntField("b"));
ASSERT(!c->more());
}
}
private:
unique_ptr<DBClientCursor> query(int minA, int minB, int maxA, int maxB, const BSONObj& hint) {
Query q;
q = q.minKey(BSON("a" << minA << "b" << minB)).maxKey(BSON("a" << maxA << "b" << maxB));
if (!hint.isEmpty())
q.hint(hint);
return _client.query(ns, q);
}
void check(
int minA, int minB, int maxA, int maxB, int expectedCount, const BSONObj& hint = empty_) {
ASSERT_EQUALS(expectedCount, count(query(minA, minB, maxA, maxB, hint)));
}
int count(unique_ptr<DBClientCursor> c) {
int ret = 0;
while (c->more()) {
++ret;
c->next();
}
return ret;
}
const char* ns;
static BSONObj empty_;
};
BSONObj MinMax::empty_;
class MatchCodeCodeWScope : public ClientBase {
public:
MatchCodeCodeWScope() : _ns("unittests.querytests.MatchCodeCodeWScope") {}
~MatchCodeCodeWScope() {
_client.dropCollection("unittests.querytests.MatchCodeCodeWScope");
}
void run() {
checkMatch();
ASSERT_OK(dbtests::createIndex(&_opCtx, _ns, BSON("a" << 1)));
checkMatch();
}
private:
void checkMatch() {
_client.remove(_ns, BSONObj());
_client.insert(_ns, code());
_client.insert(_ns, codeWScope());
ASSERT_EQUALS(1U, _client.count(_ns, code()));
ASSERT_EQUALS(1U, _client.count(_ns, codeWScope()));
ASSERT_EQUALS(1U, _client.count(_ns, BSON("a" << BSON("$type" << (int)Code))));
ASSERT_EQUALS(1U, _client.count(_ns, BSON("a" << BSON("$type" << (int)CodeWScope))));
}
BSONObj code() const {
BSONObjBuilder codeBuilder;
codeBuilder.appendCode("a", "return 1;");
return codeBuilder.obj();
}
BSONObj codeWScope() const {
BSONObjBuilder codeWScopeBuilder;
codeWScopeBuilder.appendCodeWScope("a", "return 1;", BSONObj());
return codeWScopeBuilder.obj();
}
const char* _ns;
};
class MatchDBRefType : public ClientBase {
public:
MatchDBRefType() : _ns("unittests.querytests.MatchDBRefType") {}
~MatchDBRefType() {
_client.dropCollection("unittests.querytests.MatchDBRefType");
}
void run() {
checkMatch();
ASSERT_OK(dbtests::createIndex(&_opCtx, _ns, BSON("a" << 1)));
checkMatch();
}
private:
void checkMatch() {
_client.remove(_ns, BSONObj());
_client.insert(_ns, dbref());
ASSERT_EQUALS(1U, _client.count(_ns, dbref()));
ASSERT_EQUALS(1U, _client.count(_ns, BSON("a" << BSON("$type" << (int)DBRef))));
}
BSONObj dbref() const {
BSONObjBuilder b;
OID oid;
b.appendDBRef("a", "ns", oid);
return b.obj();
}
const char* _ns;
};
class DirectLocking : public ClientBase {
public:
void run() {
Lock::GlobalWrite lk(&_opCtx);
OldClientContext ctx(&_opCtx, "unittests.DirectLocking");
_client.remove("a.b", BSONObj());
ASSERT_EQUALS("unittests", ctx.db()->name());
}
const char* ns;
};
class FastCountIn : public ClientBase {
public:
~FastCountIn() {
_client.dropCollection("unittests.querytests.FastCountIn");
}
void run() {
const char* ns = "unittests.querytests.FastCountIn";
_client.insert(ns,
BSON("i"
<< "a"));
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("i" << 1)));
ASSERT_EQUALS(1U, _client.count(ns, fromjson("{i:{$in:['a']}}")));
}
};
class EmbeddedArray : public ClientBase {
public:
~EmbeddedArray() {
_client.dropCollection("unittests.querytests.EmbeddedArray");
}
void run() {
const char* ns = "unittests.querytests.EmbeddedArray";
_client.insert(ns, fromjson("{foo:{bar:['spam']}}"));
_client.insert(ns, fromjson("{foo:{bar:['spam','eggs']}}"));
_client.insert(ns, fromjson("{bar:['spam']}"));
_client.insert(ns, fromjson("{bar:['spam','eggs']}"));
ASSERT_EQUALS(2U,
_client.count(ns,
BSON("bar"
<< "spam")));
ASSERT_EQUALS(2U,
_client.count(ns,
BSON("foo.bar"
<< "spam")));
}
};
class DifferentNumbers : public ClientBase {
public:
~DifferentNumbers() {
_client.dropCollection("unittests.querytests.DifferentNumbers");
}
void t(const char* ns) {
unique_ptr<DBClientCursor> cursor = _client.query(ns, Query().sort("7"));
while (cursor->more()) {
BSONObj o = cursor->next();
verify(o.valid(BSONVersion::kLatest));
}
}
void run() {
const char* ns = "unittests.querytests.DifferentNumbers";
{
BSONObjBuilder b;
b.append("7", (int)4);
_client.insert(ns, b.obj());
}
{
BSONObjBuilder b;
b.append("7", (long long)2);
_client.insert(ns, b.obj());
}
{
BSONObjBuilder b;
b.appendNull("7");
_client.insert(ns, b.obj());
}
{
BSONObjBuilder b;
b.append("7", "b");
_client.insert(ns, b.obj());
}
{
BSONObjBuilder b;
b.appendNull("8");
_client.insert(ns, b.obj());
}
{
BSONObjBuilder b;
b.append("7", (double)3.7);
_client.insert(ns, b.obj());
}
t(ns);
ASSERT_OK(dbtests::createIndex(&_opCtx, ns, BSON("7" << 1)));
t(ns);
}
};
class CollectionBase : public ClientBase {
public:
CollectionBase(string leaf) {
_ns = "unittests.querytests.";
_ns += leaf;
_client.dropCollection(ns());
}
virtual ~CollectionBase() {
_client.dropCollection(ns());
}
int count() {
return (int)_client.count(ns());
}
size_t numCursorsOpen() {
AutoGetCollectionForReadCommand ctx(&_opCtx, NamespaceString(_ns));
Collection* collection = ctx.getCollection();
if (!collection)
return 0;
return collection->getCursorManager()->numCursors();
}
const char* ns() {
return _ns.c_str();
}
private:
string _ns;
};
class SymbolStringSame : public CollectionBase {
public:
SymbolStringSame() : CollectionBase("symbolstringsame") {}
void run() {
{
BSONObjBuilder b;
b.appendSymbol("x", "eliot");
b.append("z", 17);
_client.insert(ns(), b.obj());
}
ASSERT_EQUALS(17, _client.findOne(ns(), BSONObj())["z"].number());
{
BSONObjBuilder b;
b.appendSymbol("x", "eliot");
ASSERT_EQUALS(17, _client.findOne(ns(), b.obj())["z"].number());
}
ASSERT_EQUALS(17,
_client
.findOne(ns(),
BSON("x"
<< "eliot"))["z"]
.number());
ASSERT_OK(dbtests::createIndex(&_opCtx, ns(), BSON("x" << 1)));
ASSERT_EQUALS(17,
_client
.findOne(ns(),
BSON("x"
<< "eliot"))["z"]
.number());
}
};
class TailableCappedRaceCondition : public CollectionBase {
public:
TailableCappedRaceCondition() : CollectionBase("tailablecappedrace") {
_client.dropCollection(ns());
_n = 0;
}
void run() {
string err;
OldClientWriteContext ctx(&_opCtx, ns());
// note that extents are always at least 4KB now - so this will get rounded up
// a bit.
{
WriteUnitOfWork wunit(&_opCtx);
ASSERT(userCreateNS(&_opCtx,
ctx.db(),
ns(),
fromjson("{ capped : true, size : 2000, max: 10000 }"),
CollectionOptions::parseForCommand,
false)
.isOK());
wunit.commit();
}
for (int i = 0; i < 200; i++) {
insertNext();
ASSERT(count() < 90);
}
int a = count();
unique_ptr<DBClientCursor> c =
_client.query(ns(),
QUERY("i" << GT << 0).hint(BSON("$natural" << 1)),
0,
0,
0,
QueryOption_CursorTailable);
int n = 0;
while (c->more()) {
BSONObj z = c->next();
n++;
}
ASSERT_EQUALS(a, n);
insertNext();
ASSERT(c->more());
for (int i = 0; i < 90; i++) {
insertNext();
}
while (c->more()) {
c->next();
}
}
void insertNext() {
BSONObjBuilder b;
b.appendOID("_id", 0, true);
b.append("i", _n++);
insert(ns(), b.obj());
}
int _n;
};
class HelperTest : public CollectionBase {
public:
HelperTest() : CollectionBase("helpertest") {}
void run() {
OldClientWriteContext ctx(&_opCtx, ns());
for (int i = 0; i < 50; i++) {
insert(ns(), BSON("_id" << i << "x" << i * 2));
}
ASSERT_EQUALS(50, count());
BSONObj res;
ASSERT(Helpers::findOne(&_opCtx, ctx.getCollection(), BSON("_id" << 20), res, true));
ASSERT_EQUALS(40, res["x"].numberInt());
ASSERT(Helpers::findById(&_opCtx, ctx.db(), ns(), BSON("_id" << 20), res));
ASSERT_EQUALS(40, res["x"].numberInt());
ASSERT(!Helpers::findById(&_opCtx, ctx.db(), ns(), BSON("_id" << 200), res));
long long slow;
long long fast;
int n = 10000;
DEV n = 1000;
{
Timer t;
for (int i = 0; i < n; i++) {
ASSERT(
Helpers::findOne(&_opCtx, ctx.getCollection(), BSON("_id" << 20), res, true));
}
slow = t.micros();
}
{
Timer t;
for (int i = 0; i < n; i++) {
ASSERT(Helpers::findById(&_opCtx, ctx.db(), ns(), BSON("_id" << 20), res));
}
fast = t.micros();
}
std::cout << "HelperTest slow:" << slow << " fast:" << fast << endl;
}
};
class HelperByIdTest : public CollectionBase {
public:
HelperByIdTest() : CollectionBase("helpertestbyid") {}
void run() {
OldClientWriteContext ctx(&_opCtx, ns());
for (int i = 0; i < 1000; i++) {
insert(ns(), BSON("_id" << i << "x" << i * 2));
}
for (int i = 0; i < 1000; i += 2) {
_client.remove(ns(), BSON("_id" << i));
}
BSONObj res;
for (int i = 0; i < 1000; i++) {
bool found = Helpers::findById(&_opCtx, ctx.db(), ns(), BSON("_id" << i), res);
ASSERT_EQUALS(i % 2, int(found));
}
}
};
class ClientCursorTest : public CollectionBase {
ClientCursorTest() : CollectionBase("clientcursortest") {}
void run() {
OldClientWriteContext ctx(&_opCtx, ns());
for (int i = 0; i < 1000; i++) {
insert(ns(), BSON("_id" << i << "x" << i * 2));
}
}
};
class FindingStart : public CollectionBase {
public:
FindingStart() : CollectionBase("findingstart") {}
void run() {
BSONObj info;
ASSERT(_client.runCommand("unittests",
BSON("create"
<< "querytests.findingstart"
<< "capped"
<< true
<< "$nExtents"
<< 5
<< "autoIndexId"
<< false),
info));
int i = 0;
int max = 1;
while (1) {
int oldCount = count();
_client.insert(ns(), BSON("ts" << i++));
int newCount = count();
if (oldCount == newCount || newCount < max)
break;
if (newCount > max)
max = newCount;
}
for (int k = 0; k < 5; ++k) {
_client.insert(ns(), BSON("ts" << i++));
int min =
_client.query(ns(), Query().sort(BSON("$natural" << 1)))->next()["ts"].numberInt();
for (int j = -1; j < i; ++j) {
unique_ptr<DBClientCursor> c =
_client.query(ns(), QUERY("ts" << GTE << j), 0, 0, 0, QueryOption_OplogReplay);
ASSERT(c->more());
BSONObj next = c->next();
ASSERT(!next["ts"].eoo());
ASSERT_EQUALS((j > min ? j : min), next["ts"].numberInt());
}
}
}
};
class FindingStartPartiallyFull : public CollectionBase {
public:
FindingStartPartiallyFull() : CollectionBase("findingstart") {}
void run() {
size_t startNumCursors = numCursorsOpen();
BSONObj info;
ASSERT(_client.runCommand("unittests",
BSON("create"
<< "querytests.findingstart"
<< "capped"
<< true
<< "$nExtents"
<< 5
<< "autoIndexId"
<< false),
info));
int i = 0;
for (; i < 150; _client.insert(ns(), BSON("ts" << i++)))
;
for (int k = 0; k < 5; ++k) {
_client.insert(ns(), BSON("ts" << i++));
int min =
_client.query(ns(), Query().sort(BSON("$natural" << 1)))->next()["ts"].numberInt();
for (int j = -1; j < i; ++j) {
unique_ptr<DBClientCursor> c =
_client.query(ns(), QUERY("ts" << GTE << j), 0, 0, 0, QueryOption_OplogReplay);
ASSERT(c->more());
BSONObj next = c->next();
ASSERT(!next["ts"].eoo());
ASSERT_EQUALS((j > min ? j : min), next["ts"].numberInt());
}
}
ASSERT_EQUALS(startNumCursors, numCursorsOpen());
}
};
/**
* Check OplogReplay mode where query timestamp is earlier than the earliest
* entry in the collection.
*/
class FindingStartStale : public CollectionBase {
public:
FindingStartStale() : CollectionBase("findingstart") {}
void run() {
size_t startNumCursors = numCursorsOpen();
// Check OplogReplay mode with missing collection.
unique_ptr<DBClientCursor> c0 =
_client.query(ns(), QUERY("ts" << GTE << 50), 0, 0, 0, QueryOption_OplogReplay);
ASSERT(!c0->more());
BSONObj info;
ASSERT(_client.runCommand("unittests",
BSON("create"
<< "querytests.findingstart"
<< "capped"
<< true
<< "$nExtents"
<< 5
<< "autoIndexId"
<< false),
info));
// Check OplogReplay mode with empty collection.
unique_ptr<DBClientCursor> c =
_client.query(ns(), QUERY("ts" << GTE << 50), 0, 0, 0, QueryOption_OplogReplay);
ASSERT(!c->more());
// Check with some docs in the collection.
for (int i = 100; i < 150; _client.insert(ns(), BSON("ts" << i++)))
;
c = _client.query(ns(), QUERY("ts" << GTE << 50), 0, 0, 0, QueryOption_OplogReplay);
ASSERT(c->more());
ASSERT_EQUALS(100, c->next()["ts"].numberInt());
// Check that no persistent cursors outlast our queries above.
ASSERT_EQUALS(startNumCursors, numCursorsOpen());
}
};
class WhatsMyUri : public CollectionBase {
public:
WhatsMyUri() : CollectionBase("whatsmyuri") {}
void run() {
BSONObj result;
_client.runCommand("admin", BSON("whatsmyuri" << 1), result);
ASSERT_EQUALS("", result["you"].str());
}
};
class CollectionInternalBase : public CollectionBase {
public:
CollectionInternalBase(const char* nsLeaf)
: CollectionBase(nsLeaf), _lk(&_opCtx, "unittests", MODE_X), _ctx(&_opCtx, ns()) {}
private:
Lock::DBLock _lk;
OldClientContext _ctx;
};
class Exhaust : public CollectionInternalBase {
public:
Exhaust() : CollectionInternalBase("exhaust") {}
void run() {
BSONObj info;
ASSERT(_client.runCommand("unittests",
BSON("create"
<< "querytests.exhaust"
<< "capped"
<< true
<< "size"
<< 8192),
info));
_client.insert(ns(), BSON("ts" << 0));
Message message;
assembleQueryRequest(ns(),
BSON("ts" << GTE << 0),
0,
0,
0,
QueryOption_OplogReplay | QueryOption_CursorTailable |
QueryOption_Exhaust,
message);
DbMessage dbMessage(message);
QueryMessage queryMessage(dbMessage);
Message result;
string exhaust = runQuery(&_opCtx, queryMessage, NamespaceString(ns()), result);
ASSERT(exhaust.size());
ASSERT_EQUALS(string(ns()), exhaust);
}
};
class QueryReadsAll : public CollectionBase {
public:
QueryReadsAll() : CollectionBase("queryreadsall") {}
void run() {
for (int i = 0; i < 5; ++i) {
insert(ns(), BSONObj());
}
{
// With five results and a batch size of 5, a cursor is created since we don't know
// there are no more results.
std::unique_ptr<DBClientCursor> c = _client.query(ns(), Query(), 5);
ASSERT(c->more());
ASSERT_NE(0, c->getCursorId());
for (int i = 0; i < 5; ++i) {
ASSERT(c->more());
c->next();
}
ASSERT(!c->more());
}
{
// With a batchsize of 6 we know there are no more results so we don't create a
// cursor.
std::unique_ptr<DBClientCursor> c = _client.query(ns(), Query(), 6);
ASSERT(c->more());
ASSERT_EQ(0, c->getCursorId());
}
}
};
namespace queryobjecttests {
class names1 {
public:
void run() {
ASSERT_BSONOBJ_EQ(BSON("x" << 1), QUERY("query" << BSON("x" << 1)).getFilter());
ASSERT_BSONOBJ_EQ(BSON("x" << 1), QUERY("$query" << BSON("x" << 1)).getFilter());
}
};
} // namespace queryobjecttests
class OrderingTest {
public:
void run() {
{
Ordering o = Ordering::make(BSON("a" << 1 << "b" << -1 << "c" << 1));
ASSERT_EQUALS(1, o.get(0));
ASSERT_EQUALS(-1, o.get(1));
ASSERT_EQUALS(1, o.get(2));
ASSERT(!o.descending(1));
ASSERT(o.descending(1 << 1));
ASSERT(!o.descending(1 << 2));
}
{
Ordering o = Ordering::make(BSON("a.d" << 1 << "a" << 1 << "e" << -1));
ASSERT_EQUALS(1, o.get(0));
ASSERT_EQUALS(1, o.get(1));
ASSERT_EQUALS(-1, o.get(2));
ASSERT(!o.descending(1));
ASSERT(!o.descending(1 << 1));
ASSERT(o.descending(1 << 2));
}
}
};
class All : public Suite {
public:
All() : Suite("query") {}
void setupTests() {
add<FindingStart>();
add<FindOneOr>();
add<FindOneRequireIndex>();
add<FindOneEmptyObj>();
add<BoundedKey>();
add<GetMore>();
add<GetMoreKillOp>();
add<GetMoreInvalidRequest>();
add<PositiveLimit>();
add<TailNotAtEnd>();
add<EmptyTail>();
add<TailableDelete>();
add<TailableDelete2>();
add<TailableInsertDelete>();
add<TailCappedOnly>();
add<TailableQueryOnId>();
add<OplogReplayMode>();
add<OplogReplaySlaveReadTill>();
add<OplogReplayExplain>();
add<ArrayId>();
add<UnderscoreNs>();
add<EmptyFieldSpec>();
add<MultiNe>();
add<EmbeddedNe>();
add<EmbeddedNumericTypes>();
add<AutoResetIndexCache>();
add<UniqueIndex>();
add<UniqueIndexPreexistingData>();
add<SubobjectInArray>();
add<Size>();
add<FullArray>();
add<InsideArray>();
add<IndexInsideArrayCorrect>();
add<SubobjArr>();
add<MinMax>();
add<MatchCodeCodeWScope>();
add<MatchDBRefType>();
add<DirectLocking>();
add<FastCountIn>();
add<EmbeddedArray>();
add<DifferentNumbers>();
add<SymbolStringSame>();
add<TailableCappedRaceCondition>();
add<HelperTest>();
add<HelperByIdTest>();
add<FindingStartPartiallyFull>();
add<FindingStartStale>();
add<WhatsMyUri>();
add<Exhaust>();
add<QueryReadsAll>();
add<queryobjecttests::names1>();
add<OrderingTest>();
}
};
SuiteInstance<All> myall;
} // namespace QueryTests
} // namespace
| 33.130608 | 100 | 0.534734 | [
"object",
"vector"
] |
101c086087d8f0ff155ac0ee90a477b2a93c6de2 | 9,622 | hh | C++ | packages/MC/geometry/RTK_Geometry.hh | GCZhang/Profugus | d4d8fe295a92a257b26b6082224226ca1edbff5d | [
"BSD-2-Clause"
] | 19 | 2015-06-04T09:02:41.000Z | 2021-04-27T19:32:55.000Z | packages/MC/geometry/RTK_Geometry.hh | GCZhang/Profugus | d4d8fe295a92a257b26b6082224226ca1edbff5d | [
"BSD-2-Clause"
] | null | null | null | packages/MC/geometry/RTK_Geometry.hh | GCZhang/Profugus | d4d8fe295a92a257b26b6082224226ca1edbff5d | [
"BSD-2-Clause"
] | 5 | 2016-10-05T20:48:28.000Z | 2021-06-21T12:00:54.000Z | //----------------------------------*-C++-*----------------------------------//
/*!
* \file MC/geometry/RTK_Geometry.hh
* \author Thomas M. Evans
* \date Tuesday April 29 16:43:25 2014
* \brief RTK_Geometry class definition.
* \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#ifndef MC_geometry_RTK_Geometry_hh
#define MC_geometry_RTK_Geometry_hh
#include <cmath>
#include <memory>
#include "harness/DBC.hh"
#include "harness/Soft_Equivalence.hh"
#include "utils/Constants.hh"
#include "utils/Vector_Functions.hh"
#include "RTK_State.hh"
#include "RTK_Cell.hh"
#include "RTK_Array.hh"
#include "Tracking_Geometry.hh"
namespace profugus
{
//===========================================================================//
/*!
* \class RTK_Geometry
* \brief Defines geometry implementations for the RTK MC geometry.
*
* The profugus::RTK_Array and profugus::RTK_Cell classes allow clients to
* build hierarchical arrays of pin-cells, arrays of arrays of pin-cells, etc.
* In this way, simple LWR reactor geometries can be constructed quickly.
* However, in order to use these classes in the profugus MC framework, they
* must be defined as a profugus::RTK_Geometry. The RTK_Geometry class
* provides the correct publicly derived interface to profugus::RTK_Geometry
* so that the profugus MC classes can use this as a geometry implementation.
* This class is parameterized on Array so that different types of geometries
* can be constructed from the same code, ie.
* \code
typedef RTK_Geometry< RTK_Array<RTK_Cell> > Lattice;
typedef RTK_Geometry< RTK_Array< RTK_Array<RTK_Cell> > > Core;
// make an RTK_Core core reactor geometry
typedef profugus::Core Core_Geometry;
typedef Core_Geometry::Array_t Core_t;
typedef Core_t::Object_t Lattice_t;
typedef Lattice_t::Object_t Pin_Cell_t;
typedef Core_Geometry::SP_Array SP_Core;
typedef Core_t::SP_Object SP_Lattice;
typedef Lattice_t::SP_Object SP_Pin_Cell;
SP_Core core(new Core_t(...));
// ...
Core_Geometry rtk_core(core);
* \endcode
* See the tests for more examples.
*
* \sa profugus::RTK_Array, profugus::RTK_Cell
*/
/*!
* \example geometry/rtk/test/tstLattice.cc
* \example geometry/rtk/test/tstCore.cc
*
* Test of RTK_Geometry implementations.
*/
//===========================================================================//
template<class Array>
class RTK_Geometry : public Tracking_Geometry<RTK_State>
{
public:
//@{
//! Typedefs.
typedef Array Array_t;
typedef std::shared_ptr<Array_t> SP_Array;
typedef def::Vec_Dbl Vec_Dbl;
typedef def::Vec_Int Vec_Int;
//@}
private:
// >>> DATA
// Underlying object.
SP_Array d_array;
// Volumes of each cell
Vec_Dbl d_volumes;
// Level of array.
const int d_level;
public:
// Constructor.
explicit RTK_Geometry(SP_Array array);
// >>> DERIVED INTERFACE from Geometry_Base
//! Initialize a track.
void initialize(const Space_Vector &r, const Space_Vector &direction,
Geo_State_t &state) const;
//! Get distance to next boundary.
double distance_to_boundary(Geo_State_t &state)
{
REQUIRE(d_array);
d_array->distance_to_boundary(state.d_r, state.d_dir, state);
return state.dist_to_next_region;
}
//! Move to and cross a cell surface (do not reflect the particle, but
//! indicate that the particle is on a reflecting surface).
void move_to_surface(Geo_State_t &state)
{
REQUIRE(d_array);
// move the particle
move(state.dist_to_next_region, state);
// process the particle through the surface
d_array->cross_surface(state.d_r, state);
}
//! Move the particle to a point in the current direction.
/// Clear any surface tags; the final point should \b not be a boundary
/// surface.
void move_to_point(double d, Geo_State_t &state)
{
REQUIRE(d_array);
// move the particle
move(d, state);
// update the array state to clear any surface tags
d_array->update_state(state);
}
//! Number of cells (excluding "outside" cell)
geometry::cell_type num_cells() const { return d_array->num_cells(); }
// Get the volume for a cell
double cell_volume(int cellid) const
{
REQUIRE(cellid < num_cells());
CHECK(cellid < d_volumes.size());
double vol = d_volumes[cellid];
ENSURE(vol >= 0.0);
return vol;
}
//! Return the current cell ID
geometry::cell_type cell(const Geo_State_t &state) const
{
// Note: large arrays may overflow signed int
ENSURE(d_array->cellid(state) >= 0);
return d_array->cellid(state);
}
//! Return the cell ID from the given location
geometry::cell_type cell(const Space_Vector &r) const
{
return Tracking_Geometry<RTK_State>::cell(r);
}
//! Return the current material ID
geometry::matid_type matid(const Geo_State_t &state) const
{
// we need a better mechanism later on....TME
return d_array->matid(state);
}
//! Return the material ID from the given location
geometry::matid_type matid(const Space_Vector &r) const
{
return Tracking_Geometry<RTK_State>::matid(r);
}
//! Return the state with respect to outer geometry boundary
geometry::Boundary_State boundary_state(const Geo_State_t &state) const
{
if (state.escaping_face != Geo_State_t::NONE)
{
// if the particle has escaped indicate that the particle
// is outside the geometry
CHECK(state.exiting_level[d_level]
|| state.next_face == Geo_State_t::NONE);
return geometry::OUTSIDE;
}
else if (state.reflecting_face != Geo_State_t::NONE)
{
// test of reflection on the given face
return geometry::REFLECT;
}
return geometry::INSIDE;
}
//! Return the boundary state for a given position
geometry::Boundary_State boundary_state(const Space_Vector &r) const
{
return Tracking_Geometry<RTK_State>::boundary_state(r);
}
//! Return the current position.
Space_Vector position(const Geo_State_t &state) const { return state.d_r; }
//! Return the current direction.
Space_Vector direction(const Geo_State_t &state) const {return state.d_dir;}
//! Change the particle direction.
void change_direction(const Space_Vector &new_direction, Geo_State_t &state)
{
// update the direction
state.d_dir = new_direction;
// normalize the direction
vector_normalize(state.d_dir);
}
// Change the direction through angles \f$(\theta,\phi)\f$.
void change_direction(double costheta, double phi, Geo_State_t &state)
{
cartesian_vector_transform(costheta, phi, state.d_dir);
}
// Reflect the direction at a reflecting surface.
bool reflect(Geo_State_t &state);
// Return the outward normal.
Space_Vector normal(const Geo_State_t &state) const;
// >>> ACCESSORS
//! Return vector of cell volumes
const Vec_Dbl &cell_volumes() const
{
REQUIRE( d_volumes.size() == num_cells() );
return d_volumes;
}
//! Return the underlying array representation of objects.
const Array_t& array() const { REQUIRE(d_array); return *d_array; }
// Get bounding box
Bounding_Box get_extents() const;
// Get bounding box for a cell
Bounding_Box get_cell_extents(geometry::cell_type cell) const;
// Diagnostic output.
void output(std::ostream &out) const
{
REQUIRE( d_array );
d_array->output(out);
}
private:
// >>> IMPLEMENTATION
/*! \brief Move a particle a distance \e d in the current direction.
*
* A particle is moved through a distance \f$d\f$ according to,
* \f[
* \left(\begin{array}{l}
* x\\y\\z\end{array}\right) =
* \left(\begin{array}{l}
* x_o\\y_o\\z_o\end{array}\right) + d
* \left(\begin{array}{l}
* \Omega_x\\ \Omega_y\\ \Omega_z\end{array}\right)\:.
* \f]
*
* The direction vector of the particle must be a unit-vector, ie:
* \f$|\Omega| = 1\f$.
*/
void move(double d, Geo_State_t &state)
{
REQUIRE(d >= 0.0);
REQUIRE(soft_equiv(vector_magnitude(state.d_dir), 1.0, 1.0e-6));
// advance the particle (unrolled loop)
state.d_r[def::X] += d * state.d_dir[def::X];
state.d_r[def::Y] += d * state.d_dir[def::Y];
state.d_r[def::Z] += d * state.d_dir[def::Z];
}
private:
// Lower and upper extents of the enclosed array
Space_Vector d_lower;
Space_Vector d_upper;
};
//---------------------------------------------------------------------------//
// GEOMETRY TYPES
//---------------------------------------------------------------------------//
//@{
//! Single-level lattice/core geometries.
typedef RTK_Geometry< RTK_Array<RTK_Cell> > Lattice;
typedef RTK_Geometry< RTK_Array< RTK_Array<RTK_Cell> > > Core;
//@}
} // end namespace profugus
#endif // MC_geometry_RTK_Geometry_hh
//---------------------------------------------------------------------------//
// end of geometry/RTK_Geometry.hh
//---------------------------------------------------------------------------//
| 30.839744 | 80 | 0.609333 | [
"geometry",
"object",
"vector"
] |
102231abaa79d5328def5272ce8c2925cb337e4a | 2,570 | cpp | C++ | Worms/src/InGame/Entity/Object/Item/Banana/BabyBanana.cpp | GearEngine/GearEngine | fa5ed49ca6289a215799a7b84ece1241eb33bd36 | [
"Apache-2.0"
] | 3 | 2020-03-05T06:56:51.000Z | 2020-03-12T09:36:20.000Z | Worms/src/InGame/Entity/Object/Item/Banana/BabyBanana.cpp | GearEngine/GearEngine | fa5ed49ca6289a215799a7b84ece1241eb33bd36 | [
"Apache-2.0"
] | 2 | 2020-03-05T15:40:28.000Z | 2020-03-11T16:04:44.000Z | Worms/src/InGame/Entity/Object/Item/Banana/BabyBanana.cpp | GearEngine/GearEngine | fa5ed49ca6289a215799a7b84ece1241eb33bd36 | [
"Apache-2.0"
] | null | null | null | #include "wmpch.h"
#include "BabyBanana.h"
#include "BabyBananaFSMHandlers.h"
#include "../ItemPixelCollisionHandler.h"
#include "../ItemStatusHandler.h"
namespace InGame {
BabyBanana::BabyBanana(const InitiateData & initData)
{
m_ID = Gear::EntitySystem::CreateEntity(false);
Gear::EntitySystem::AttachComponent(m_ID, {
Gear::ComponentID::FSM, Gear::ComponentID::Timer, Gear::ComponentID::Drawer,
Gear::ComponentID::Status, Gear::ComponentID::Transform, Gear::ComponentID::Physics,
Gear::ComponentID::Animator
});
Gear::EntitySystem::SetAnimator(m_ID, {
{ Item::State::OnGoing, Gear::Animation2D::Create(Gear::TextureStorage::GetFrameTexture2D("BananaBullet"), 0.0f) }
});
Gear::EntitySystem::SetFSM(m_ID, {
{ Item::State::OnGoing, new BabyBananaOnGoingHandler }, { Item::State::OnUnderWater, new BabyBananaOnUnderWater},
{ Item::State::OnExplosion, new BabyBananaOnExplosion },
});
auto mask = initData.Mapinfo.Mask;
int width = mask->GetWidth();
int height = mask->GetHeight();
auto maskTranslate = glm::translate(glm::mat4(1.0f), initData.MapPosition)
* glm::scale(glm::mat4(1.0f), { width / initData.MapReductionRatio , height / initData.MapReductionRatio , 1.0f });
Gear::EntitySystem::SetPhysics(m_ID, true, 20.f, -0.1f);
Gear::EntitySystem::SetPixelCollision(m_ID, { 255, 255, 255 }, mask, maskTranslate, {
{ "BabyPC", Gear::CreateRef<BabyTypePCHandler>() },
{ "GeneralWeaponUnderWater", Gear::CreateRef<GaneralWeaponOnUnderWater>() }
});
Gear::EntitySystem::SetStatus(m_ID, {
{ Item::Info::Angle, 0.0f}, { Item::Info::Power, 100.0f }, {Item::Info::ExplosionText, Explosion::Text::Poot}, {Item::Info::ExplosionSize, Explosion::Size::Size75},
{ Item::Info::From, -1}, { Item::Info::Number, ItemInfo::Number::BabyBanana }
});
}
void BabyBanana::init(const glm::vec3 & position, float initAngle, float initPower, int From, float explosionTime)
{
Gear::EntitySystem::ActivateEntity(m_ID);
Gear::EntitySystem::GetFSM(m_ID)->SetCurrentState(Item::State::OnGoing);
auto timer = Gear::EntitySystem::GetTimer(m_ID);
timer->SetTimer(explosionTime + 0.1f);
timer->Start();
glm::vec3 pos = position;
pos.z = ZOrder::z_Item;
Gear::EntitySystem::SetTransform(m_ID, pos, 0.0f, glm::vec2(1.8f, 1.8f));
auto physics = Gear::EntitySystem::GetPhysics2D(m_ID);
glm::vec2 ExternalVector(initPower * glm::cos(glm::radians(initAngle)), initPower * glm::sin(glm::radians(initAngle)));
physics->SetExternalVector(ExternalVector);
physics->SetPixelCollisionHandler("BabyPC");
}
} | 39.538462 | 167 | 0.710895 | [
"transform"
] |
102361c219e80c41f62c73baae1a16a44d0e1a7d | 5,851 | cpp | C++ | Foundation/extensions/DataspaceLib/tests/GainDataspace.test.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | Foundation/extensions/DataspaceLib/tests/GainDataspace.test.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | Foundation/extensions/DataspaceLib/tests/GainDataspace.test.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | /** @file
*
* @ingroup foundationDataspaceLib
*
* @brief Unit tests for the #GainDataspace.
*
* @authors Trond Lossius, Tim Place, Nils Peters, ...
*
* @copyright Copyright © 2011 Trond Lossius @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
// Dataspaces and Units employ C++ double-inheritance and are thus unsuitable for direct use
// through the usual TTObject API
#define TT_NO_DEPRECATION_WARNINGS
#include "GainDataspace.h"
TTErr GainDataspace::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
// Create dataspace object and set to temperature
TTObjectBasePtr myDataspace = NULL;
TTErr err;
err = TTObjectBaseInstantiate(TT("dataspace"), (TTObjectBasePtr*)&myDataspace, 0);
myDataspace->setAttributeValue(TT("dataspace"), TT("gain"));
TTValue v;
TTValue expected;
/************************************************/
/* */
/* Test conversions to neutral unit */
/* */
/************************************************/
// Linear => Linear
myDataspace->setAttributeValue(TT("inputUnit"), TT("linear"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("linear"));
v = TTValue(1.23);
expected = TTValue(1.23);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("linear to linear",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
// dB => Linear
myDataspace->setAttributeValue(TT("inputUnit"), TT("dB"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("linear"));
v = TTValue(0.);
expected = TTValue(1.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("0 dB to linear",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
// midi => Linear
myDataspace->setAttributeValue(TT("inputUnit"), TT("midi"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("linear"));
v = TTValue(100.0);
expected = TTValue(1.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("100 MIDI to linear",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
/************************************************/
/* */
/* Test conversions from neutral unit */
/* */
/************************************************/
// linear => dB
myDataspace->setAttributeValue(TT("inputUnit"), TT("linear"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("dB"));
v = TTValue(1.0);
expected = TTValue(0.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("1.0 linear to dB",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
// linear => midi
myDataspace->setAttributeValue(TT("inputUnit"), TT("linear"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("midi"));
v = TTValue(1.0);
expected = TTValue(100.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("1.0 linear to MIDI",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
/************************************************/
/* */
/* Some additional important midi relationships */
/* */
/************************************************/
// 127 midi => 10 dB
myDataspace->setAttributeValue(TT("inputUnit"), TT("midi"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("dB"));
v = TTValue(127.0);
expected = TTValue(10.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("127 MIDI to 10 dB",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
// 10 dB => 127 midi
myDataspace->setAttributeValue(TT("inputUnit"), TT("dB"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("midi"));
v = TTValue(10.0);
expected = TTValue(127.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("10 dB to 127 MIDI",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
// 0 midi => 0 linear
myDataspace->setAttributeValue(TT("inputUnit"), TT("midi"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("linear"));
v = TTValue(0.0);
expected = TTValue(0.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("0 MIDI to 0 linear",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
// 0 linear => 0 midi
myDataspace->setAttributeValue(TT("inputUnit"), TT("linear"));
myDataspace->setAttributeValue(TT("outputUnit"), TT("midi"));
v = TTValue(0.0);
expected = TTValue(0.0);
myDataspace->sendMessage(TT("convert"), v, v);
TTTestAssertion("0 linear to 0 midi",
TTTestFloatEquivalence(TTFloat64(v), TTFloat64(expected)),
testAssertionCount,
errorCount);
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
| 29.40201 | 92 | 0.554606 | [
"object"
] |
1025cbed7e23615e5f5f8531aec429866cb1a5df | 8,342 | cpp | C++ | tests/static_sync_index.cpp | FreshDISKANN/FreshDISKANN | c7750ed7ae2df202b3f3a98477199963245c8ba7 | [
"MIT"
] | 6 | 2020-10-13T11:30:53.000Z | 2021-12-03T15:50:15.000Z | tests/static_sync_index.cpp | FreshDISKANN/FreshDISKANN | c7750ed7ae2df202b3f3a98477199963245c8ba7 | [
"MIT"
] | null | null | null | tests/static_sync_index.cpp | FreshDISKANN/FreshDISKANN | c7750ed7ae2df202b3f3a98477199963245c8ba7 | [
"MIT"
] | 3 | 2020-10-13T11:30:55.000Z | 2021-12-02T14:29:42.000Z | #include <index.h>
#include <future>
#include <Neighbor_Tag.h>
#include <numeric>
#include <omp.h>
#include <shard.h>
#include <string.h>
#include <sync_index.h>
#include <time.h>
#include <timer.h>
#include <cstring>
#include <iomanip>
#include "aux_utils.h"
#include "utils.h"
#ifndef _WINDOWS
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "memory_mapper.h"
#define NUM_INSERT_THREADS 16
#define NUM_DELETE_THREADS 4
#define NUM_SEARCH_THREADS 4
template<typename T, typename TagT>
void sync_search_kernel(T* query, size_t query_num, size_t query_aligned_dim,
const int recall_at, _u64 L,
diskann::SyncIndex<T, TagT>& sync_index,
const std::string& truthset_file,
tsl::robin_set<TagT>& inactive_tags) {
unsigned* gt_ids = NULL;
float* gt_dists = NULL;
size_t gt_num, gt_dim;
diskann::load_truthset(truthset_file, gt_ids, gt_dists, gt_num, gt_dim);
// query_num = 1;
float* query_result_dists = new float[recall_at * query_num];
TagT* query_result_tags = new TagT[recall_at * query_num];
// memset(query_result_dists, 0, sizeof(float) * recall_at * query_num);
// memset(query_result_tags, 0, sizeof(TagT) * recall_at * query_num);
for (_u32 q = 0; q < query_num; q++) {
for (_u32 r = 0; r < (_u32) recall_at; r++) {
query_result_tags[q * recall_at + r] = std::numeric_limits<TagT>::max();
query_result_dists[q * recall_at + r] = std::numeric_limits<float>::max();
}
}
std::vector<double> latency_stats(query_num, 0);
std::string recall_string = "Recall@" + std::to_string(recall_at);
std::cout << std::setw(4) << "Ls" << std::setw(12) << "QPS " << std::setw(18)
<< "Mean Latency (ms)" << std::setw(15) << "99.9 Latency"
<< std::setw(12) << recall_string << std::endl;
std::cout << "==============================================================="
"==============="
<< std::endl;
auto s = std::chrono::high_resolution_clock::now();
#pragma omp parallel for num_threads(NUM_SEARCH_THREADS)
for (int64_t i = 0; i < (int64_t) query_num; i++) {
auto qs = std::chrono::high_resolution_clock::now();
sync_index.search_async(query + i * query_aligned_dim, recall_at, L,
query_result_tags + i * recall_at,
query_result_dists + i * recall_at);
auto qe = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = qe - qs;
latency_stats[i] = diff.count() * 1000;
std::this_thread::sleep_for(std::chrono::milliseconds(2));
/* for (_u32 t = 0;t < (_u32) recall_at; t++) {
std::cout<<t<<": " << query_result_tags[i*recall_at + t] << ","
<<query_result_dists[i*recall_at +t] <<" ";
}
std::cout<<std::endl;
*/
}
auto e = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = e - s;
float qps = (query_num / diff.count());
float recall = diskann::calculate_recall(query_num, gt_ids, gt_dists, gt_dim,
query_result_tags, recall_at,
recall_at, inactive_tags);
std::sort(latency_stats.begin(), latency_stats.end());
std::cout << std::setw(4) << L << std::setw(12) << qps << std::setw(18)
<< std::accumulate(latency_stats.begin(), latency_stats.end(), 0) /
(float) query_num
<< std::setw(15) << (float) latency_stats[(_u64)(0.999 * query_num)]
<< std::setw(12) << recall << std::endl;
delete[] query_result_dists;
delete[] query_result_tags;
}
template<typename T, typename TagT>
void insertion_kernel(T* data_load, diskann::SyncIndex<T, TagT>& sync_index,
diskann::Parameters& paras, size_t num_points,
size_t num_start, size_t aligned_dim) {
diskann::Timer timer;
#pragma omp parallel for num_threads(NUM_INSERT_THREADS)
for (size_t i = num_start; i < num_points; i++) {
sync_index.insert(data_load + aligned_dim * i, i, paras);
}
float time_secs = timer.elapsed() / 1.0e6f;
std::cout << "Inserted " << num_points - num_start << " points in "
<< time_secs << "s" << std::endl;
}
template<typename T, typename TagT>
void delete_kernel(diskann::SyncIndex<T, TagT>& sync_index,
std::vector<TagT>& delete_vec) {
diskann::Timer timer;
#pragma omp parallel for num_threads(NUM_DELETE_THREADS)
for (size_t i = 0; i < delete_vec.size(); ++i)
sync_index.lazy_delete(delete_vec[i]);
float time_secs = timer.elapsed() / 1.0e6f;
std::cout << "Deleted " << delete_vec.size() << " points in " << time_secs
<< "s" << std::endl;
}
template<typename T, typename TagT>
void test(const std::string& data_path, const unsigned L_mem,
const unsigned R_mem, const float alpha_mem, const unsigned L_disk,
const unsigned R_disk, const float alpha_disk, const size_t num_start,
const size_t num_shards, const unsigned num_pq_chunks,
const unsigned nodes_to_cache, const std::string& save_path) {
diskann::Parameters paras;
paras.Set<unsigned>("L_mem", L_mem);
paras.Set<unsigned>("R_mem", R_mem);
paras.Set<float>("alpha_mem", alpha_mem);
paras.Set<unsigned>("L_disk", L_disk);
paras.Set<unsigned>("R_disk", R_disk);
paras.Set<float>("alpha_disk", alpha_disk);
paras.Set<unsigned>("C", 1500);
paras.Set<unsigned>("beamwidth", 5);
paras.Set<unsigned>("num_pq_chunks", num_pq_chunks);
paras.Set<unsigned>("nodes_to_cache", nodes_to_cache);
T* data_load = NULL;
size_t num_points, dim, aligned_dim;
diskann::load_aligned_bin<T>(data_path.c_str(), data_load, num_points, dim,
aligned_dim);
std::cout << "Loaded full data for driver." << std::endl;
diskann::SyncIndex<T, TagT> sync_index(num_points + 5000, dim, num_shards,
paras, 2, save_path);
std::cout << "Ran constructor." << std::endl;
std::vector<TagT> tags(num_start);
std::iota(tags.begin(), tags.end(), 0);
diskann::Timer timer;
sync_index.build(data_path.c_str(), num_start, tags);
std::cout << "Sync Index build time: " << timer.elapsed() / 1000000 << "s\n";
delete[] data_load;
}
int main(int argc, char** argv) {
if (argc < 14) {
std::cout
<< "Correct usage: " << argv[0]
<< " <type[int8/uint8/float]> <data_file> <L_mem> <R_mem> <alpha_mem>"
<< " <L_disk> <R_disk> <alpha_disk>"
<< " <num_start> <num_shards> <#pq_chunks> <#nodes_to_cache>"
<< " <save_graph_file>" << std::endl;
exit(-1);
}
int arg_no = 3;
unsigned L_mem = (unsigned) atoi(argv[arg_no++]);
unsigned R_mem = (unsigned) atoi(argv[arg_no++]);
float alpha_mem = (float) std::atof(argv[arg_no++]);
unsigned L_disk = (unsigned) atoi(argv[arg_no++]);
unsigned R_disk = (unsigned) atoi(argv[arg_no++]);
float alpha_disk = (float) std::atof(argv[arg_no++]);
size_t num_start = (size_t) std::atoi(argv[arg_no++]);
size_t num_shards = (size_t) std::atoi(argv[arg_no++]);
unsigned num_pq_chunks = (unsigned) std::atoi(argv[arg_no++]);
unsigned nodes_to_cache = (unsigned) std::atoi(argv[arg_no++]);
std::string save_path(argv[arg_no++]);
if (std::string(argv[1]) == std::string("int8"))
test<int8_t, unsigned>(argv[2], L_mem, R_mem, alpha_mem, L_disk, R_disk,
alpha_disk, num_start, num_shards, num_pq_chunks,
nodes_to_cache, save_path);
else if (std::string(argv[1]) == std::string("uint8"))
test<uint8_t, unsigned>(argv[2], L_mem, R_mem, alpha_mem, L_disk, R_disk,
alpha_disk, num_start, num_shards, num_pq_chunks,
nodes_to_cache, save_path);
else if (std::string(argv[1]) == std::string("float"))
test<float, unsigned>(argv[2], L_mem, R_mem, alpha_mem, L_disk, R_disk,
alpha_disk, num_start, num_shards, num_pq_chunks,
nodes_to_cache, save_path);
else
std::cout << "Unsupported type. Use float/int8/uint8" << std::endl;
}
| 41.093596 | 80 | 0.606689 | [
"vector"
] |
102624d80cdb9c316cf52958d04ef4a89ea54e7d | 25,429 | cpp | C++ | src/Root.cpp | kritzikratzi/ofxMightyUI | 63eaa7fcc8739e019f27500f68c4129a18be5434 | [
"MIT"
] | 52 | 2015-02-19T21:22:19.000Z | 2022-01-24T07:59:07.000Z | src/Root.cpp | kritzikratzi/ofxMightyUI | 63eaa7fcc8739e019f27500f68c4129a18be5434 | [
"MIT"
] | 5 | 2016-05-22T16:39:57.000Z | 2020-09-19T20:29:20.000Z | src/Root.cpp | kritzikratzi/ofxMightyUI | 63eaa7fcc8739e019f27500f68c4129a18be5434 | [
"MIT"
] | 14 | 2015-05-19T10:04:52.000Z | 2021-05-12T09:07:22.000Z | /*
* Root.cpp
* ofxMightyUI
*
* Created by hansi on 28.01.11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "Root.h"
#include "ofEventUtils.h"
#include "ofEvents.h"
#include "Container.h"
#include "ScrollPane.h"
#include "ofxMightyUI.h"
#include <GLFW/glfw3.h>
using namespace mui;
// TODO: the handleXX functions might return null, even if touchMovedOutside and touchUpOutside
// delegated to containers. this shouldn't be the case.
mui::Root * mui::Root::INSTANCE = NULL;
//--------------------------------------------------------------
mui::Root::Root() : Container( 0, 0, -1, -1 ){
INSTANCE = this;
ignoreEvents = true;
keyboardResponder = nullptr;
popupMenu = nullptr;
init();
};
//--------------------------------------------------------------
void mui::Root::init(){
#if TARGET_OS_IPHONE
NativeIOS::init();
// #elif TARGET_OS_MAC
// NativeOSX::init();
#endif
name = "Root";
width = ofGetWidth()/mui::MuiConfig::scaleFactor;
height = ofGetHeight()/mui::MuiConfig::scaleFactor;
ofAddListener( ofEvents().setup, this, &mui::Root::of_setup, OF_EVENT_ORDER_AFTER_APP );
ofAddListener( ofEvents().update, this, &mui::Root::of_update, OF_EVENT_ORDER_AFTER_APP );
ofAddListener( ofEvents().draw, this, &mui::Root::of_draw, OF_EVENT_ORDER_AFTER_APP );
//ofAddListener( ofEvents().exit, this, &mui::Root::of_exit );
ofAddListener( ofEvents().windowResized, this, &mui::Root::of_windowResized, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().keyPressed, this, &mui::Root::of_keyPressed, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().keyReleased, this, &mui::Root::of_keyReleased, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().mouseMoved, this, &mui::Root::of_mouseMoved, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().mouseDragged, this, &mui::Root::of_mouseDragged, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().mousePressed, this, &mui::Root::of_mousePressed, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().mouseReleased, this, &mui::Root::of_mouseReleased, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().mouseScrolled, this, &mui::Root::of_mouseScrolled, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().touchDown, this, &mui::Root::of_touchDown, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().touchUp, this, &mui::Root::of_touchUp, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().touchMoved, this, &mui::Root::of_touchMoved, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().touchDoubleTap, this, &mui::Root::of_touchDoubleTap, OF_EVENT_ORDER_BEFORE_APP );
ofAddListener( ofEvents().touchCancelled, this, &mui::Root::of_touchCancelled, OF_EVENT_ORDER_BEFORE_APP );
//ofAddListener( ofEvents().messageEvent, this, &mui::Root::of_messageEvent );
ofAddListener( ofEvents().fileDragEvent, this, &mui::Root::of_fileDragEvent, OF_EVENT_ORDER_BEFORE_APP );
// this seems unclear ... let's better put this in place!
for( int i = 0; i < OF_MAX_TOUCHES; i++ ){
touchResponder[i] = NULL;
}
}
void mui::Root::handleUpdate(){
int _width = ofGetWidth()/mui::MuiConfig::scaleFactor;
int _height = ofGetHeight()/mui::MuiConfig::scaleFactor;
if( width != _width || height != _height ){
width = _width;
height = _height;
handleLayout();
cout << "updating width width = " << width << ", height = " << height << endl;
}
else if( numLayoutFrames > 0 ){
numLayoutFrames--;
handleLayout();
cout << "updating width width = " << width << ", height = " << height << endl;
}
tweener.step( ofGetSystemTime() );
// figure out where we are hovering
set<Container*> newHoverResponder;
Container * c = findChildAt(ofGetMouseX()/mui::MuiConfig::scaleFactor, ofGetMouseY()/mui::MuiConfig::scaleFactor,true,true);
Container * top = c;
if(c){
ofMouseEventArgs args; //TODO: fix up coords
while(c!=nullptr){
if(!c->ignoreEvents){
newHoverResponder.insert(c);
if(hoverResponder.find(c) == hoverResponder.end() ){
c->mouseEnter(args);
c->onMouseEnter.notify(args);
}
}
c = c->parent;
}
}
if(manageCursor){
mui::Container * src = touchResponder[0] ? touchResponder[0] : top;
auto cursor = src? src->cursor : MUI_ROOT->cursor;
if( cursor != lastCursor){
muiSetCursor(cursor);
lastCursor = cursor;
}
}
for( Container * c : hoverResponder ){
ofMouseEventArgs args; //TODO: fix up coords
if(newHoverResponder.find(c) == newHoverResponder.end()){
c->mouseExit(args);
c->onMouseExit.notify(args);
}
}
hoverResponder = move(newHoverResponder);
Container::handleUpdate();
handleRemovals();
}
//--------------------------------------------------------------
void mui::Root::handleDraw(){
ofSetupScreenOrtho();
ofPushStyle();
ofScale( mui::MuiConfig::scaleFactor, mui::MuiConfig::scaleFactor, mui::MuiConfig::scaleFactor );
ofFill();
ofSetLineWidth( 1 );
ofSetColor( 255, 255, 255 );
ofEnableAlphaBlending();
Container::handleDraw();
handleRemovals();
if( mui::MuiConfig::debugDraw ){
mui::Container * active = this->findChildAt( ofGetMouseX()/mui::MuiConfig::scaleFactor - this->x, ofGetMouseY()/mui::MuiConfig::scaleFactor-this->y, true );
if( active != NULL ){
ofPoint p = active->getGlobalPosition();
ofPushMatrix();
ofFill();
string name;
mui::Container * c = active;
string size;
while( c != NULL ){
bool empty = c->name == "";
auto n = empty ? (typeid(*c).name()) : c->name;
name = (empty?"::":"") + n + (name==""?"":">") + name;
c = c->parent;
}
name = name + " [" + typeid(*active).name() + "]";
ofRectangle b = active->getGlobalBounds();
stringstream info;
info << "Pos:" << b.x << "," << b.y << " " << b.width << " x " << b.height << " / ";
info << "Rel:" << active->x << "," << active->y;
size = info.str();
ofxFontStashStyle style = mui::Helpers::getStyle(10);
ofNoFill();
ofSetColor( 255,255,0 );
ofDrawRectangle( p.x, p.y, active->width, active->height );
if (p.y > 30) p.y -= 30;
else p.y = min(muiGetHeight() - 30, p.y + active->height);
ofSetColor(255);
ofFill();
style.color = ofColor(0);
style.blur = 5;
for(int i = 0; i < 10; i++){
mui::Helpers::getFontStash().draw(name, style, p.x, p.y+10);
mui::Helpers::getFontStash().draw(size, style, p.x, p.y+20);
}
style.color = ofColor(255);
style.blur = 0;
mui::Helpers::getFontStash().draw(name, style, p.x, p.y+10);
mui::Helpers::getFontStash().draw(size, style, p.x, p.y+20);
ofPopMatrix();
ofSetColor(255);
}
}
ofPopStyle();
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleTouchDown( ofTouchEventArgs &touch ){
#if TARGET_OS_IPHONE
NativeIOS::hide();
// #elif TARGET_OS_MAC
// NativeOSX::hide();
#endif
ofTouchEventArgs copy = touch;
fixTouchPosition( touch, copy, NULL );
//return ( touchResponder[touch.id] = Container::handleTouchDown( copy ) );
Container * lastPopup = popupMenu;
touchResponder[touch.id] = nullptr;
touchResponder[touch.id] = Container::handleTouchDown( copy );
if( touchResponder[touch.id] != keyboardResponder ) keyboardResponder = NULL;
if( popupMenu == lastPopup ) removePopupIfNecessary(touchResponder[touch.id]);
return touchResponder[touch.id];
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleTouchMoved( ofTouchEventArgs &touch ){
ofTouchEventArgs copy = touch;
fixTouchPosition( touch, copy, NULL );
Container * touched = Container::handleTouchMoved( copy );
if( touched != touchResponder[touch.id] && touchResponder[touch.id] != NULL ){
copy = touch;
fixTouchPosition( touch, copy, NULL );
copy = Helpers::translateTouch( copy, this, touchResponder[touch.id] );
touchResponder[touch.id]->touchMovedOutside( copy );
touchResponder[touch.id]->onTouchMovedOutside.notify(copy);
return touchResponder[touch.id];
}
return touched;
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleTouchHover( ofTouchEventArgs &touch ){
ofTouchEventArgs copy = touch;
fixTouchPosition( touch, copy, NULL );
Container * touched = Container::handleTouchHover( copy );
if( touched != touchResponder[touch.id] && touchResponder[touch.id] != NULL ){
copy = touch;
fixTouchPosition( touch, copy, NULL );
copy = Helpers::translateTouch( copy, this, touchResponder[touch.id] );
touchResponder[touch.id]->touchMovedOutside( copy );
touchResponder[touch.id]->onTouchMovedOutside.notify(copy);
return touchResponder[touch.id];
}
return touched;
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleTouchUp( ofTouchEventArgs &touch ){
ofTouchEventArgs copy = touch;
fixTouchPosition( touch, copy, NULL );
Container * touched = Container::handleTouchUp( copy );
if( touched != touchResponder[touch.id] && touchResponder[touch.id] != NULL ){
fixTouchPosition( touch, copy, touchResponder[touch.id] );
Container *c = touchResponder[touch.id];
touchResponder[touch.id]->touchUpOutside( copy );
touchResponder[touch.id]->onTouchUpOutside.notify( copy );
c->singleTouchId = -1;
}
touchResponder[touch.id] = NULL;
return touched;
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleTouchDoubleTap( ofTouchEventArgs &touch ){
ofTouchEventArgs copy = touch;
fixTouchPosition( touch, copy, NULL );
return Container::handleTouchDoubleTap( copy );
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleTouchCancelled( ofTouchEventArgs &touch ){
if( touchResponder[touch.id] != NULL ){
touchResponder[touch.id]->touchCanceled( touch );
touchResponder[touch.id]->singleTouchId = -1;
mui::Container * c = touchResponder[touch.id];
touchResponder[touch.id] = NULL;
return c;
}
else{
return NULL;
}
}
//--------------------------------------------------------------
void mui::Root::fixTouchPosition( glm::vec2 &touch, glm::vec2 ©, Container * container ){
copy.x = touch.x/mui::MuiConfig::scaleFactor;
copy.y = touch.y/mui::MuiConfig::scaleFactor;
if( container != NULL ){
ofPoint pos = container->getGlobalPosition();
copy.x -= pos.x;
copy.y -= pos.y;
}
}
//--------------------------------------------------------------
ofRectangle mui::Root::convertNativeToMui( const ofRectangle rect ){
const float s = mui::MuiConfig::scaleFactor;
return ofRectangle(rect.x/s, rect.y/s, rect.width/s, rect.height/s);
}
//--------------------------------------------------------------
ofPoint mui::Root::convertNativeToMui( const ofPoint pt ){
const float s = mui::MuiConfig::scaleFactor;
return ofPoint(pt.x/s, pt.y/s, pt.z/s);
}
//--------------------------------------------------------------
ofRectangle mui::Root::convertMuiToNative( const ofRectangle rect ){
const float s = mui::MuiConfig::scaleFactor;
return ofRectangle(rect.x*s, rect.y*s, rect.width*s, rect.height*s);
}
//--------------------------------------------------------------
ofPoint mui::Root::convertMuiToNative( const ofPoint pt ){
const float s = mui::MuiConfig::scaleFactor;
return ofPoint(pt.x*s, pt.y*s, pt.z*s);
}
//--------------------------------------------------------------
bool mui::Root::becomeTouchResponder( Container * c, ofTouchEventArgs &touch ){
// the trivial case ...
if( c != NULL && c == touchResponder[touch.id] )
return true;
// notify previous owner,
// cancel if it doesn't allow transfering focus
if( touchResponder[touch.id] != NULL ){
if( touchResponder[touch.id]->focusTransferable == false )
return false;
touchResponder[touch.id]->handleTouchCanceled( touch );
touchResponder[touch.id]->singleTouchId = -1;
}
// alright, install new owner
touchResponder[touch.id] = c;
if( touchResponder[touch.id] != NULL ){
touchResponder[touch.id]->singleTouchId = touch.id;
}
return true;
}
bool mui::Root::becomeKeyboardResponder( Container * c ){
this->keyboardResponder = c;
return true;
}
//--------------------------------------------------------------
void mui::Root::safeRemove( Container * c ){
safeRemoveList.push_back( c );
}
//--------------------------------------------------------------
void mui::Root::safeDelete( Container * c ){
safeDeleteList.push_back( c );
}
//--------------------------------------------------------------
void mui::Root::safeRemoveAndDelete( mui::Container *c ){
safeRemoveAndDeleteList.push_back( c );
}
//--------------------------------------------------------------
void mui::Root::removeFromResponders( Container * c ){
if(c == nullptr ) return;
for( int i = 0; i < OF_MAX_TOUCHES; i++ ){
if( touchResponder[i] == c ){
touchResponder[i] = NULL;
}
}
if( keyboardResponder == c ){
keyboardResponder = NULL;
}
hoverResponder.erase(c);
if(c == popupMenu ) popupMenu = nullptr;
// recurse
//for(const auto & child : c->children){
// removeFromResponders(child);
//}
}
void mui::Root::reloadTextures(){
mui::Helpers::clearCaches();
}
//--------------------------------------------------------------
void mui::Root::prepareAnimation( int milliseconds, int type, int direction ){
param = tween::TweenerParam( milliseconds, (short)type, (short)direction );
}
//--------------------------------------------------------------
void mui::Root::runOnUiThread(function<void()> func){
//TBD
}
void mui::Root::setDisplayScaling(float reqScale){
float scale = reqScale == 0? muiGetDefaultDisplayScaling() : reqScale;
mui::MuiConfig::detectRetina = reqScale == 0;
mui::MuiConfig::scaleFactor = scale;
mui::Helpers::getFontStash().pixelDensity = scale;
ofEvents().notifyWindowResized(ofGetWidth(), ofGetHeight());
}
//--------------------------------------------------------------
bool mui::Root::getKeyPressed( int key ){
return ofGetKeyPressed(key);
}
//--------------------------------------------------------------
void mui::Root::animate( float &variable, float targetValue ){
param.addProperty( &variable, targetValue );
}
//--------------------------------------------------------------
void mui::Root::commitAnimation(){
tweener.addTween( param );
}
void mui::Root::handleRemovals(){
vector<Container*> cp = move(safeRemoveList);
for(auto c : cp){
c->remove();
}
cp = move(safeDeleteList);
for(auto c : cp){
c->remove();
}
cp = move(safeRemoveAndDeleteList);
for(auto c : cp){
c->remove();
delete c;
}
safeRemoveList.clear();
safeDeleteList.clear();
safeRemoveAndDeleteList.clear();
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleKeyPressed( ofKeyEventArgs &event ){
// this is a bit awkward, there seems to be a bug in
// glfw that re-sends modifier key when they are released.
// for now, i'm not fixing this. i really shouldn't be, not here.
// resend hover/drag commands, so that we immediately see the effects of changed
// cursor etc. without having to handle all code everywhere.
auto retriggerMouse = [&]() {
// now simulate hover/touch/drag...
bool pressed = ofGetMousePressed(OF_MOUSE_BUTTON_1) || ofGetMousePressed(OF_MOUSE_BUTTON_2) || ofGetMousePressed(OF_MOUSE_BUTTON_3) || ofGetMousePressed(OF_MOUSE_BUTTON_4) || ofGetMousePressed(OF_MOUSE_BUTTON_5) || ofGetMousePressed(OF_MOUSE_BUTTON_6);
if (pressed) {
// dragging...
ofTouchEventArgs args;
args.x = ofGetMouseX();
args.y = ofGetMouseY();
handleTouchMoved(args);
}
else {
// moving
ofMouseEventArgs args;
args.x = ofGetMouseX();
args.y = ofGetMouseY();
handleMouseMoved(args.x, args.y);
}
};
if( getKeyPressed(OF_KEY_ESC) && popupMenu != nullptr){
if (keyboardResponder == nullptr || !keyboardResponder->onKeyPressed.notify(event) || !keyboardResponder->keyPressed(event)) {
safeRemove(popupMenu);
popupMenu = nullptr;
}
retriggerMouse();
return this;
}
if( mui::MuiConfig::enableDebuggingShortcuts && getKeyPressed(MUI_KEY_ACTION) && event.keycode == GLFW_KEY_D ){
mui::MuiConfig::debugDraw ^= true;
retriggerMouse();
return this;
}
if( mui::MuiConfig::enableDebuggingShortcuts && getKeyPressed(OF_KEY_ALT) && event.keycode == OF_KEY_RETURN){
// dump the view hierachy!
mui::Container * active = this->findChildAt( ofGetMouseX()/mui::MuiConfig::scaleFactor - this->x, ofGetMouseY()/mui::MuiConfig::scaleFactor-this->y, true );
cout << "------------------------------------";
cout << "DUMPING VIEW HIERACHY" << endl;
while( active != NULL ){
ofRectangle b = active->getBounds();
stringstream info;
info << "Pos:" << b.x << "," << b.y << " " << b.width << " x " << b.height;
string size = info.str();
cout << "> " << active->name << size << endl;
active = active->parent;
}
cout << "------------------------------------";
retriggerMouse();
return this;
}
if (mui::MuiConfig::debugDraw && getKeyPressed(OF_KEY_ALT) && event.keycode == 'F') {
mui::Container * active = this->findChildAt(muiGetMouseX() - this->x, muiGetMouseY() - this->y, true);
ofTouchEventArgs temp;
if (active) active->requestFocus(temp);
return this;
}
if( mui::MuiConfig::debugDraw && getKeyPressed(OF_KEY_ALT) && event.keycode == 'I' ){
cout << "------------------------------------" << endl;
mui::Container * active = this->findChildAt( muiGetMouseX() - this->x, muiGetMouseY()-this->y, true );
cout << "Set a debug point in " << __FILE__ << ":" << __LINE__ << " to inspect this element" << endl;
cout << "------------------------------------" << endl;
return this;
}
if( mui::MuiConfig::debugDraw && getKeyPressed(OF_KEY_ALT) && event.keycode == 'L' ){
handleLayout();
retriggerMouse();
return this;
}
mui::Container * temp = keyboardResponder;
// for now disable
//if (temp == nullptr) {
// auto pos = muiGetMousePos();
// temp = findChildAt(pos.x, pos.y, true, true);
//}
if( temp != nullptr ){
if( !temp->isVisibleOnScreen()){
temp = nullptr;
retriggerMouse();
return nullptr;
}
else{
while(temp != nullptr && !temp->onKeyPressed.notify(event) && !temp->keyPressed(event)){
temp = temp->parent;
}
retriggerMouse();
return temp;
}
}
// still here? a bit sad...
retriggerMouse();
return nullptr;
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleKeyReleased( ofKeyEventArgs &event ){
if( keyboardResponder != NULL ){
if(keyboardResponder->onKeyReleased.notify(event)) return keyboardResponder;
keyboardResponder->keyReleased(event);
}
// now simulate hover/touch/drag...
bool pressed = ofGetMousePressed(OF_MOUSE_BUTTON_1) || ofGetMousePressed(OF_MOUSE_BUTTON_2) || ofGetMousePressed(OF_MOUSE_BUTTON_3) || ofGetMousePressed(OF_MOUSE_BUTTON_4) || ofGetMousePressed(OF_MOUSE_BUTTON_5) || ofGetMousePressed(OF_MOUSE_BUTTON_6);
if (pressed) {
// dragging...
ofTouchEventArgs args;
args.x = ofGetMouseX();
args.y = ofGetMouseY();
handleTouchMoved(args);
}
else {
// moving
ofMouseEventArgs args;
args.x = ofGetMouseX();
args.y = ofGetMouseY();
handleMouseMoved(args.x, args.y);
}
return keyboardResponder;
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleMouseMoved( float x, float y ){
ofTouchEventArgs args;
args.x = x;
args.y = y;
args.id = 0;
return handleTouchHover(args);
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleMouseDragged( float x, float y, int button ){
ofTouchEventArgs args;
args.x = x;
args.y = y;
args.id = 0;
return handleTouchMoved(args);
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleMousePressed( float x, float y, int button ){
ofTouchEventArgs args;
args.x = x;
args.y = y;
args.id = 0;
uint64_t now = ofGetSystemTimeMicros();
if(now>lastMouseDown && (now-lastMouseDown)/1000<230){
args.type = ofTouchEventArgs::doubleTap;
}
lastMouseDown = now;
return handleTouchDown(args);
}
//--------------------------------------------------------------
mui::Container * mui::Root::handleMouseReleased( float x, float y, int button ){
ofTouchEventArgs args;
args.x = x;
args.y = y;
args.id = 0;
return handleTouchUp(args);
}
void mui::Root::showPopupMenu( mui::Container * c, mui::Container * source, ofVec2f pos, mui::HorizontalAlign horizontalAlign, mui::VerticalAlign verticalAlign ){
mui::Root::showPopupMenu(c, source, pos.x, pos.y, horizontalAlign, verticalAlign );
}
void mui::Root::showPopupMenu( mui::Container * c, mui::Container * source, float x, float y, mui::HorizontalAlign horizontalAlign, mui::VerticalAlign verticalAlign ){
if(popupMenu != nullptr){
popupMenu->visible = false;
popupMenu->remove();
popupMenu = nullptr;
}
if(c == nullptr) return;
c->visible = true;
add(c);
c->handleLayout();
popupMenu = c;
if( source == nullptr ){
popupMenu->x = x;
popupMenu->y = y;
}
else{
ofPoint p = source->getGlobalPosition();
popupMenu->x = p.x + x;
popupMenu->y = p.y + y;
}
switch(horizontalAlign){
case mui::Left: break;
case mui::Right: popupMenu->x -= popupMenu->width; break;
case mui::Center: popupMenu->x -= popupMenu->width/2; break;
}
switch(verticalAlign){
case mui::Top: break;
case mui::Middle: popupMenu->y -= popupMenu->height; break;
case mui::Bottom: popupMenu->y -= popupMenu->height/2; break;
}
popupMenu->x = ofClamp(popupMenu->x, 1, width - popupMenu->width );
popupMenu->y = ofClamp(popupMenu->y, 1, height - popupMenu->height );
}
void mui::Root::removePopup(mui::Container * popup) {
if (this->popupMenu == popup) {
popup->visible = false;
safeRemove(popup);
popup = nullptr;
}
}
void mui::Root::of_setup( ofEventArgs &args ){
//handleSetup();
handleLayout();
}
void mui::Root::of_update( ofEventArgs &args ){
if(mui::MuiConfig::detectRetina){
auto ptr = ofGetWindowPtr();
auto glfw = dynamic_cast<ofAppGLFWWindow*>(ptr);
if(glfw && mui::MuiConfig::scaleFactor != muiGetDefaultDisplayScaling() ){
mui::MuiConfig::scaleFactor = muiGetDefaultDisplayScaling();
mui::Helpers::getFontStash().pixelDensity = mui::MuiConfig::scaleFactor;
cout << "[ofxMightyUI] updated pixel scaling factor to " << mui::MuiConfig::scaleFactor << endl;
}
}
handleUpdate();
}
void mui::Root::of_draw( ofEventArgs &args ){
handleDraw();
}
void mui::Root::of_exit( ofEventArgs &args ){
//handleExit(args);
}
void mui::Root::of_windowResized( ofResizeEventArgs &args ){
//handleWindowResized(args);
if (args.width <= 0 || args.height <= 0) return;
width = args.width/mui::MuiConfig::scaleFactor;
height = args.height/mui::MuiConfig::scaleFactor;
numLayoutFrames = 1;
handleLayout();
}
bool mui::Root::of_keyPressed( ofKeyEventArgs &args ){
return handleKeyPressed(args) != NULL;
}
bool mui::Root::of_keyReleased( ofKeyEventArgs &args ){
return handleKeyReleased(args) != NULL;
}
bool mui::Root::of_mouseMoved( ofMouseEventArgs &args ){
return handleMouseMoved(args.x, args.y) != NULL;
}
bool mui::Root::of_mouseDragged( ofMouseEventArgs &args ){
return handleMouseDragged(args.x, args.y, args.button) != NULL;
}
bool mui::Root::of_mousePressed( ofMouseEventArgs &args ){
return handleMousePressed(args.x, args.y, args.button) != NULL;
}
bool mui::Root::of_mouseReleased( ofMouseEventArgs &args ){
return handleMouseReleased(args.x, args.y, args.button) != NULL;
}
bool mui::Root::of_mouseScrolled( ofMouseEventArgs &args ){
glm::vec2 pos;
fixTouchPosition(args, pos, NULL);
mui::Container * container = (mui::Container*)findChildOfType<mui::ScrollPane>(pos.x, pos.y, true, true);
if( container != NULL ){
container->mouseScroll(args);
container->onMouseScroll.notify(args);
return true;
}
else{
mui::Container * container = findChildAt(pos.x, pos.y, true, true );
if( container != nullptr && container != this ){
container->mouseScroll(args);
container->onMouseScroll.notify(args);
return true;
}
else{
return false;
}
}
}
bool mui::Root::of_touchDown( ofTouchEventArgs &args ){
return handleTouchDown(args) != NULL;
}
bool mui::Root::of_touchUp( ofTouchEventArgs &args ){
return handleTouchUp(args) != NULL;
}
bool mui::Root::of_touchMoved( ofTouchEventArgs &args ){
return handleTouchMoved(args) != NULL;
}
bool mui::Root::of_touchDoubleTap( ofTouchEventArgs &args ){
return handleTouchDoubleTap(args) != NULL;
}
bool mui::Root::of_touchCancelled( ofTouchEventArgs &args ){
return handleTouchCancelled(args) != NULL;
}
void mui::Root::of_messageEvent( ofMessage &args ){
//handleMessageEvent(args);
}
bool mui::Root::of_fileDragEvent( ofDragInfo &args ){
ofDragInfo copy = args;
copy.position.x = args.position.x/mui::MuiConfig::scaleFactor;
copy.position.y = args.position.y/mui::MuiConfig::scaleFactor;
return handleFileDragged(copy);
}
void mui::Root::removePopupIfNecessary( mui::Container * target ){
if(popupMenu != nullptr ){
if(target != nullptr ){
// is the popup somehow a parent of what was clicked?
while(target != nullptr){
if( target == popupMenu ){
return;
}
target = target->parent;
}
}
popupMenu->visible = false;
safeRemove(popupMenu);
popupMenu = nullptr;
}
}
| 30.711353 | 254 | 0.630933 | [
"vector"
] |
102860601d4fb8c70626e7256edb94a34dda018d | 30,820 | cpp | C++ | src/Klondike.cpp | CaesiumFox/Klondike | 977220eea1fa3a0ffb54e5718581c579c3650459 | [
"MIT"
] | 2 | 2019-12-05T05:16:12.000Z | 2020-02-26T00:31:01.000Z | src/Klondike.cpp | CaesiumFox/Klondike | 977220eea1fa3a0ffb54e5718581c579c3650459 | [
"MIT"
] | null | null | null | src/Klondike.cpp | CaesiumFox/Klondike | 977220eea1fa3a0ffb54e5718581c579c3650459 | [
"MIT"
] | 1 | 2019-12-05T05:12:55.000Z | 2019-12-05T05:12:55.000Z | #include "Klondike.h"
Klondike::Klondike() {
srand((uint32_t)time(0));
SDL_Init(SDL_INIT_EVERYTHING);
SDL_DisplayMode DM;
SDL_GetCurrentDisplayMode(0, &DM);
window = SDL_CreateWindow("Klondike", 100, 100, DM.w, DM.h, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN);
SDL_GetWindowSize(window, &WinWidth, &WinHeight);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
//SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD);
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
event = SDL_Event();
storage = new Storage(renderer);
state = GameState::Playing;
selected = { '0', 0 };
foundations_pos = vector<SDL_Rect>(4);
tableau_pos = vector<SDL_Rect>(7);
for(auto &e : layout.foundations)
e = deque<Card>(0);
for (auto& e : layout.tableau)
e = deque<Card>(0);
stock_pos = { (WinWidth / 2 - 464) + 32, 32, 96, 128 };
waste_pos = { (WinWidth / 2 - 464) + 160, 32, 96, 128 };
waste_hitbox = { (WinWidth / 2 - 464) + 160, 32, 160, 128 };
for (int i = 0; i < 4; i++) foundations_pos[i] = { (WinWidth / 2 - 464) + 416 + 128 * i, 32, 96, 128 };
for (int i = 0; i < 7; i++) tableau_pos[i] = { (WinWidth / 2 - 464) + 32 + 128 * i, 192, 96, 128 };
storage->font->Height = 64;
paused_pos = { (WinWidth - storage->font->GetWidth(u"PAUSED"s)) / 2, WinHeight / 2 - 32 };
youwin_pos = { (WinWidth - storage->font->GetWidth(u"YOU WIN!"s)) / 2, WinHeight / 2 - 32 };
scorevalue_pos = { (WinWidth / 2 - 464) + 32, 0 };
timevalue_pos = { (WinWidth / 2 - 464) + 288, 0 };
nowvalue_pos = { WinWidth - 256, WinHeight - 32 };
pb_pos = { 0, 0, 32, 32 };
ngb_pos = { 0, 32, 32, 32 };
udb_pos = {0, 64, 32, 32};
set_pos = {0, 96, 32, 32};
qb_pos = { WinWidth - 32, 0, 32, 32 };
newgame_window_pos = {WinWidth / 2 - 192, WinHeight / 2 - 160, 384, 320};
storage->font->Height = 64;
newgame_label_pos = {
newgame_window_pos.x + (newgame_window_pos.w - storage->font->GetWidth(u"New Game")) / 2,
newgame_window_pos.y + 16
};
newgame_btn1_pos = { newgame_window_pos.x + 64, newgame_window_pos.y + 64, 128, 128 };
newgame_btn3_pos = { newgame_window_pos.x + 192, newgame_window_pos.y + 64, 128, 128 };
newgame_cancel_pos = { newgame_window_pos.x + 128, newgame_window_pos.y + 224, 128, 64 };
storage->font->Height = 32;
newgame_cancel_text_pos = {
newgame_cancel_pos.x + (newgame_cancel_pos.w - storage->font->GetWidth(u"Cancel")) / 2,
newgame_cancel_pos.y + 16
};
settings_window_pos = { WinWidth / 2 - 400, WinHeight / 2 - 300, 800, 600 };
storage->font->Height = 64;
settings_label_pos = {
settings_window_pos.x + (settings_window_pos.w - storage->font->GetWidth(u"Settings")) / 2,
settings_window_pos.y + 16
};
settings_bg_pos = vector<SDL_Rect>(storage->bg_count);
settings_bg_pos[0] = { settings_window_pos.x + 64, settings_window_pos.y + 128, 128, 128 };
settings_bg_pos[1] = { settings_window_pos.x + 256, settings_window_pos.y + 128, 128, 128 };
settings_bg_pos[2] = { settings_window_pos.x + 448, settings_window_pos.y + 128, 128, 128 };
settings_cancel_pos = { settings_window_pos.x + 336, settings_window_pos.y + 504, 128, 64 };
storage->font->Height = 32;
settings_cancel_text_pos = {
settings_cancel_pos.x + (settings_cancel_pos.w - storage->font->GetWidth(u"Cancel")) / 2,
settings_cancel_pos.y + 16
};
final_firework_1 = nullptr;
final_firework_2 = nullptr;
final_firework_3 = nullptr;
final_firework_4 = nullptr;
delay = 0;
running = true;
win = false;
gamemode = GameMode::OneCard;
shown = FormShown::GamePlay;
LoadFile();
Loop();
}
Klondike::~Klondike() {
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
storage->~Storage();
layout.stock.~deque();
layout.waste.~deque();
for (auto& e : layout.foundations)
e.~deque();
for (auto& e : layout.tableau)
e.~deque();
SDL_Quit();
}
void Klondike::Loop() {
while (running) {
Input();
Update();
Render();
}
}
void Klondike::Render() {
SDL_RenderClear(renderer);
RenderEverywhereBelow();
switch (shown) {
case FormShown::GamePlay:
switch (state) {
case GameState::Playing:
RenderPlaying();
break;
case GameState::Paused:
RenderPaused();
break;
case GameState::Finished:
RenderFinished();
break;
}
break;
case FormShown::NewGameDialog:
RenderNewGame();
break;
case FormShown::SettingsDialog:
RenderSettings();
break;
}
RenderEverywhereAbove();
SDL_RenderPresent(renderer);
}
void Klondike::RenderEverywhereBelow() {
SDL_RenderCopy(renderer, storage->backgrounds[storage->settingBackground], NULL, NULL);
}
void Klondike::RenderPlaying() {
DrawStock();
DrawWaste();
DrawFoundations();
DrawFannedPiles();
SDL_RenderCopy(renderer, storage->undobutton_img, NULL, &udb_pos);
SDL_RenderCopy(renderer, storage->pausebutton_img, NULL, &pb_pos);
SDL_RenderCopy(renderer, storage->newgamebutton_img, NULL, &ngb_pos);
}
void Klondike::RenderPaused() {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &stock_pos);
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &waste_pos);
for (int i = 0; i < 4; i++)
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &foundations_pos[i]);
for (int i = 0; i < 7; i++)
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &tableau_pos[i]);
SDL_RenderCopy(renderer, storage->undobutton_img, NULL, &udb_pos);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 64);
SDL_RenderFillRect(renderer, NULL);
SDL_RenderCopy(renderer, storage->playbutton_img, NULL, &pb_pos);
SDL_RenderCopy(renderer, storage->newgamebutton_img, NULL, &ngb_pos);
SDL_RenderCopy(renderer, storage->setbutton_img, NULL, &set_pos);
storage->font->Height = 64;
storage->font->DrawString("PAUSED", renderer, paused_pos.x, paused_pos.y);
}
void Klondike::RenderFinished() {
DrawStock();
DrawWaste();
DrawFoundations();
DrawFannedPiles();
SDL_RenderCopy(renderer, storage->pausebutton_img, NULL, &pb_pos);
SDL_RenderCopy(renderer, storage->undobutton_img, NULL, &udb_pos);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 64);
SDL_RenderFillRect(renderer, NULL);
SDL_RenderCopy(renderer, storage->newgamebutton_img, NULL, &ngb_pos);
if (win) {
if (final_firework_1) final_firework_1->Draw(renderer, storage);
if (final_firework_2) final_firework_2->Draw(renderer, storage);
if (final_firework_3) final_firework_3->Draw(renderer, storage);
if (final_firework_4) final_firework_4->Draw(renderer, storage);
storage->font->Height = 64;
storage->font->DrawString("YOU WIN!", renderer, youwin_pos.x, youwin_pos.y);
}
}
void Klondike::RenderNewGame() {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &stock_pos);
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &waste_pos);
for (int i = 0; i < 4; i++)
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &foundations_pos[i]);
for (int i = 0; i < 7; i++)
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &tableau_pos[i]);
SDL_RenderCopy(renderer, storage->undobutton_img, NULL, &udb_pos);
SDL_RenderCopy(renderer, storage->pausebutton_img, NULL, &pb_pos);
SDL_RenderCopy(renderer, storage->newgamebutton_img, NULL, &ngb_pos);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 64);
SDL_RenderFillRect(renderer, NULL);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 127);
SDL_RenderFillRect(renderer, &newgame_window_pos);
storage->font->Height = 64;
storage->font->DrawString("New Game", renderer, newgame_label_pos.x, newgame_label_pos.y);
SDL_RenderCopy(renderer, storage->new_one_image, NULL, &newgame_btn1_pos);
SDL_RenderCopy(renderer, storage->new_three_image, NULL, &newgame_btn3_pos);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &newgame_cancel_pos);
storage->font->Height = 32;
storage->font->Color = { 0, 0, 0, 255 };
storage->font->DrawString("Cancel", renderer, newgame_cancel_text_pos.x, newgame_cancel_text_pos.y);
storage->font->Color = { 255, 255, 255, 255 };
}
void Klondike::RenderSettings() {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &stock_pos);
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &waste_pos);
for (int i = 0; i < 4; i++)
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &foundations_pos[i]);
for (int i = 0; i < 7; i++)
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &tableau_pos[i]);
SDL_RenderCopy(renderer, storage->undobutton_img, NULL, &udb_pos);
SDL_RenderCopy(renderer, storage->pausebutton_img, NULL, &pb_pos);
SDL_RenderCopy(renderer, storage->newgamebutton_img, NULL, &ngb_pos);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 64);
SDL_RenderFillRect(renderer, NULL);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 127);
SDL_RenderFillRect(renderer, &settings_window_pos);
storage->font->Height = 64;
storage->font->DrawString("Settings", renderer, settings_label_pos.x, settings_label_pos.y);
for (int i = 0; i < storage->bg_count; i++) {
SDL_RenderCopy(renderer, storage->backgrounds[i], NULL, &settings_bg_pos[i]);
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &settings_cancel_pos);
storage->font->Height = 32;
storage->font->Color = { 0, 0, 0, 255 };
storage->font->DrawString("Cancel", renderer, settings_cancel_text_pos.x, settings_cancel_text_pos.y);
storage->font->Color = { 255, 255, 255, 255 };
}
void Klondike::RenderEverywhereAbove() {
storage->font->Height = 32;
storage->font->DrawString("Score: "s + to_string(layout.score), renderer, scorevalue_pos.x, scorevalue_pos.y);
storage->font->DrawString("Time: "s + ToolKit::GetStrTime(delay + ToolKit::TimeCut(time_points)), renderer, timevalue_pos.x, timevalue_pos.y);
storage->font->DrawString("Now: "s + ToolKit::GetCurrentStrTime(), renderer, nowvalue_pos.x, nowvalue_pos.y);
SDL_RenderCopy(renderer, storage->quitbutton_img, NULL, &qb_pos);
}
void Klondike::Input() {
while (SDL_PollEvent(&event)) {
InputEverywhere();
switch (shown) {
case FormShown::GamePlay:
switch (state) {
case GameState::Playing:
InputPlaying();
break;
case GameState::Paused:
InputPaused();
break;
case GameState::Finished:
InputFinished();
break;
default:
break;
}
break;
case FormShown::NewGameDialog:
InputNewGame();
break;
case FormShown::SettingsDialog:
InputSettings();
break;
default:
break;
}
}
}
void Klondike::InputEverywhere() {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point m = { event.button.x, event.button.y };
if (SDL_PointInRect(&m, &qb_pos)) {
running = false;
SaveFile();
return;
}
}
break;
case SDL_QUIT:
running = false;
SaveFile();
break;
default:
break;
}
}
void Klondike::InputPlaying() {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point m = { event.button.x, event.button.y };
if (SDL_PointInRect(&m, &pb_pos)) {
state = GameState::Paused;
time_points.push_back(time(NULL));
return;
}
if (SDL_PointInRect(&m, &ngb_pos)) {
selected = { '0', 0 };
state = GameState::Paused;
shown = FormShown::NewGameDialog;
time_points.push_back(time(NULL));
return;
}
if (SDL_PointInRect(&m, &udb_pos)) {
selected = { '0', 0 };
Undo();
return;
}
if (SDL_PointInRect(&m, &stock_pos)) {
selected = { '0', 0 };
if (layout.stock.empty()) {
// don't forget:
// stock.top = stock.back
// waste.top = waste.front
layout.stock = layout.waste;
layout.waste.clear();
for (auto& e : layout.stock) {
e.Turn();
}
if (gamemode == GameMode::OneCard) {
layout.score -= 100;
if (layout.score < 0) layout.score = 0;
}
}
else {
for (int i = 0; i < (gamemode == GameMode::OneCard ? 1 : 3) && !layout.stock.empty(); i++) {
layout.waste.push_front(layout.stock.back());
layout.waste.front().Turn();
layout.stock.pop_back();
}
}
Record();
return;
}
if (SDL_PointInRect(&m, &waste_hitbox)) {
if (!layout.waste.empty()) {
selected.where = 'w';
}
else {
selected.where = '0';
}
return;
}
// maybe foundations ?
for (int f = 0; f < 4; f++) {
if (SDL_PointInRect(&m, &foundations_pos[f])) {
if (selected.where == 'w') {
if (PossibleToFoundation(f, &layout.waste.front())) {
layout.foundations[f].push_front(layout.waste.front());
layout.waste.pop_front();
layout.score += 10;
selected.where = '0';
Record();
return;
}
else if (!layout.foundations[f].empty()) {
selected.where = 'a' + f;
}
else {
selected.where = '0';
}
}
else if (selected.where >= '1' && selected.where <= '7' && selected.pos == 0) {
if (PossibleToFoundation(f, &layout.tableau[int(selected.where - '1')].front())) {
layout.foundations[f].push_front(layout.tableau[int(selected.where - '1')].front());
layout.tableau[int(selected.where - '1')].pop_front();
layout.score += 10;
selected.where = '0';
Record();
return;
}
else if (!layout.foundations[f].empty()) {
selected.where = 'a' + f;
}
else {
selected.where = '0';
}
}
else if (selected.where >= 'a' && selected.where <= 'd') {
if (f != int(selected.where - 'a'))
layout.foundations[f].swap(layout.foundations[int(selected.where - 'a')]);
selected.where = '0';
Record();
return;
}
else if (!layout.foundations[f].empty()) {
selected.where = 'a' + f;
}
else {
selected.where = '0';
}
return;
}
}
// maybe tableau ?
int pile = WhichPile(m.x);
if (pile != -1) {
int index = WhichCardInPile(pile, m.y);
if (index == 0 || index == -2) {
if (selected.where == 'w') {
if (PossibleToPile(pile, &layout.waste.front())) {
layout.tableau[pile].push_front(layout.waste.front());
layout.waste.pop_front();
layout.score += 5;
selected.where = '0';
Record();
}
else if (!layout.tableau[pile].empty()) {
selected = { char('1' + pile), index };
}
else {
selected.where = '0';
}
}
else if (selected.where >= 'a' && selected.where <= 'd') {
if (PossibleToPile(pile, &layout.foundations[int(selected.where - 'a')].front())) {
layout.tableau[pile].push_front(layout.foundations[int(selected.where - 'a')].front());
layout.foundations[int(selected.where - 'a')].pop_front();
layout.score -= 15;
if (layout.score < 0) layout.score = 0;
selected.where = '0';
Record();
}
else if (!layout.tableau[pile].empty()) {
selected = { char('1' + pile), index };
}
else {
selected.where = '0';
}
}
else if (selected.where >= '1' && selected.where <= '7') {
if (PossibleToPile(pile, &layout.tableau[int(selected.where - '1')][selected.pos]) && layout.tableau[int(selected.where - '1')][selected.pos].IsOpened()) {
for (int i = selected.pos; i >= 0; i--)
layout.tableau[pile].push_front(layout.tableau[int(selected.where - '1')][i]);
for (int i = selected.pos; i >= 0; i--)
layout.tableau[int(selected.where - '1')].pop_front();
selected.where = '0';
Record();
}
else if (!layout.tableau[pile].empty()) {
selected = { char('1' + pile), index };
}
else {
selected.where = '0';
}
}
else if (!layout.tableau[pile].empty()) {
selected = { char('1' + pile), index };
}
else {
selected.where = '0';
}
return;
}
else if (index != -1) {
selected = { char('1' + pile), index };
return;
}
}
// TODO
selected = { '0', 0 };
}
if (event.button.button == SDL_BUTTON_RIGHT) {
bool builded = Build();
if(builded) Record();
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.scancode) {
case SDL_Scancode::SDL_SCANCODE_ESCAPE:
state = GameState::Paused;
time_points.push_back(time(NULL));
break;
default:
break;
}
break;
default:
break;
}
}
void Klondike::InputPaused() {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point m = { event.button.x, event.button.y };
if (SDL_PointInRect(&m, &pb_pos)) {
state = GameState::Playing;
time_points.push_back(time(NULL));
return;
}
if (SDL_PointInRect(&m, &ngb_pos)) {
selected = { '0', 0 };
shown = FormShown::NewGameDialog;
return;
}
if (SDL_PointInRect(&m, &set_pos)) {
shown = FormShown::SettingsDialog;
return;
}
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.scancode) {
case SDL_Scancode::SDL_SCANCODE_ESCAPE:
state = GameState::Playing;
time_points.push_back(time(NULL));
break;
default:
break;
}
break;
default:
break;
}
}
void Klondike::InputFinished() {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point m = { event.button.x, event.button.y };
if (SDL_PointInRect(&m, &ngb_pos)) {
selected = { '0', 0 };
shown = FormShown::NewGameDialog;
return;
}
}
break;
default:
break;
}
}
void Klondike::InputNewGame() {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point m = { event.button.x, event.button.y };
if (SDL_PointInRect(&m, &newgame_btn1_pos)) {
selected = { '0', 0 };
shown = FormShown::GamePlay;
state = GameState::Playing;
NewGame(GameMode::OneCard);
time_points.push_back(time(NULL));
return;
}
if (SDL_PointInRect(&m, &newgame_btn3_pos)) {
selected = { '0', 0 };
shown = FormShown::GamePlay;
state = GameState::Playing;
NewGame(GameMode::ThreeCards);
time_points.push_back(time(NULL));
return;
}
if (SDL_PointInRect(&m, &newgame_cancel_pos)) {
shown = FormShown::GamePlay;
if(state != GameState::Finished) time_points.push_back(time(NULL));
return;
}
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.scancode) {
case SDL_Scancode::SDL_SCANCODE_ESCAPE:
shown = FormShown::GamePlay;
time_points.push_back(time(NULL));
break;
default:
break;
}
break;
default:
break;
}
}
void Klondike::InputSettings() {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point m = { event.button.x, event.button.y };
for (int i = 0; i < storage->bg_count; i++) {
if (SDL_PointInRect(&m, &settings_bg_pos[i])) {
storage->settingBackground = i;
shown = FormShown::GamePlay;
state = GameState::Paused;
return;
}
}
if (SDL_PointInRect(&m, &settings_cancel_pos)) {
shown = FormShown::GamePlay;
state = GameState::Paused;
return;
}
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.scancode) {
case SDL_Scancode::SDL_SCANCODE_ESCAPE:
shown = FormShown::GamePlay;
state = GameState::Paused;
break;
default:
break;
}
break;
default:
break;
}
}
void Klondike::Update() {
UpdateEverywhere();
switch (shown) {
case FormShown::GamePlay:
switch (state) {
case GameState::Playing:
UpdatePlaying();
break;
case GameState::Paused:
UpdatePaused();
break;
case GameState::Finished:
UpdateFinished();
break;
}
case FormShown::NewGameDialog:
UpdateNewGame();
break;
case FormShown::SettingsDialog:
UpdateSettings();
break;
}
}
void Klondike::UpdateEverywhere() {}
void Klondike::UpdatePlaying() {
for (int p = 0; p < 7; p++) {
if (!layout.tableau[p].empty()) {
if (!layout.tableau[p].front().IsOpened()) {
layout.score += 5;
layout.tableau[p].front().Open();
}
}
}
if (!layout.foundations[0].empty() && !layout.foundations[1].empty() && !layout.foundations[2].empty() && !layout.foundations[3].empty())
win =
layout.foundations[0].front().GetRank() == CardRank::King &&
layout.foundations[1].front().GetRank() == CardRank::King &&
layout.foundations[2].front().GetRank() == CardRank::King &&
layout.foundations[3].front().GetRank() == CardRank::King;
if (win) {
state = GameState::Finished; time_points.push_back(time(NULL));
}
}
void Klondike::UpdatePaused() {}
void Klondike::UpdateFinished() {
if (win) {
if (final_firework_1 == nullptr) {
final_firework_1 = new Firework(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 7);
}
else {
final_firework_1->Update();
if (final_firework_1->Faded()) {
final_firework_1->Recharge(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 7);
}
}
if (final_firework_2 == nullptr) {
if(final_firework_1->GetVelocity() < 5)
final_firework_2 = new Firework(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 7);
}
else{
final_firework_2->Update();
if (final_firework_2->Faded()) {
final_firework_2->Recharge(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 7);
}
}
if (final_firework_3 == nullptr) {
if (final_firework_1->GetVelocity() < 10)
final_firework_3 = new Firework(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 3);
}
else {
final_firework_3->Update();
if (final_firework_3->Faded()) {
final_firework_3->Recharge(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 3);
}
}
if (final_firework_4 == nullptr) {
if (final_firework_1->GetVelocity() < 15)
final_firework_4 = new Firework(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 3);
}
else {
final_firework_4->Update();
if (final_firework_4->Faded()) {
final_firework_4->Recharge(complex<double>(double(rand() % WinWidth), double(rand() % WinHeight)), rand() % 10 + 10, rand() % 3);
}
}
}
}
void Klondike::UpdateNewGame() {}
void Klondike::UpdateSettings() {}
void Klondike::DrawStock() {
if (layout.stock.empty()) {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &stock_pos);
}
else {
layout.stock.back().Draw(renderer, storage, stock_pos.x, stock_pos.y);
}
}
void Klondike::DrawWaste() {
if (gamemode == GameMode::OneCard) {
if (layout.waste.empty()) {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &waste_pos);
}
else {
if (selected.where == 'w') {
SDL_Rect bound = { waste_pos.x - 4, waste_pos.y - 4, waste_pos.w + 8, waste_pos.h + 8 };
SDL_RenderCopy(renderer, storage->select_bound, NULL, &bound);
}
layout.waste[0].Draw(renderer, storage, waste_pos.x, waste_pos.y);
}
}
else {
if (layout.waste.empty()) {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &waste_pos);
}
else if (layout.waste.size() == 1) {
if (selected.where == 'w') {
SDL_Rect bound = { waste_pos.x - 4, waste_pos.y - 4, waste_pos.w + 8, waste_pos.h + 8 };
SDL_RenderCopy(renderer, storage->select_bound, NULL, &bound);
}
layout.waste[0].Draw(renderer, storage, waste_pos.x, waste_pos.y);
}
else if (layout.waste.size() == 2) {
layout.waste[1].Draw(renderer, storage, waste_pos.x, waste_pos.y);
if (selected.where == 'w') {
SDL_Rect bound = { waste_pos.x - 4 + 32, waste_pos.y - 4, waste_pos.w + 8, waste_pos.h + 8 };
SDL_RenderCopy(renderer, storage->select_bound, NULL, &bound);
}
layout.waste[0].Draw(renderer, storage, waste_pos.x + 32, waste_pos.y);
}
else {
layout.waste[2].Draw(renderer, storage, waste_pos.x, waste_pos.y);
layout.waste[1].Draw(renderer, storage, waste_pos.x + 32, waste_pos.y);
if (selected.where == 'w') {
SDL_Rect bound = { waste_pos.x - 4 + 64, waste_pos.y - 4, waste_pos.w + 8, waste_pos.h + 8 };
SDL_RenderCopy(renderer, storage->select_bound, NULL, &bound);
}
layout.waste[0].Draw(renderer, storage, waste_pos.x + 64, waste_pos.y);
}
}
}
void Klondike::DrawFoundations() {
for (int i = 0; i < 4; i++) {
if (layout.foundations[i].empty()) {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &foundations_pos[i]);
}
else {
if (selected.where == 'a' + i) {
SDL_Rect bound = { foundations_pos[i].x - 4, foundations_pos[i].y - 4, foundations_pos[i].w + 8, foundations_pos[i].h + 8 };
SDL_RenderCopy(renderer, storage->select_bound, NULL, &bound);
}
layout.foundations[i].front().Draw(renderer, storage, foundations_pos[i].x, foundations_pos[i].y);
}
}
}
void Klondike::DrawFannedPiles() {
for (int i = 0; i < 7; i++) {
if (layout.tableau[i].empty()) {
SDL_RenderCopy(renderer, storage->empty_place_image, NULL, &tableau_pos[i]);
}
else {
int offset = 0;
for (int j = layout.tableau[i].size() - 1; j >= 0; j--) {
if (selected.where == '1' + i && selected.pos == j) {
SDL_Rect bound = { tableau_pos[i].x - 4, tableau_pos[i].y - 4 + offset, tableau_pos[i].w + 8, tableau_pos[i].h + 8 };
SDL_RenderCopy(renderer, storage->select_bound, NULL, &bound);
}
layout.tableau[i][j].Draw(renderer, storage, tableau_pos[i].x, tableau_pos[i].y + offset);
offset += (layout.tableau[i][j].IsOpened() ? (CountOpenedInPile(i) <= 10 ? 32 : 20) : 2);
}
}
}
}
void Klondike::NewGame(GameMode gm = GameMode::OneCard) {
Reset();
gamemode = gm;
// init deck
for (int suit = 0; suit < 4; suit++) {
for (int rank = 0; rank < 13; rank++) {
layout.stock.push_back(Card(CardSuit(suit), CardRank(rank), false));
}
}
// shuffle
for (int i = 0; i < 1000; i++) {
int a = rand() % 52, b = rand() % 52;
auto temp = layout.stock[a];
layout.stock[a] = layout.stock[b];
layout.stock[b] = temp;
}
// packing
for (int i = 0; i < 7; i++) {
for (int p = i; p < 7; p++) {
layout.tableau[p].push_front(layout.stock.back());
layout.stock.pop_back();
}
}
for (int p = 0; p < 7; p++) {
layout.tableau[p].front().Turn();
}
Record();
}
bool Klondike::Build() {
bool flag = true;
bool res = false;
while (flag) {
flag = false;
for (int s = 0; s < 4; s++) {
if(!layout.waste.empty())
if (PossibleToFoundation(s, &layout.waste.front())) {
flag = true;
layout.foundations[s].push_front(layout.waste.front());
layout.waste.pop_front();
layout.score += 10;
}
for (int p = 0; p < 7; p++) {
if (!layout.tableau[p].empty())
if (PossibleToFoundation(s, &layout.tableau[p].front())) {
flag = true;
layout.foundations[s].push_front(layout.tableau[p].front());
layout.foundations[s].front().Open();
layout.tableau[p].pop_front();
layout.score += 10;
}
}
}
for (int p = 0; p < 7; p++) {
if (!layout.tableau[p].empty()) {
if (!layout.tableau[p].front().IsOpened()) {
layout.score += 5;
layout.tableau[p].front().Open();
}
}
}
if (flag) res = true;
}
return res;
}
void Klondike::Undo() {
if (history.size() > 1) {
layout.Clear();
history.back().Clear();
history.pop_back();
layout = history.back();
}
}
void Klondike::Record() {
history.push_back(layout);
}
void Klondike::Reset() {
win = false;
delay = 0;
time_points.clear();
layout.Clear();
for (auto& l : history)
l.Clear();
history.clear();
}
void Klondike::SaveFile() {
ofstream file("save.record", ios::binary);
auto transform = [](Card * c) -> char { return char(c->GetRank()) | (char(c->GetSuit()) << 4) | (char(c->IsOpened()) << 6); };
for (auto& e : layout.stock) {
file << transform(&e);
}
file << char(0xFF);
for (auto& e : layout.waste) {
file << transform(&e);
}
file << char(0xFF);
for (auto &f : layout.foundations) {
for (auto& e : f) {
file << transform(&e);
}
file << char(0xFF);
}
for (auto& p : layout.tableau) {
for (auto& e : p) {
file << transform(&e);
}
file << char(0xFF);
}
ToolKit::Encode4B(file, *(unsigned long *)(&layout.score));
time_t new_delay = delay + ToolKit::TimeCut(time_points);
ToolKit::Encode8B(file, *(unsigned long long*)(&new_delay));
file << (gamemode == GameMode::OneCard ? '1' : '3');
file.close();
}
void Klondike::LoadFile() {
ifstream file("save.record", ios::binary);
if(file.fail()) {
NewGame();
time_points.push_back(time(NULL));
return;
}
Reset();
auto transform = [](char c) -> Card { return Card(CardSuit((c >> 4) & 3), CardRank(c & 15), bool((c >> 6) & 1)); };
char c;
while (1) {
file >> c;
if (c == char(0xFF)) break;
layout.stock.push_back(transform(c));
}
while (1) {
file >> c;
if (c == char(0xFF)) break;
layout.waste.push_back(transform(c));
}
for (auto& f : layout.foundations) {
while (1) {
file >> c;
if (c == char(0xFF)) break;
f.push_back(transform(c));
}
}
for (auto& p : layout.tableau) {
while (1) {
file >> c;
if (c == char(0xFF)) break;
p.push_back(transform(c));
}
}
layout.score = ToolKit::Decode_u32_LE(file);
delay = ToolKit::Decode_u64_LE(file);
char gmc;
file.get(gmc);
gamemode = (gmc == '1' ? GameMode::OneCard : GameMode::ThreeCards);
file.close();
Record();
time_points.push_back(time(NULL));
}
bool Klondike::PossibleToFoundation(int index, Card* c) {
if (layout.foundations[index].empty())
return c->GetRank() == CardRank::Ace;
if (layout.foundations[index].front().GetRank() == CardRank::King)
return false;
return
(layout.foundations[index].front().GetSuit() == c->GetSuit()) &&
(CardRank(int(layout.foundations[index].front().GetRank()) + 1) == c->GetRank());
}
bool Klondike::PossibleToPile(int index, Card* c) {
if (layout.tableau[index].empty())
return c->GetRank() == CardRank::King;
if (layout.tableau[index].front().GetRank() == CardRank::Ace)
return false;
return
((int(layout.tableau[index].front().GetSuit()) + int(c->GetSuit())) % 2 == 1) &&
(CardRank(int(layout.tableau[index].front().GetRank()) - 1) == c->GetRank());
}
int Klondike::WhichPile(int x) {
for (int p = 0; p < 7; p++) {
if (x >= (WinWidth / 2 - 464) + p * 128 + 32 && x < (WinWidth / 2 - 464) + (p + 1) * 128)
return p;
}
return -1;
}
int Klondike::WhichCardInPile(int index, int y) {
if (layout.tableau[index].empty())
return -2; // special for king
int offset = 192;
for (int i = layout.tableau[index].size() - 1; i >= 0; i--) {
if (y >= offset && y < offset + (i == 0 ? 128 : (layout.tableau[index][i].IsOpened() ? (CountOpenedInPile(index) <= 10 ? 32 : 20) : 2)))
return i;
offset += (layout.tableau[index][i].IsOpened() ? (CountOpenedInPile(index) <= 10 ? 32 : 20) : 2);
}
return -1;
}
int Klondike::CountOpenedInPile(int index) {
int count = 0;
for (auto& e : layout.tableau[index])
if (e.IsOpened()) count++;
return count;
} | 30.912738 | 161 | 0.640136 | [
"render",
"vector",
"transform"
] |
1028662b6963f34468fe019f51b41a45fddfd60d | 86,141 | cpp | C++ | src/drivers/m62.cpp | tt-arcade/mame4all-pi | b1479cacfa616fc0dea4ad0f9b19a679a04867cf | [
"Unlicense"
] | 33 | 2015-08-10T11:13:47.000Z | 2021-08-30T10:00:46.000Z | src/drivers/m62.cpp | tt-arcade/mame4all-pi | b1479cacfa616fc0dea4ad0f9b19a679a04867cf | [
"Unlicense"
] | 13 | 2015-08-25T03:53:08.000Z | 2022-03-30T18:02:35.000Z | src/drivers/m62.cpp | tt-arcade/mame4all-pi | b1479cacfa616fc0dea4ad0f9b19a679a04867cf | [
"Unlicense"
] | 40 | 2015-08-25T05:09:21.000Z | 2022-02-08T05:02:30.000Z | #include "../vidhrdw/m62.cpp"
/****************************************************************************
Irem "M62" system
There's two crystals on Kid Kiki. 24.00 MHz and 3.579545 MHz for sound
TODO:
- Kid Niki is missing the drums
**************************************************************************/
#include "driver.h"
#include "sndhrdw/irem.h"
#include "vidhrdw/generic.h"
void irem_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void battroad_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void spelunk2_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
int ldrun_vh_start( void );
int kidniki_vh_start( void );
int spelunkr_vh_start( void );
WRITE_HANDLER( irem_flipscreen_w );
WRITE_HANDLER( kungfum_scroll_low_w );
WRITE_HANDLER( kungfum_scroll_high_w );
WRITE_HANDLER( ldrun3_vscroll_w );
WRITE_HANDLER( ldrun4_hscroll_w );
WRITE_HANDLER( irem_background_hscroll_w );
WRITE_HANDLER( irem_background_vscroll_w );
WRITE_HANDLER( battroad_scroll_w );
WRITE_HANDLER( kidniki_text_vscroll_w );
WRITE_HANDLER( kidniki_background_bank_w );
WRITE_HANDLER( spelunkr_palbank_w );
WRITE_HANDLER( spelunk2_gfxport_w );
void kungfum_vh_screenrefresh(struct osd_bitmap *bitmap,int fullrefresh);
void battroad_vh_screenrefresh(struct osd_bitmap *bitmap,int fullrefresh);
void ldrun_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void ldrun4_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void lotlot_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void kidniki_vh_screenrefresh(struct osd_bitmap *bitmap,int fullrefresh);
void spelunkr_vh_screenrefresh(struct osd_bitmap *bitmap,int fullrefresh);
void spelunk2_vh_screenrefresh(struct osd_bitmap *bitmap,int fullrefresh);
extern unsigned char *irem_textram;
extern size_t irem_textram_size;
/* Lode Runner 2 seems to have a simple protection on the bank switching */
/* circuitry. It writes data to ports 0x80 and 0x81, then reads port 0x80 */
/* a variable number of times (discarding the result) and finally retrieves */
/* data from the bankswitched ROM area. */
/* Since the data written to 0x80 is always the level number, I just use */
/* that to select the ROM. The only exception I make is a special case used in */
/* service mode to test the ROMs. */
static int ldrun2_bankswap;
READ_HANDLER( ldrun2_bankswitch_r )
{
if (ldrun2_bankswap)
{
unsigned char *RAM = memory_region(REGION_CPU1);
ldrun2_bankswap--;
/* swap to bank #1 on second read */
if (ldrun2_bankswap == 0)
cpu_setbank(1,&RAM[0x12000]);
}
return 0;
}
WRITE_HANDLER( ldrun2_bankswitch_w )
{
int bankaddress;
static int bankcontrol[2];
int banks[30] =
{
0,0,0,0,0,1,0,1,0,0,
0,1,1,1,1,1,0,0,0,0,
1,0,1,1,1,1,1,1,1,1
};
unsigned char *RAM = memory_region(REGION_CPU1);
bankcontrol[offset] = data;
if (offset == 0)
{
if (data < 1 || data > 30)
{
//logerror("unknown bank select %02x\n",data);
return;
}
bankaddress = 0x10000 + (banks[data-1] * 0x2000);
cpu_setbank(1,&RAM[bankaddress]);
}
else
{
if (bankcontrol[0] == 0x01 && data == 0x0d)
/* special case for service mode */
ldrun2_bankswap = 2;
else ldrun2_bankswap = 0;
}
}
/* Lode Runner 3 has, it seems, a poor man's protection consisting of a PAL */
/* (I think; it's included in the ROM set) which is read at certain times, */
/* and the game crashes if ti doesn't match the expected values. */
READ_HANDLER( ldrun3_prot_5_r )
{
return 5;
}
READ_HANDLER( ldrun3_prot_7_r )
{
return 7;
}
WRITE_HANDLER( ldrun4_bankswitch_w )
{
int bankaddress;
unsigned char *RAM = memory_region(REGION_CPU1);
bankaddress = 0x10000 + ((data & 0x01) * 0x4000);
cpu_setbank(1,&RAM[bankaddress]);
}
static WRITE_HANDLER( kidniki_bankswitch_w )
{
int bankaddress;
unsigned char *RAM = memory_region(REGION_CPU1);
bankaddress = 0x10000 + (data & 0x0f) * 0x2000;
cpu_setbank(1,&RAM[bankaddress]);
}
#define battroad_bankswitch_w kidniki_bankswitch_w
static WRITE_HANDLER( spelunkr_bankswitch_w )
{
int bankaddress;
unsigned char *RAM = memory_region(REGION_CPU1);
bankaddress = 0x10000 + (data & 0x03) * 0x2000;
cpu_setbank(1,&RAM[bankaddress]);
}
WRITE_HANDLER( spelunk2_bankswitch_w )
{
unsigned char *RAM = memory_region(REGION_CPU1);
cpu_setbank(1,&RAM[0x20000 + 0x1000 * ((data & 0xc0)>>6)]);
cpu_setbank(2,&RAM[0x10000 + 0x0400 * (data & 0x3c)]);
}
static struct MemoryWriteAddress kungfum_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0xa000, 0xa000, kungfum_scroll_low_w },
{ 0xb000, 0xb000, kungfum_scroll_high_w },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
/* Kung Fu Master is the only game in this driver to have separated (but */
/* contiguous) videoram and colorram. They are interleaved in all the others. */
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress battroad_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0xa000, 0xbfff, MRA_BANK1 },
{ 0xc800, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress battroad_writemem[] =
{
{ 0x0000, 0xbfff, MWA_ROM },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xc800, 0xcfff, MWA_RAM, &irem_textram, &irem_textram_size },
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress ldrun_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0xd000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress ldrun_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress ldrun2_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0x9fff, MRA_BANK1 },
{ 0xd000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress ldrun2_writemem[] =
{
{ 0x0000, 0x9fff, MWA_ROM },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress ldrun3_readmem[] =
{
{ 0x0000, 0xbfff, MRA_ROM },
{ 0xc800, 0xc800, ldrun3_prot_5_r },
{ 0xcc00, 0xcc00, ldrun3_prot_7_r },
{ 0xcfff, 0xcfff, ldrun3_prot_7_r },
{ 0xd000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress ldrun3_writemem[] =
{
{ 0x0000, 0xbfff, MWA_ROM },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress ldrun4_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xbfff, MRA_BANK1 },
{ 0xd000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress ldrun4_writemem[] =
{
{ 0x0000, 0xbfff, MWA_ROM },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xc800, 0xc800, ldrun4_bankswitch_w },
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress lotlot_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0xa000, 0xafff, MRA_RAM },
{ 0xd000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress lotlot_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0xa000, 0xafff, MWA_RAM, &irem_textram, &irem_textram_size },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xd000, 0xdfff, videoram_w, &videoram, &videoram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress kidniki_readmem[] = {
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0x9fff, MRA_BANK1 },
{ 0xa000, 0xafff, MRA_RAM },
{ 0xd000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress kidniki_writemem[] = {
{ 0x0000, 0x9fff, MWA_ROM },
{ 0xa000, 0xafff, videoram_w, &videoram, &videoram_size },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xd000, 0xdfff, MWA_RAM, &irem_textram, &irem_textram_size },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress spelunkr_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0x9fff, MRA_BANK1 },
{ 0xa000, 0xbfff, MRA_RAM },
{ 0xc800, 0xcfff, MRA_RAM },
{ 0xe000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress spelunkr_writemem[] =
{
{ 0x0000, 0x9fff, MWA_ROM },
{ 0xa000, 0xbfff, videoram_w, &videoram, &videoram_size },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xc800, 0xcfff, MWA_RAM, &irem_textram, &irem_textram_size },
{ 0xd000, 0xd001, irem_background_vscroll_w },
{ 0xd002, 0xd003, irem_background_hscroll_w },
{ 0xd004, 0xd004, spelunkr_bankswitch_w },
{ 0xd005, 0xd005, spelunkr_palbank_w },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress spelunk2_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0x8fff, MRA_BANK1 },
{ 0x9000, 0x9fff, MRA_BANK2 },
{ 0xa000, 0xbfff, MRA_RAM },
{ 0xc800, 0xcfff, MRA_RAM },
{ 0xe000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress spelunk2_writemem[] =
{
{ 0x0000, 0x9fff, MWA_ROM },
{ 0xa000, 0xbfff, videoram_w, &videoram, &videoram_size },
{ 0xc000, 0xc0ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xc800, 0xcfff, MWA_RAM, &irem_textram, &irem_textram_size },
{ 0xd000, 0xd002, spelunk2_gfxport_w },
{ 0xd003, 0xd003, spelunk2_bankswitch_w },
{ 0xe000, 0xefff, MWA_RAM },
{ -1 } /* end of table */
};
static struct IOReadPort ldrun_readport[] =
{
{ 0x00, 0x00, input_port_0_r }, /* coin */
{ 0x01, 0x01, input_port_1_r }, /* player 1 control */
{ 0x02, 0x02, input_port_2_r }, /* player 2 control */
{ 0x03, 0x03, input_port_3_r }, /* DSW 1 */
{ 0x04, 0x04, input_port_4_r }, /* DSW 2 */
{ -1 } /* end of table */
};
static struct IOWritePort battroad_writeport[] =
{
{ 0x00, 0x00, irem_sound_cmd_w },
{ 0x01, 0x01, irem_flipscreen_w }, /* + coin counters */
{ 0x80, 0x82, battroad_scroll_w },
{ 0x83, 0x83, battroad_bankswitch_w },
{ -1 } /* end of table */
};
static struct IOWritePort ldrun_writeport[] =
{
{ 0x00, 0x00, irem_sound_cmd_w },
{ 0x01, 0x01, irem_flipscreen_w }, /* + coin counters */
{ -1 } /* end of table */
};
static struct IOReadPort ldrun2_readport[] =
{
{ 0x00, 0x00, input_port_0_r }, /* coin */
{ 0x01, 0x01, input_port_1_r }, /* player 1 control */
{ 0x02, 0x02, input_port_2_r }, /* player 2 control */
{ 0x03, 0x03, input_port_3_r }, /* DSW 1 */
{ 0x04, 0x04, input_port_4_r }, /* DSW 2 */
{ 0x80, 0x80, ldrun2_bankswitch_r },
{ -1 } /* end of table */
};
static struct IOWritePort ldrun2_writeport[] =
{
{ 0x00, 0x00, irem_sound_cmd_w },
{ 0x01, 0x01, irem_flipscreen_w }, /* + coin counters */
{ 0x80, 0x81, ldrun2_bankswitch_w },
{ -1 } /* end of table */
};
static struct IOWritePort ldrun3_writeport[] =
{
{ 0x00, 0x00, irem_sound_cmd_w },
{ 0x01, 0x01, irem_flipscreen_w }, /* + coin counters */
{ 0x80, 0x80, ldrun3_vscroll_w },
/* 0x81 used too, don't know what for */
{ -1 } /* end of table */
};
static struct IOWritePort ldrun4_writeport[] =
{
{ 0x00, 0x00, irem_sound_cmd_w },
{ 0x01, 0x01, irem_flipscreen_w }, /* + coin counters */
{ 0x82, 0x83, ldrun4_hscroll_w },
{ -1 } /* end of table */
};
static struct IOWritePort kidniki_writeport[] =
{
{ 0x00, 0x00, irem_sound_cmd_w },
{ 0x01, 0x01, irem_flipscreen_w }, /* + coin counters */
{ 0x80, 0x81, irem_background_hscroll_w },
{ 0x82, 0x83, kidniki_text_vscroll_w },
{ 0x84, 0x84, kidniki_background_bank_w },
{ 0x85, 0x85, kidniki_bankswitch_w },
{ -1 } /* end of table */
};
#define IN0_PORT \
/* Start 1 & 2 also restarts and freezes the game with stop mode on \
and are used in test mode to enter and esc the various tests */ \
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) \
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 ) \
/* service coin must be active for 19 frames to be consistently recognized */ \
PORT_BIT_IMPULSE( 0x04, IP_ACTIVE_LOW, IPT_SERVICE1, 19 ) \
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 ) \
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
#define IN1_PORT \
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY ) \
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY ) \
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) \
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) \
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */ \
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) \
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */ \
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 )
#define IN2_PORT \
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL ) \
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL ) \
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL ) \
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL ) \
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN2 ) \
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL ) \
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */ \
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
#define COINAGE_DSW \
/* TODO: support the different settings which happen in Coin Mode 2 */ \
PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coinage ) ) /* mapped on coin mode 1 */ \
PORT_DIPSETTING( 0x90, DEF_STR( 7C_1C ) ) \
PORT_DIPSETTING( 0xa0, DEF_STR( 6C_1C ) ) \
PORT_DIPSETTING( 0xb0, DEF_STR( 5C_1C ) ) \
PORT_DIPSETTING( 0xc0, DEF_STR( 4C_1C ) ) \
PORT_DIPSETTING( 0xd0, DEF_STR( 3C_1C ) ) \
PORT_DIPSETTING( 0xe0, DEF_STR( 2C_1C ) ) \
PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) ) \
PORT_DIPSETTING( 0x70, DEF_STR( 1C_2C ) ) \
PORT_DIPSETTING( 0x60, DEF_STR( 1C_3C ) ) \
PORT_DIPSETTING( 0x50, DEF_STR( 1C_4C ) ) \
PORT_DIPSETTING( 0x40, DEF_STR( 1C_5C ) ) \
PORT_DIPSETTING( 0x30, DEF_STR( 1C_6C ) ) \
PORT_DIPSETTING( 0x20, DEF_STR( 1C_7C ) ) \
PORT_DIPSETTING( 0x10, DEF_STR( 1C_8C ) ) \
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) \
/* setting 0x80 give 1 Coin/1 Credit */
#define COINAGE2_DSW \
/* TODO: support the different settings which happen in Coin Mode 2 */ \
PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coinage ) ) /* mapped on coin mode 1 */ \
PORT_DIPSETTING( 0xa0, DEF_STR( 6C_1C ) ) \
PORT_DIPSETTING( 0xb0, DEF_STR( 5C_1C ) ) \
PORT_DIPSETTING( 0xc0, DEF_STR( 4C_1C ) ) \
PORT_DIPSETTING( 0xd0, DEF_STR( 3C_1C ) ) \
PORT_DIPSETTING( 0x10, DEF_STR( 8C_3C ) ) \
PORT_DIPSETTING( 0xe0, DEF_STR( 2C_1C ) ) \
PORT_DIPSETTING( 0x20, DEF_STR( 5C_3C ) ) \
PORT_DIPSETTING( 0x30, DEF_STR( 3C_2C ) ) \
PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) ) \
PORT_DIPSETTING( 0x40, DEF_STR( 2C_3C ) ) \
PORT_DIPSETTING( 0x90, DEF_STR( 1C_2C ) ) \
PORT_DIPSETTING( 0x80, DEF_STR( 1C_3C ) ) \
PORT_DIPSETTING( 0x70, DEF_STR( 1C_4C ) ) \
PORT_DIPSETTING( 0x60, DEF_STR( 1C_5C ) ) \
PORT_DIPSETTING( 0x50, DEF_STR( 1C_6C ) ) \
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) \
INPUT_PORTS_START( kungfum )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x01, "Easy" )
PORT_DIPSETTING( 0x00, "Hard" )
PORT_DIPNAME( 0x02, 0x02, "Energy Loss" )
PORT_DIPSETTING( 0x02, "Slow" )
PORT_DIPSETTING( 0x00, "Fast" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
/* In slowmo mode, press 2 to slow game speed */
PORT_BITX ( 0x08, 0x08, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Slow Motion Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In freeze mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Freeze", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In level selection mode, press 1 to select and 2 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Level Selection Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( battroad )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x03, 0x03, "Fuel Decrease" )
PORT_DIPSETTING( 0x03, "Slow" )
PORT_DIPSETTING( 0x02, "Medium" )
PORT_DIPSETTING( 0x01, "Fast" )
PORT_DIPSETTING( 0x00, "Fastest" )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x04, "Easy" )
PORT_DIPSETTING( 0x00, "Hard" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
COINAGE_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In stop mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Stop Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( ldrun )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x03, 0x03, "Timer" )
PORT_DIPSETTING( 0x03, "Slow" )
PORT_DIPSETTING( 0x02, "Medium" )
PORT_DIPSETTING( 0x01, "Fast" )
PORT_DIPSETTING( 0x00, "Fastest" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In stop mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Stop Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In level selection mode, press 1 to select and 2 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Level Selection Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( ldrun2 )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x01, 0x01, "Timer" )
PORT_DIPSETTING( 0x01, "Slow" )
PORT_DIPSETTING( 0x00, "Fast" )
PORT_DIPNAME( 0x02, 0x02, "Game Speed" )
PORT_DIPSETTING( 0x00, "Low" )
PORT_DIPSETTING( 0x02, "High" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In freeze mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Freeze", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In level selection mode, press 1 to select and 2 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Level Selection Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( ldrun3 )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x01, 0x01, "Timer" )
PORT_DIPSETTING( 0x01, "Slow" )
PORT_DIPSETTING( 0x00, "Fast" )
PORT_DIPNAME( 0x02, 0x02, "Game Speed" )
PORT_DIPSETTING( 0x00, "Low" )
PORT_DIPSETTING( 0x02, "High" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In stop mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Stop Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In level selection mode, press 1 to select and 2 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Level Selection Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( ldrun4 )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x01, 0x01, "Timer" )
PORT_DIPSETTING( 0x01, "Slow" )
PORT_DIPSETTING( 0x00, "Fast" )
PORT_DIPNAME( 0x02, 0x02, "2 Players Game" )
PORT_DIPSETTING( 0x00, "1 Credit" )
PORT_DIPSETTING( 0x02, "2 Credits" )
PORT_DIPNAME( 0x0c, 0x0c, "1 Player Lives" )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, "2 Players Lives" )
PORT_DIPSETTING( 0x02, "5" )
PORT_DIPSETTING( 0x00, "6" )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x10, "Allow 2 Players Game" )
PORT_DIPSETTING( 0x00, DEF_STR( No ) )
PORT_DIPSETTING( 0x10, DEF_STR( Yes ) )
/* In level selection mode, press 1 to select and 2 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Level Selection Mode", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode (must set 2P game to No)", KEYCODE_F2, IP_JOY_NONE )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
INPUT_PORTS_END
INPUT_PORTS_START( lotlot )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x03, 0x03, "Speed" )
PORT_DIPSETTING( 0x03, "Very Slow" )
PORT_DIPSETTING( 0x02, "Slow" )
PORT_DIPSETTING( 0x01, "Fast" )
PORT_DIPSETTING( 0x00, "Very Fast" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "1" )
PORT_DIPSETTING( 0x04, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x00, "4" )
COINAGE2_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In freeze mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Freeze", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( kidniki )
PORT_START
IN0_PORT
PORT_START
IN1_PORT
PORT_START
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x02, "2" )
PORT_DIPSETTING( 0x03, "3" )
PORT_DIPSETTING( 0x01, "4" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x04, "Normal" )
PORT_DIPSETTING( 0x00, "Hard" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x08, "50000" )
PORT_DIPSETTING( 0x00, "80000" )
COINAGE2_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x08, "Game Repeats" )
PORT_DIPSETTING( 0x08, DEF_STR( No ) )
PORT_DIPSETTING( 0x00, DEF_STR( Yes ) )
PORT_DIPNAME( 0x10, 0x10, "Allow Continue" )
PORT_DIPSETTING( 0x00, DEF_STR( No ) )
PORT_DIPSETTING( 0x10, DEF_STR( Yes ) )
/* In freeze mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Freeze", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( spelunkr )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x03, 0x03, "Energy Decrease" )
PORT_DIPSETTING( 0x03, "Slow" )
PORT_DIPSETTING( 0x02, "Medium" )
PORT_DIPSETTING( 0x01, "Fast" )
PORT_DIPSETTING( 0x00, "Fastest" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE2_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x00, "Allow Continue" )
PORT_DIPSETTING( 0x08, DEF_STR( No ) )
PORT_DIPSETTING( 0x00, DEF_STR( Yes ) )
/* In teleport mode, keep 1 pressed and press up or down to move the character */
PORT_BITX ( 0x10, 0x10, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Teleport", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In freeze mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Freeze", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
INPUT_PORTS_START( spelunk2 )
PORT_START /* IN0 */
IN0_PORT
PORT_START /* IN1 */
IN1_PORT
PORT_START /* IN2 */
IN2_PORT
PORT_START /* DSW1 */
PORT_DIPNAME( 0x03, 0x03, "Energy Decrease" )
PORT_DIPSETTING( 0x03, "Slow" )
PORT_DIPSETTING( 0x02, "Medium" )
PORT_DIPSETTING( 0x01, "Fast" )
PORT_DIPSETTING( 0x00, "Fastest" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x08, "2" )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x04, "4" )
PORT_DIPSETTING( 0x00, "5" )
COINAGE2_DSW
PORT_START /* DSW2 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) )
/* This activates a different coin mode. Look at the dip switch setting schematic */
PORT_DIPNAME( 0x04, 0x04, "Coin Mode" )
PORT_DIPSETTING( 0x04, "Mode 1" )
PORT_DIPSETTING( 0x00, "Mode 2" )
PORT_DIPNAME( 0x08, 0x08, "Allow Continue" )
PORT_DIPSETTING( 0x00, DEF_STR( No ) )
PORT_DIPSETTING( 0x08, DEF_STR( Yes ) )
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
/* In freeze mode, press 2 to stop and 1 to restart */
PORT_BITX ( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Freeze", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
#define TILELAYOUT(NUM) static struct GfxLayout tilelayout_##NUM = \
{ \
8,8, /* 8*8 characters */ \
NUM, /* NUM characters */ \
3, /* 3 bits per pixel */ \
{ 2*NUM*8*8, NUM*8*8, 0 }, \
{ 0, 1, 2, 3, 4, 5, 6, 7 }, \
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, \
8*8 /* every char takes 8 consecutive bytes */ \
}
TILELAYOUT(1024);
TILELAYOUT(2048);
TILELAYOUT(4096);
static struct GfxLayout battroad_charlayout =
{
8,8, /* 8*8 characters */
1024, /* number of characters */
2, /* 2 bits per pixel */
{ 0, 1024*8*8 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
8*8 /* every char takes 8 consecutive bytes */
};
static struct GfxLayout lotlot_charlayout =
{
12,10, /* character size */
256, /* number of characters */
3, /* bits per pixel */
{ 0, 256*32*8, 2*256*32*8 },
{ 0, 1, 2, 3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8 },
32*8 /* every char takes 32 consecutive bytes */
};
static struct GfxLayout kidniki_charlayout =
{
12,8, /* character size */
1024, /* number of characters */
3, /* bits per pixel */
{ 0, 0x4000*8, 2*0x4000*8 },
{ 0, 1, 2, 3, 64+0,64+1,64+2,64+3,64+4,64+5,64+6,64+7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
16*8 /* every char takes 16 consecutive bytes */
};
static struct GfxLayout spelunk2_charlayout =
{
12,8, /* character size */
512, /* number of characters */
3, /* bits per pixel */
{ 0, 0x4000*8, 2*0x4000*8 },
{
0,1,2,3,
0x2000*8+0,0x2000*8+1,0x2000*8+2,0x2000*8+3,
0x2000*8+4,0x2000*8+5,0x2000*8+6,0x2000*8+7
},
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
8*8 /* every char takes 8 consecutive bytes */
};
#define SPRITELAYOUT(NUM) static struct GfxLayout spritelayout_##NUM = \
{ \
16,16, /* 16*16 sprites */ \
NUM, /* NUM sprites */ \
3, /* 3 bits per pixel */ \
{ 2*NUM*32*8, NUM*32*8, 0 }, \
{ 0, 1, 2, 3, 4, 5, 6, 7, \
16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7 }, \
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, \
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, \
32*8 /* every sprite takes 32 consecutive bytes */ \
}
SPRITELAYOUT(256);
SPRITELAYOUT(512);
SPRITELAYOUT(1024);
SPRITELAYOUT(2048);
static struct GfxDecodeInfo kungfum_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_1024, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_1024, 32*8, 32 }, /* use colors 256-511 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo battroad_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_1024, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_512, 256, 32 }, /* use colors 256-511 */
{ REGION_GFX3, 0, &battroad_charlayout, 512, 32 }, /* use colors 512-543 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo ldrun_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_1024, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_256, 256, 32 }, /* use colors 256-511 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo ldrun2_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_1024, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_512, 256, 32 }, /* use colors 256-511 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo ldrun3_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_2048, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_512, 256, 32 }, /* use colors 256-511 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo ldrun4_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_2048, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_1024, 256, 32 }, /* use colors 256-511 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo lotlot_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &lotlot_charlayout, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_256, 256, 32 }, /* use colors 256-511 */
{ REGION_GFX3, 0, &lotlot_charlayout, 512, 32 }, /* use colors 512-767 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo kidniki_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_4096, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_2048, 256, 32 }, /* use colors 256-511 */
{ REGION_GFX3, 0, &kidniki_charlayout, 0, 32 }, /* use colors 0-255 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo spelunkr_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_4096, 0, 32 }, /* use colors 0-255 */
{ REGION_GFX2, 0, &spritelayout_1024, 256, 32 }, /* use colors 256-511 */
{ REGION_GFX3, 0, &spelunk2_charlayout, 0, 32 }, /* use colors 0-255 */
{ -1 } /* end of array */
};
static struct GfxDecodeInfo spelunk2_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_4096, 0, 64 }, /* use colors 0-511 */
{ REGION_GFX2, 0, &spritelayout_1024, 512, 32 }, /* use colors 512-767 */
{ REGION_GFX3, 0, &spelunk2_charlayout, 0, 64 }, /* use colors 0-511 */
{ -1 } /* end of array */
};
#define MACHINE_DRIVER(GAMENAME,READPORT,VISIBLEMINX,VISIBLEMAXX,COLORS,CONVERTCOLOR) \
\
static struct MachineDriver machine_driver_##GAMENAME = \
{ \
/* basic machine hardware */ \
{ \
{ \
CPU_Z80, \
4000000, /* 4 Mhz (?) */ \
GAMENAME##_readmem,GAMENAME##_writemem,READPORT##_readport,GAMENAME##_writeport, \
interrupt,1 \
}, \
IREM_AUDIO_CPU \
}, \
55, 1790, /* frames per second and vblank duration from the Lode Runner manual */ \
1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */ \
0, \
\
/* video hardware */ \
64*8, 32*8, { VISIBLEMINX, VISIBLEMAXX, 0*8, 32*8-1 }, \
GAMENAME##_gfxdecodeinfo, \
COLORS, COLORS, \
CONVERTCOLOR##_vh_convert_color_prom, \
\
VIDEO_TYPE_RASTER, \
0, \
GAMENAME##_vh_start, \
generic_vh_stop, \
GAMENAME##_vh_screenrefresh, \
\
/* sound hardware */ \
0,0,0,0, \
{ \
IREM_AUDIO \
} \
}
#define kungfum_readmem ldrun_readmem
#define kungfum_writeport ldrun_writeport
#define lotlot_writeport ldrun_writeport
#define spelunkr_writeport ldrun_writeport
#define spelunk2_writeport ldrun_writeport
#define kungfum_vh_start kidniki_vh_start
#define battroad_vh_start kidniki_vh_start
#define ldrun2_vh_start ldrun_vh_start
#define ldrun3_vh_start ldrun_vh_start
#define ldrun4_vh_start ldrun_vh_start
#define lotlot_vh_start ldrun_vh_start
#define spelunk2_vh_start spelunkr_vh_start
#define ldrun2_vh_screenrefresh ldrun_vh_screenrefresh
#define ldrun3_vh_screenrefresh ldrun_vh_screenrefresh
MACHINE_DRIVER(kungfum, ldrun, 16*8, (64-16)*8-1, 512,irem);
MACHINE_DRIVER(battroad, ldrun, 16*8, (64-16)*8-1, 544,battroad);
MACHINE_DRIVER(ldrun, ldrun, 8*8, (64-8)*8-1, 512,irem);
MACHINE_DRIVER(ldrun2, ldrun2, 8*8, (64-8)*8-1, 512,irem);
MACHINE_DRIVER(ldrun3, ldrun, 8*8, (64-8)*8-1, 512,irem);
MACHINE_DRIVER(ldrun4, ldrun, 8*8, (64-8)*8-1, 512,irem);
MACHINE_DRIVER(lotlot, ldrun, 8*8, (64-8)*8-1, 768,irem);
MACHINE_DRIVER(kidniki, ldrun, 8*8, (64-8)*8-1, 512,irem);
MACHINE_DRIVER(spelunkr, ldrun, 8*8, (64-8)*8-1, 512,irem);
MACHINE_DRIVER(spelunk2, ldrun, 8*8, (64-8)*8-1, 768,spelunk2);
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( kungfum )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "a-4e-c.bin", 0x0000, 0x4000, 0xb6e2d083 )
ROM_LOAD( "a-4d-c.bin", 0x4000, 0x4000, 0x7532918e )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "a-3e-.bin", 0xa000, 0x2000, 0x58e87ab0 ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3f-.bin", 0xc000, 0x2000, 0xc81e31ea ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3h-.bin", 0xe000, 0x2000, 0xd99fb995 )
ROM_REGION( 0x06000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g-4c-a.bin", 0x00000, 0x2000, 0x6b2cc9c8 ) /* characters */
ROM_LOAD( "g-4d-a.bin", 0x02000, 0x2000, 0xc648f558 )
ROM_LOAD( "g-4e-a.bin", 0x04000, 0x2000, 0xfbe9276e )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "b-4k-.bin", 0x00000, 0x2000, 0x16fb5150 ) /* sprites */
ROM_LOAD( "b-4f-.bin", 0x02000, 0x2000, 0x67745a33 )
ROM_LOAD( "b-4l-.bin", 0x04000, 0x2000, 0xbd1c2261 )
ROM_LOAD( "b-4h-.bin", 0x06000, 0x2000, 0x8ac5ed3a )
ROM_LOAD( "b-3n-.bin", 0x08000, 0x2000, 0x28a213aa )
ROM_LOAD( "b-4n-.bin", 0x0a000, 0x2000, 0xd5228df3 )
ROM_LOAD( "b-4m-.bin", 0x0c000, 0x2000, 0xb16de4f2 )
ROM_LOAD( "b-3m-.bin", 0x0e000, 0x2000, 0xeba0d66b )
ROM_LOAD( "b-4c-.bin", 0x10000, 0x2000, 0x01298885 )
ROM_LOAD( "b-4e-.bin", 0x12000, 0x2000, 0xc77b87d4 )
ROM_LOAD( "b-4d-.bin", 0x14000, 0x2000, 0x6a70615f )
ROM_LOAD( "b-4a-.bin", 0x16000, 0x2000, 0x6189d626 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "g-1j-.bin", 0x0000, 0x0100, 0x668e6bca ) /* character palette red component */
ROM_LOAD( "b-1m-.bin", 0x0100, 0x0100, 0x76c05a9c ) /* sprite palette red component */
ROM_LOAD( "g-1f-.bin", 0x0200, 0x0100, 0x964b6495 ) /* character palette green component */
ROM_LOAD( "b-1n-.bin", 0x0300, 0x0100, 0x23f06b99 ) /* sprite palette green component */
ROM_LOAD( "g-1h-.bin", 0x0400, 0x0100, 0x550563e1 ) /* character palette blue component */
ROM_LOAD( "b-1l-.bin", 0x0500, 0x0100, 0x35e45021 ) /* sprite palette blue component */
ROM_LOAD( "b-5f-.bin", 0x0600, 0x0020, 0x7a601c3d ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "b-6f-.bin", 0x0620, 0x0100, 0x82c20d12 ) /* video timing? - same as battroad */
ROM_END
ROM_START( kungfud )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "a-4e-d", 0x0000, 0x4000, 0xfc330a46 )
ROM_LOAD( "a-4d-d", 0x4000, 0x4000, 0x1b2fd32f )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "a-3e-.bin", 0xa000, 0x2000, 0x58e87ab0 ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3f-.bin", 0xc000, 0x2000, 0xc81e31ea ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3h-.bin", 0xe000, 0x2000, 0xd99fb995 )
ROM_REGION( 0x06000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g-4c-a.bin", 0x00000, 0x2000, 0x6b2cc9c8 ) /* characters */
ROM_LOAD( "g-4d-a.bin", 0x02000, 0x2000, 0xc648f558 )
ROM_LOAD( "g-4e-a.bin", 0x04000, 0x2000, 0xfbe9276e )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "b-4k-.bin", 0x00000, 0x2000, 0x16fb5150 ) /* sprites */
ROM_LOAD( "b-4f-.bin", 0x02000, 0x2000, 0x67745a33 )
ROM_LOAD( "b-4l-.bin", 0x04000, 0x2000, 0xbd1c2261 )
ROM_LOAD( "b-4h-.bin", 0x06000, 0x2000, 0x8ac5ed3a )
ROM_LOAD( "b-3n-.bin", 0x08000, 0x2000, 0x28a213aa )
ROM_LOAD( "b-4n-.bin", 0x0a000, 0x2000, 0xd5228df3 )
ROM_LOAD( "b-4m-.bin", 0x0c000, 0x2000, 0xb16de4f2 )
ROM_LOAD( "b-3m-.bin", 0x0e000, 0x2000, 0xeba0d66b )
ROM_LOAD( "b-4c-.bin", 0x10000, 0x2000, 0x01298885 )
ROM_LOAD( "b-4e-.bin", 0x12000, 0x2000, 0xc77b87d4 )
ROM_LOAD( "b-4d-.bin", 0x14000, 0x2000, 0x6a70615f )
ROM_LOAD( "b-4a-.bin", 0x16000, 0x2000, 0x6189d626 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "g-1j-.bin", 0x0000, 0x0100, 0x668e6bca ) /* character palette red component */
ROM_LOAD( "b-1m-.bin", 0x0100, 0x0100, 0x76c05a9c ) /* sprite palette red component */
ROM_LOAD( "g-1f-.bin", 0x0200, 0x0100, 0x964b6495 ) /* character palette green component */
ROM_LOAD( "b-1n-.bin", 0x0300, 0x0100, 0x23f06b99 ) /* sprite palette green component */
ROM_LOAD( "g-1h-.bin", 0x0400, 0x0100, 0x550563e1 ) /* character palette blue component */
ROM_LOAD( "b-1l-.bin", 0x0500, 0x0100, 0x35e45021 ) /* sprite palette blue component */
ROM_LOAD( "b-5f-.bin", 0x0600, 0x0020, 0x7a601c3d ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "b-6f-.bin", 0x0620, 0x0100, 0x82c20d12 ) /* video timing? - same as battroad */
ROM_END
ROM_START( spartanx )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "a-4e-c-j.bin", 0x0000, 0x4000, 0x32a0a9a6 )
ROM_LOAD( "a-4d-c-j.bin", 0x4000, 0x4000, 0x3173ea78 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "a-3e-.bin", 0xa000, 0x2000, 0x58e87ab0 ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3f-.bin", 0xc000, 0x2000, 0xc81e31ea ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3h-.bin", 0xe000, 0x2000, 0xd99fb995 )
ROM_REGION( 0x06000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g-4c-a-j.bin", 0x00000, 0x2000, 0x8af9c5a6 ) /* characters */
ROM_LOAD( "g-4d-a-j.bin", 0x02000, 0x2000, 0xb8300c72 )
ROM_LOAD( "g-4e-a-j.bin", 0x04000, 0x2000, 0xb50429cd )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "b-4k-.bin", 0x00000, 0x2000, 0x16fb5150 ) /* sprites */
ROM_LOAD( "b-4f-.bin", 0x02000, 0x2000, 0x67745a33 )
ROM_LOAD( "b-4l-.bin", 0x04000, 0x2000, 0xbd1c2261 )
ROM_LOAD( "b-4h-.bin", 0x06000, 0x2000, 0x8ac5ed3a )
ROM_LOAD( "b-3n-.bin", 0x08000, 0x2000, 0x28a213aa )
ROM_LOAD( "b-4n-.bin", 0x0a000, 0x2000, 0xd5228df3 )
ROM_LOAD( "b-4m-.bin", 0x0c000, 0x2000, 0xb16de4f2 )
ROM_LOAD( "b-3m-.bin", 0x0e000, 0x2000, 0xeba0d66b )
ROM_LOAD( "b-4c-.bin", 0x10000, 0x2000, 0x01298885 )
ROM_LOAD( "b-4e-.bin", 0x12000, 0x2000, 0xc77b87d4 )
ROM_LOAD( "b-4d-.bin", 0x14000, 0x2000, 0x6a70615f )
ROM_LOAD( "b-4a-.bin", 0x16000, 0x2000, 0x6189d626 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "g-1j-.bin", 0x0000, 0x0100, 0x668e6bca ) /* character palette red component */
ROM_LOAD( "b-1m-.bin", 0x0100, 0x0100, 0x76c05a9c ) /* sprite palette red component */
ROM_LOAD( "g-1f-.bin", 0x0200, 0x0100, 0x964b6495 ) /* character palette green component */
ROM_LOAD( "b-1n-.bin", 0x0300, 0x0100, 0x23f06b99 ) /* sprite palette green component */
ROM_LOAD( "g-1h-.bin", 0x0400, 0x0100, 0x550563e1 ) /* character palette blue component */
ROM_LOAD( "b-1l-.bin", 0x0500, 0x0100, 0x35e45021 ) /* sprite palette blue component */
ROM_LOAD( "b-5f-.bin", 0x0600, 0x0020, 0x7a601c3d ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "b-6f-.bin", 0x0620, 0x0100, 0x82c20d12 ) /* video timing? - same as battroad */
ROM_END
ROM_START( kungfub )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "c5.5h", 0x0000, 0x4000, 0x5d8e791d )
ROM_LOAD( "c4.5k", 0x4000, 0x4000, 0x4000e2b8 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "a-3e-.bin", 0xa000, 0x2000, 0x58e87ab0 ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3f-.bin", 0xc000, 0x2000, 0xc81e31ea ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3h-.bin", 0xe000, 0x2000, 0xd99fb995 )
ROM_REGION( 0x06000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g-4c-a.bin", 0x00000, 0x2000, 0x6b2cc9c8 ) /* characters */
ROM_LOAD( "g-4d-a.bin", 0x02000, 0x2000, 0xc648f558 )
ROM_LOAD( "g-4e-a.bin", 0x04000, 0x2000, 0xfbe9276e )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "b-4k-.bin", 0x00000, 0x2000, 0x16fb5150 ) /* sprites */
ROM_LOAD( "b-4f-.bin", 0x02000, 0x2000, 0x67745a33 )
ROM_LOAD( "b-4l-.bin", 0x04000, 0x2000, 0xbd1c2261 )
ROM_LOAD( "b-4h-.bin", 0x06000, 0x2000, 0x8ac5ed3a )
ROM_LOAD( "b-3n-.bin", 0x08000, 0x2000, 0x28a213aa )
ROM_LOAD( "b-4n-.bin", 0x0a000, 0x2000, 0xd5228df3 )
ROM_LOAD( "b-4m-.bin", 0x0c000, 0x2000, 0xb16de4f2 )
ROM_LOAD( "b-3m-.bin", 0x0e000, 0x2000, 0xeba0d66b )
ROM_LOAD( "b-4c-.bin", 0x10000, 0x2000, 0x01298885 )
ROM_LOAD( "b-4e-.bin", 0x12000, 0x2000, 0xc77b87d4 )
ROM_LOAD( "b-4d-.bin", 0x14000, 0x2000, 0x6a70615f )
ROM_LOAD( "b-4a-.bin", 0x16000, 0x2000, 0x6189d626 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "g-1j-.bin", 0x0000, 0x0100, 0x668e6bca ) /* character palette red component */
ROM_LOAD( "b-1m-.bin", 0x0100, 0x0100, 0x76c05a9c ) /* sprite palette red component */
ROM_LOAD( "g-1f-.bin", 0x0200, 0x0100, 0x964b6495 ) /* character palette green component */
ROM_LOAD( "b-1n-.bin", 0x0300, 0x0100, 0x23f06b99 ) /* sprite palette green component */
ROM_LOAD( "g-1h-.bin", 0x0400, 0x0100, 0x550563e1 ) /* character palette blue component */
ROM_LOAD( "b-1l-.bin", 0x0500, 0x0100, 0x35e45021 ) /* sprite palette blue component */
ROM_LOAD( "b-5f-.bin", 0x0600, 0x0020, 0x7a601c3d ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "b-6f-.bin", 0x0620, 0x0100, 0x82c20d12 ) /* video timing? - same as battroad */
ROM_END
ROM_START( kungfub2 )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "kf4", 0x0000, 0x4000, 0x3f65313f )
ROM_LOAD( "kf5", 0x4000, 0x4000, 0x9ea325f3 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "a-3e-.bin", 0xa000, 0x2000, 0x58e87ab0 ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3f-.bin", 0xc000, 0x2000, 0xc81e31ea ) /* samples (ADPCM 4-bit) */
ROM_LOAD( "a-3h-.bin", 0xe000, 0x2000, 0xd99fb995 )
ROM_REGION( 0x06000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "g-4c-a.bin", 0x00000, 0x2000, 0x6b2cc9c8 ) /* characters */
ROM_LOAD( "g-4d-a.bin", 0x02000, 0x2000, 0xc648f558 )
ROM_LOAD( "g-4e-a.bin", 0x04000, 0x2000, 0xfbe9276e )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "b-4k-.bin", 0x00000, 0x2000, 0x16fb5150 ) /* sprites */
ROM_LOAD( "b-4f-.bin", 0x02000, 0x2000, 0x67745a33 )
ROM_LOAD( "b-4l-.bin", 0x04000, 0x2000, 0xbd1c2261 )
ROM_LOAD( "b-4h-.bin", 0x06000, 0x2000, 0x8ac5ed3a )
ROM_LOAD( "b-3n-.bin", 0x08000, 0x2000, 0x28a213aa )
ROM_LOAD( "b-4n-.bin", 0x0a000, 0x2000, 0xd5228df3 )
ROM_LOAD( "b-4m-.bin", 0x0c000, 0x2000, 0xb16de4f2 )
ROM_LOAD( "b-3m-.bin", 0x0e000, 0x2000, 0xeba0d66b )
ROM_LOAD( "b-4c-.bin", 0x10000, 0x2000, 0x01298885 )
ROM_LOAD( "b-4e-.bin", 0x12000, 0x2000, 0xc77b87d4 )
ROM_LOAD( "b-4d-.bin", 0x14000, 0x2000, 0x6a70615f )
ROM_LOAD( "b-4a-.bin", 0x16000, 0x2000, 0x6189d626 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "g-1j-.bin", 0x0000, 0x0100, 0x668e6bca ) /* character palette red component */
ROM_LOAD( "b-1m-.bin", 0x0100, 0x0100, 0x76c05a9c ) /* sprite palette red component */
ROM_LOAD( "g-1f-.bin", 0x0200, 0x0100, 0x964b6495 ) /* character palette green component */
ROM_LOAD( "b-1n-.bin", 0x0300, 0x0100, 0x23f06b99 ) /* sprite palette green component */
ROM_LOAD( "g-1h-.bin", 0x0400, 0x0100, 0x550563e1 ) /* character palette blue component */
ROM_LOAD( "b-1l-.bin", 0x0500, 0x0100, 0x35e45021 ) /* sprite palette blue component */
ROM_LOAD( "b-5f-.bin", 0x0600, 0x0020, 0x7a601c3d ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "b-6f-.bin", 0x0620, 0x0100, 0x82c20d12 ) /* video timing? - same as battroad */
ROM_END
ROM_START( battroad )
ROM_REGION( 0x1e000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "br-a-4e.b", 0x00000, 0x2000, 0x9bf14768 )
ROM_LOAD( "br-a-4d.b", 0x02000, 0x2000, 0x39ca1627 )
ROM_LOAD( "br-a-4b.b", 0x04000, 0x2000, 0x1865bb22 )
ROM_LOAD( "br-a-4a", 0x06000, 0x2000, 0x65b61c21 )
ROM_LOAD( "br-c-7c", 0x10000, 0x2000, 0x2e1eca52 ) /* banked at a000-bfff */
ROM_LOAD( "br-c-7l", 0x12000, 0x2000, 0xf2178578 )
ROM_LOAD( "br-c-7d", 0x14000, 0x2000, 0x3aa9fa30 )
ROM_LOAD( "br-c-7b", 0x16000, 0x2000, 0x0b31b90b )
ROM_LOAD( "br-c-7a", 0x18000, 0x2000, 0xec3b0080 )
ROM_LOAD( "br-c-7k", 0x1c000, 0x2000, 0xedc75f7f )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "br-a-3e", 0xa000, 0x2000, 0xa7140871 )
ROM_LOAD( "br-a-3f", 0xc000, 0x2000, 0x1bb51b30 )
ROM_LOAD( "br-a-3h", 0xe000, 0x2000, 0xafb3e083 )
ROM_REGION( 0x06000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "br-c-6h", 0x00000, 0x2000, 0xca50841c ) /* tiles */
ROM_LOAD( "br-c-6n", 0x02000, 0x2000, 0x7d53163a )
ROM_LOAD( "br-c-6k", 0x04000, 0x2000, 0x5951e12a )
ROM_REGION( 0x0c000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "br-b-4k.a", 0x00000, 0x2000, 0xd3c5e85b ) /* sprites */
ROM_LOAD( "br-b-4f.a", 0x02000, 0x2000, 0x4354232a )
ROM_LOAD( "br-b-3n.a", 0x04000, 0x2000, 0x2668dbef )
ROM_LOAD( "br-b-4n.a", 0x06000, 0x2000, 0xc719a324 )
ROM_LOAD( "br-b-4c.a", 0x08000, 0x2000, 0x0b3193bf )
ROM_LOAD( "br-b-4e.a", 0x0a000, 0x2000, 0x3662e8fb )
ROM_REGION( 0x04000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "br-c-1b", 0x00000, 0x2000, 0x8088911e ) /* characters */
ROM_LOAD( "br-c-1c", 0x02000, 0x2000, 0x3d78b653 )
ROM_REGION( 0x0740, REGION_PROMS )
ROM_LOAD( "br-c-3j", 0x0000, 0x0100, 0xaceaed79 ) /* tile palette red component */
ROM_LOAD( "br-b-1m", 0x0100, 0x0100, 0x3bd30c7d ) /* sprite palette red component */
ROM_LOAD( "br-c-3l", 0x0200, 0x0100, 0x7cf6f380 ) /* tile palette green component */
ROM_LOAD( "br-b-1n", 0x0300, 0x0100, 0xb7f3dc3b ) /* sprite palette green component */
ROM_LOAD( "br-c-3k", 0x0400, 0x0100, 0xd90e4a54 ) /* tile palette blue component */
ROM_LOAD( "br-b-1l", 0x0500, 0x0100, 0x5271c7d8 ) /* sprite palette blue component */
ROM_LOAD( "br-c-1j", 0x0600, 0x0020, 0x78eb5d77 ) /* character palette */
ROM_LOAD( "br-b-5p", 0x0620, 0x0020, 0xce746937 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "br-b-6f", 0x0640, 0x0100, 0x82c20d12 ) /* video timing? - same as kungfum */
ROM_END
ROM_START( ldrun )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "lr-a-4e", 0x0000, 0x2000, 0x5d7e2a4d )
ROM_LOAD( "lr-a-4d", 0x2000, 0x2000, 0x96f20473 )
ROM_LOAD( "lr-a-4b", 0x4000, 0x2000, 0xb041c4a9 )
ROM_LOAD( "lr-a-4a", 0x6000, 0x2000, 0x645e42aa )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "lr-a-3f", 0xc000, 0x2000, 0x7a96accd )
ROM_LOAD( "lr-a-3h", 0xe000, 0x2000, 0x3f7f3939 )
ROM_REGION( 0x6000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr-e-2d", 0x0000, 0x2000, 0x24f9b58d ) /* characters */
ROM_LOAD( "lr-e-2j", 0x2000, 0x2000, 0x43175e08 )
ROM_LOAD( "lr-e-2f", 0x4000, 0x2000, 0xe0317124 )
ROM_REGION( 0x6000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr-b-4k", 0x0000, 0x2000, 0x8141403e ) /* sprites */
ROM_LOAD( "lr-b-3n", 0x2000, 0x2000, 0x55154154 )
ROM_LOAD( "lr-b-4c", 0x4000, 0x2000, 0x924e34d0 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "lr-e-3m", 0x0000, 0x0100, 0x53040416 ) /* character palette red component */
ROM_LOAD( "lr-b-1m", 0x0100, 0x0100, 0x4bae1c25 ) /* sprite palette red component */
ROM_LOAD( "lr-e-3l", 0x0200, 0x0100, 0x67786037 ) /* character palette green component */
ROM_LOAD( "lr-b-1n", 0x0300, 0x0100, 0x9cd3db94 ) /* sprite palette green component */
ROM_LOAD( "lr-e-3n", 0x0400, 0x0100, 0x5b716837 ) /* character palette blue component */
ROM_LOAD( "lr-b-1l", 0x0500, 0x0100, 0x08d8cf9a ) /* sprite palette blue component */
ROM_LOAD( "lr-b-5p", 0x0600, 0x0020, 0xe01f69e2 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "lr-b-6f", 0x0620, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( ldruna )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "roma4c", 0x0000, 0x2000, 0x279421e1 )
ROM_LOAD( "lr-a-4d", 0x2000, 0x2000, 0x96f20473 )
ROM_LOAD( "roma4b", 0x4000, 0x2000, 0x3c464bad )
ROM_LOAD( "roma4a", 0x6000, 0x2000, 0x899df8e0 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "lr-a-3f", 0xc000, 0x2000, 0x7a96accd )
ROM_LOAD( "lr-a-3h", 0xe000, 0x2000, 0x3f7f3939 )
ROM_REGION( 0x6000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr-e-2d", 0x0000, 0x2000, 0x24f9b58d ) /* characters */
ROM_LOAD( "lr-e-2j", 0x2000, 0x2000, 0x43175e08 )
ROM_LOAD( "lr-e-2f", 0x4000, 0x2000, 0xe0317124 )
ROM_REGION( 0x6000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr-b-4k", 0x0000, 0x2000, 0x8141403e ) /* sprites */
ROM_LOAD( "lr-b-3n", 0x2000, 0x2000, 0x55154154 )
ROM_LOAD( "lr-b-4c", 0x4000, 0x2000, 0x924e34d0 )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "lr-e-3m", 0x0000, 0x0100, 0x53040416 ) /* character palette red component */
ROM_LOAD( "lr-b-1m", 0x0100, 0x0100, 0x4bae1c25 ) /* sprite palette red component */
ROM_LOAD( "lr-e-3l", 0x0200, 0x0100, 0x67786037 ) /* character palette green component */
ROM_LOAD( "lr-b-1n", 0x0300, 0x0100, 0x9cd3db94 ) /* sprite palette green component */
ROM_LOAD( "lr-e-3n", 0x0400, 0x0100, 0x5b716837 ) /* character palette blue component */
ROM_LOAD( "lr-b-1l", 0x0500, 0x0100, 0x08d8cf9a ) /* sprite palette blue component */
ROM_LOAD( "lr-b-5p", 0x0600, 0x0020, 0xe01f69e2 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "lr-b-6f", 0x0620, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( ldrun2 )
ROM_REGION( 0x14000, REGION_CPU1 ) /* 64k for code + 16k for banks */
ROM_LOAD( "lr2-a-4e.a", 0x00000, 0x2000, 0x22313327 )
ROM_LOAD( "lr2-a-4d", 0x02000, 0x2000, 0xef645179 )
ROM_LOAD( "lr2-a-4a.a", 0x04000, 0x2000, 0xb11ddf59 )
ROM_LOAD( "lr2-a-4a", 0x06000, 0x2000, 0x470cc8a1 )
ROM_LOAD( "lr2-h-1c.a", 0x10000, 0x2000, 0x7ebcadbc ) /* banked at 8000-9fff */
ROM_LOAD( "lr2-h-1d.a", 0x12000, 0x2000, 0x64cbb7f9 ) /* banked at 8000-9fff */
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "lr2-a-3e", 0xa000, 0x2000, 0x853f3898 )
ROM_LOAD( "lr2-a-3f", 0xc000, 0x2000, 0x7a96accd )
ROM_LOAD( "lr2-a-3h", 0xe000, 0x2000, 0x2a0e83ca )
ROM_REGION( 0x6000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr2-h-1e", 0x00000, 0x2000, 0x9d63a8ff ) /* characters */
ROM_LOAD( "lr2-h-1j", 0x02000, 0x2000, 0x40332bbd )
ROM_LOAD( "lr2-h-1h", 0x04000, 0x2000, 0x9404727d )
ROM_REGION( 0xc000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr2-b-4k", 0x00000, 0x2000, 0x79909871 ) /* sprites */
ROM_LOAD( "lr2-b-4f", 0x02000, 0x2000, 0x06ba1ef4 )
ROM_LOAD( "lr2-b-3n", 0x04000, 0x2000, 0x3cc5893f )
ROM_LOAD( "lr2-b-4n", 0x06000, 0x2000, 0x49c12f42 )
ROM_LOAD( "lr2-b-4c", 0x08000, 0x2000, 0xfbe6d24c )
ROM_LOAD( "lr2-b-4e", 0x0a000, 0x2000, 0x75172d1f )
ROM_REGION( 0x0720, REGION_PROMS )
ROM_LOAD( "lr2-h-3m", 0x0000, 0x0100, 0x2c5d834b ) /* character palette red component */
ROM_LOAD( "lr2-b-1m", 0x0100, 0x0100, 0x4ec9bb3d ) /* sprite palette red component */
ROM_LOAD( "lr2-h-3l", 0x0200, 0x0100, 0x3ae69aca ) /* character palette green component */
ROM_LOAD( "lr2-b-1n", 0x0300, 0x0100, 0x1daf1fa4 ) /* sprite palette green component */
ROM_LOAD( "lr2-h-3n", 0x0400, 0x0100, 0x2b28aec5 ) /* character palette blue component */
ROM_LOAD( "lr2-b-1l", 0x0500, 0x0100, 0xc8fb708a ) /* sprite palette blue component */
ROM_LOAD( "lr2-b-5p", 0x0600, 0x0020, 0xe01f69e2 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "lr2-b-6f", 0x0620, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( ldrun3 )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "lr3-a-4e", 0x0000, 0x4000, 0x5b334e8e )
ROM_LOAD( "lr3-a-4d.a", 0x4000, 0x4000, 0xa84bc931 )
ROM_LOAD( "lr3-a-4b.a", 0x8000, 0x4000, 0xbe09031d )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "lr3-a-3d", 0x8000, 0x4000, 0x28be68cd )
ROM_LOAD( "lr3-a-3f", 0xc000, 0x4000, 0xcb7186b7 )
ROM_REGION( 0xc000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr3-n-2a", 0x00000, 0x4000, 0xf9b74dee ) /* characters */
ROM_LOAD( "lr3-n-2c", 0x04000, 0x4000, 0xfef707ba )
ROM_LOAD( "lr3-n-2b", 0x08000, 0x4000, 0xaf3d27b9 )
ROM_REGION( 0xc000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr3-b-4k", 0x00000, 0x4000, 0x63f070c7 ) /* sprites */
ROM_LOAD( "lr3-b-3n", 0x04000, 0x4000, 0xeab7ad91 )
ROM_LOAD( "lr3-b-4c", 0x08000, 0x4000, 0x1a460a46 )
ROM_REGION( 0x0820, REGION_PROMS )
ROM_LOAD( "lr3-n-2l", 0x0000, 0x0100, 0xe880b86b ) /* character palette red component */
ROM_LOAD( "lr3-b-1m", 0x0100, 0x0100, 0xf02d7167 ) /* sprite palette red component */
ROM_LOAD( "lr3-n-2k", 0x0200, 0x0100, 0x047ee051 ) /* character palette green component */
ROM_LOAD( "lr3-b-1n", 0x0300, 0x0100, 0x9e37f181 ) /* sprite palette green component */
ROM_LOAD( "lr3-n-2m", 0x0400, 0x0100, 0x69ad8678 ) /* character palette blue component */
ROM_LOAD( "lr3-b-1l", 0x0500, 0x0100, 0x5b11c41d ) /* sprite palette blue component */
ROM_LOAD( "lr3-b-5p", 0x0600, 0x0020, 0xe01f69e2 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "lr3-n-4f", 0x0620, 0x0100, 0xdf674be9 ) /* unknown */
ROM_LOAD( "lr3-b-6f", 0x0720, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( ldrun4 )
ROM_REGION( 0x18000, REGION_CPU1 ) /* 64k for code + 32k for banked ROM */
ROM_LOAD( "lr4-a-4e", 0x00000, 0x4000, 0x5383e9bf )
ROM_LOAD( "lr4-a-4d.c", 0x04000, 0x4000, 0x298afa36 )
ROM_LOAD( "lr4-v-4k", 0x10000, 0x8000, 0x8b248abd ) /* banked at 8000-bfff */
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "lr4-a-3d", 0x8000, 0x4000, 0x86c6d445 )
ROM_LOAD( "lr4-a-3f", 0xc000, 0x4000, 0x097c6c0a )
ROM_REGION( 0xc000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr4-v-2b", 0x00000, 0x4000, 0x4118e60a ) /* characters */
ROM_LOAD( "lr4-v-2d", 0x04000, 0x4000, 0x542bb5b5 )
ROM_LOAD( "lr4-v-2c", 0x08000, 0x4000, 0xc765266c )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lr4-b-4k", 0x00000, 0x4000, 0xe7fe620c ) /* sprites */
ROM_LOAD( "lr4-b-4f", 0x04000, 0x4000, 0x6f0403db )
ROM_LOAD( "lr4-b-3n", 0x08000, 0x4000, 0xad1fba1b )
ROM_LOAD( "lr4-b-4n", 0x0c000, 0x4000, 0x0e568fab )
ROM_LOAD( "lr4-b-4c", 0x10000, 0x4000, 0x82c53669 )
ROM_LOAD( "lr4-b-4e", 0x14000, 0x4000, 0x767a1352 )
ROM_REGION( 0x0820, REGION_PROMS )
ROM_LOAD( "lr4-v-1m", 0x0000, 0x0100, 0xfe51bf1d ) /* character palette red component */
ROM_LOAD( "lr4-b-1m", 0x0100, 0x0100, 0x5d8d17d0 ) /* sprite palette red component */
ROM_LOAD( "lr4-v-1n", 0x0200, 0x0100, 0xda0658e5 ) /* character palette green component */
ROM_LOAD( "lr4-b-1n", 0x0300, 0x0100, 0xda1129d2 ) /* sprite palette green component */
ROM_LOAD( "lr4-v-1p", 0x0400, 0x0100, 0x0df23ebe ) /* character palette blue component */
ROM_LOAD( "lr4-b-1l", 0x0500, 0x0100, 0x0d89b692 ) /* sprite palette blue component */
ROM_LOAD( "lr4-b-5p", 0x0600, 0x0020, 0xe01f69e2 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "lr4-v-4h", 0x0620, 0x0100, 0xdf674be9 ) /* unknown */
ROM_LOAD( "lr4-b-6f", 0x0720, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( lotlot )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code */
ROM_LOAD( "lot-a-4e", 0x0000, 0x4000, 0x2913d08f )
ROM_LOAD( "lot-a-4d", 0x4000, 0x4000, 0x0443095f )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU (6803) */
ROM_LOAD( "lot-a-3h", 0xe000, 0x2000, 0x0781cee7 )
ROM_REGION( 0x6000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lot-k-4a", 0x00000, 0x2000, 0x1b3695f4 ) /* tiles */
ROM_LOAD( "lot-k-4c", 0x02000, 0x2000, 0xbd2b0730 )
ROM_LOAD( "lot-k-4b", 0x04000, 0x2000, 0x930ddd55 )
ROM_REGION( 0x6000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lot-b-4k", 0x00000, 0x2000, 0xfd27cb90 ) /* sprites */
ROM_LOAD( "lot-b-3n", 0x02000, 0x2000, 0xbd486fff )
ROM_LOAD( "lot-b-4c", 0x04000, 0x2000, 0x3026ee6c )
ROM_REGION( 0x6000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "lot-k-4p", 0x00000, 0x2000, 0x3b7d95ba ) /* chars */
ROM_LOAD( "lot-k-4l", 0x02000, 0x2000, 0xf98dca1f )
ROM_LOAD( "lot-k-4n", 0x04000, 0x2000, 0xf0cd76a5 )
ROM_REGION( 0x0e20, REGION_PROMS )
ROM_LOAD( "lot-k-2f", 0x0000, 0x0100, 0xb820a05e ) /* tile palette red component */
ROM_LOAD( "lot-b-1m", 0x0100, 0x0100, 0xc146461d ) /* sprite palette red component */
ROM_LOAD( "lot-k-2l", 0x0200, 0x0100, 0xac3e230d ) /* character palette red component */
ROM_LOAD( "lot-k-2e", 0x0300, 0x0100, 0x9b1fa005 ) /* tile palette green component */
ROM_LOAD( "lot-b-1n", 0x0400, 0x0100, 0x01e07db6 ) /* sprite palette green component */
ROM_LOAD( "lot-k-2k", 0x0500, 0x0100, 0x1811ad2b ) /* character palette green component */
ROM_LOAD( "lot-k-2d", 0x0600, 0x0100, 0x315ed9a8 ) /* tile palette blue component */
ROM_LOAD( "lot-b-1l", 0x0700, 0x0100, 0x8b6fcde3 ) /* sprite palette blue component */
ROM_LOAD( "lot-k-2j", 0x0800, 0x0100, 0xe791ef2a ) /* character palette blue component */
ROM_LOAD( "lot-b-5p", 0x0900, 0x0020, 0x110b21fd ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "lot-k-7e", 0x0920, 0x0200, 0x6cef0fbd ) /* unknown */
ROM_LOAD( "lot-k-7h", 0x0b20, 0x0200, 0x04442bee ) /* unknown */
ROM_LOAD( "lot-b-6f", 0x0d20, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( kidniki )
ROM_REGION( 0x30000, REGION_CPU1 ) /* main CPU */
ROM_LOAD( "dr04.4e", 0x00000, 0x04000, 0x80431858 )
ROM_LOAD( "dr03.4cd", 0x04000, 0x04000, 0xdba20934 )
ROM_LOAD( "dr11.8k", 0x10000, 0x08000, 0x04d82d93 ) /* banked at 8000-9fff */
ROM_LOAD( "dr12.8l", 0x18000, 0x08000, 0xc0b255fd )
ROM_CONTINUE( 0x28000, 0x08000 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* sound CPU */
ROM_LOAD( "dr00.3a", 0x4000, 0x04000, 0x458309f7 )
ROM_LOAD( "dr01.3cd", 0x8000, 0x04000, 0xe66897bd )
ROM_LOAD( "dr02.3f", 0xc000, 0x04000, 0xf9e31e26 ) /* 6803 code */
ROM_REGION( 0x18000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "dr06.2b", 0x00000, 0x8000, 0x4d9a970f ) /* tiles */
ROM_LOAD( "dr07.2dc", 0x08000, 0x8000, 0xab59a4c4 )
ROM_LOAD( "dr05.2a", 0x10000, 0x8000, 0x2e6dad0c )
ROM_REGION( 0x30000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "dr21.4k", 0x00000, 0x4000, 0xa06cea9a ) /* sprites */
ROM_LOAD( "dr19.4f", 0x04000, 0x4000, 0xb34605ad )
ROM_LOAD( "dr22.4l", 0x08000, 0x4000, 0x41303de8 )
ROM_LOAD( "dr20.4jh", 0x0c000, 0x4000, 0x5fbe6f61 )
ROM_LOAD( "dr14.3p", 0x10000, 0x4000, 0x76cfbcbc )
ROM_LOAD( "dr24.4p", 0x14000, 0x4000, 0xd51c8db5 )
ROM_LOAD( "dr23.4nm", 0x18000, 0x4000, 0x03469df8 )
ROM_LOAD( "dr13.3nm", 0x1c000, 0x4000, 0xd5c3dfe0 )
ROM_LOAD( "dr16.4cb", 0x20000, 0x4000, 0xf1d1bb93 )
ROM_LOAD( "dr18.4e", 0x24000, 0x4000, 0xedb7f25b )
ROM_LOAD( "dr17.4dc", 0x28000, 0x4000, 0x4fb87868 )
ROM_LOAD( "dr15.4a", 0x2c000, 0x4000, 0xe0b88de5 )
ROM_REGION( 0x0c000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "dr08.4l", 0x00000, 0x4000, 0x32d50643 ) /* chars */
ROM_LOAD( "dr09.4m", 0x04000, 0x4000, 0x17df6f95 )
ROM_LOAD( "dr10.4n", 0x08000, 0x4000, 0x820ce252 )
ROM_REGION( 0x0920, REGION_PROMS )
ROM_LOAD( "dr25.3f", 0x0000, 0x0100, 0x8e91430b ) /* character palette red component */
ROM_LOAD( "dr30.1m", 0x0100, 0x0100, 0x28c73263 ) /* sprite palette red component */
ROM_LOAD( "dr26.3h", 0x0200, 0x0100, 0xb563b93f ) /* character palette green component */
ROM_LOAD( "dr31.1n", 0x0300, 0x0100, 0x3529210e ) /* sprite palette green component */
ROM_LOAD( "dr27.3j", 0x0400, 0x0100, 0x70d668ef ) /* character palette blue component */
ROM_LOAD( "dr29.1l", 0x0500, 0x0100, 0x1173a754 ) /* sprite palette blue component */
ROM_LOAD( "dr32.5p", 0x0600, 0x0020, 0x11cd1f2e ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "dr28.8f", 0x0620, 0x0200, 0x6cef0fbd ) /* unknown */
ROM_LOAD( "dr33.6f", 0x0820, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( yanchamr )
ROM_REGION( 0x30000, REGION_CPU1 ) /* main CPU */
ROM_LOAD( "ky_a-4e-.bin", 0x00000, 0x04000, 0xc73ad2d6 )
ROM_LOAD( "ky_a-4d-.bin", 0x04000, 0x04000, 0x401af828 )
ROM_LOAD( "ky_t-8k-.bin", 0x10000, 0x08000, 0xe967de88 ) /* banked at 8000-9fff */
ROM_LOAD( "ky_t-8l-.bin", 0x18000, 0x08000, 0xa929110b )
/* ROM_CONTINUE( 0x28000, 0x08000 ) */
ROM_REGION( 0x10000, REGION_CPU2 ) /* sound CPU */
ROM_LOAD( "ky_a-3a-.bin", 0x4000, 0x04000, 0xcb365f3b )
ROM_LOAD( "dr01.3cd", 0x8000, 0x04000, 0xe66897bd )
ROM_LOAD( "dr02.3f", 0xc000, 0x04000, 0xf9e31e26 ) /* 6803 code */
ROM_REGION( 0x18000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "ky_t-2c-.bin", 0x00000, 0x8000, 0xcb9761fc ) /* tiles */
ROM_LOAD( "ky_t-2d-.bin", 0x08000, 0x8000, 0x59732741 )
ROM_LOAD( "ky_t-2a-.bin", 0x10000, 0x8000, 0x0370fd82 )
ROM_REGION( 0x30000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "ky_b-4k-.bin", 0x00000, 0x4000, 0x263a9d10 ) /* sprites */
ROM_LOAD( "ky_b-4f-.bin", 0x04000, 0x4000, 0x86e3d4a8 )
ROM_LOAD( "ky_b-4l-.bin", 0x08000, 0x4000, 0x19fa7558 )
ROM_LOAD( "ky_b-4h-.bin", 0x0c000, 0x4000, 0x93e6665c )
ROM_LOAD( "ky_b-3n-.bin", 0x10000, 0x4000, 0x0287c525 )
ROM_LOAD( "ky_b-4n-.bin", 0x14000, 0x4000, 0x764946e0 )
ROM_LOAD( "ky_b-4m-.bin", 0x18000, 0x4000, 0xeced5db9 )
ROM_LOAD( "ky_b-3m-.bin", 0x1c000, 0x4000, 0xbe6cee44 )
ROM_LOAD( "ky_b-4c-.bin", 0x20000, 0x4000, 0x84d6b65d )
ROM_LOAD( "ky_b-4e-.bin", 0x24000, 0x4000, 0xf91f9273 )
ROM_LOAD( "ky_b-4d-.bin", 0x28000, 0x4000, 0xa2fc15f0 )
ROM_LOAD( "ky_b-4a-.bin", 0x2c000, 0x4000, 0xff2b9c8a )
ROM_REGION( 0x0c000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "ky_t-4l-.bin", 0x00000, 0x4000, 0x1d0a9253 ) /* chars */
ROM_LOAD( "ky_t-4m-.bin", 0x04000, 0x4000, 0x4075c396 )
ROM_LOAD( "ky_t-4n-.bin", 0x08000, 0x4000, 0x7564f2ff )
ROM_REGION( 0x0920, REGION_PROMS )
ROM_LOAD( "dr25.3f", 0x0000, 0x0100, 0x8e91430b ) /* character palette red component */
ROM_LOAD( "dr30.1m", 0x0100, 0x0100, 0x28c73263 ) /* sprite palette red component */
ROM_LOAD( "dr26.3h", 0x0200, 0x0100, 0xb563b93f ) /* character palette green component */
ROM_LOAD( "dr31.1n", 0x0300, 0x0100, 0x3529210e ) /* sprite palette green component */
ROM_LOAD( "dr27.3j", 0x0400, 0x0100, 0x70d668ef ) /* character palette blue component */
ROM_LOAD( "dr29.1l", 0x0500, 0x0100, 0x1173a754 ) /* sprite palette blue component */
ROM_LOAD( "dr32.5p", 0x0600, 0x0020, 0x11cd1f2e ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "dr28.8f", 0x0620, 0x0200, 0x6cef0fbd ) /* unknown */
ROM_LOAD( "dr33.6f", 0x0820, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( spelunkr )
ROM_REGION( 0x18000, REGION_CPU1 ) /* main CPU */
ROM_LOAD( "spra.4e", 0x00000, 0x4000, 0xcf811201 )
ROM_LOAD( "spra.4d", 0x04000, 0x4000, 0xbb4faa4f )
ROM_LOAD( "sprm.7c", 0x10000, 0x4000, 0xfb6197e2 ) /* banked at 8000-9fff */
ROM_LOAD( "sprm.7b", 0x14000, 0x4000, 0x26bb25a4 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* sound CPU */
ROM_LOAD( "spra.3d", 0x8000, 0x04000, 0x4110363c ) /* adpcm data */
ROM_LOAD( "spra.3f", 0xc000, 0x04000, 0x67a9d2e6 ) /* 6803 code */
ROM_REGION( 0x18000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "sprm.1d", 0x00000, 0x4000, 0x4ef7ae89 ) /* tiles */
ROM_LOAD( "sprm.1e", 0x04000, 0x4000, 0xa3755180 )
ROM_LOAD( "sprm.3c", 0x08000, 0x4000, 0xb4008e6a )
ROM_LOAD( "sprm.3b", 0x0c000, 0x4000, 0xf61cf012 )
ROM_LOAD( "sprm.1c", 0x10000, 0x4000, 0x58b21c76 )
ROM_LOAD( "sprm.1b", 0x14000, 0x4000, 0xa95cb3e5 )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "sprb.4k", 0x00000, 0x4000, 0xe7f0e861 ) /* sprites */
ROM_LOAD( "sprb.4f", 0x04000, 0x4000, 0x32663097 )
ROM_LOAD( "sprb.3p", 0x08000, 0x4000, 0x8fbaf373 )
ROM_LOAD( "sprb.4p", 0x0c000, 0x4000, 0x37069b76 )
ROM_LOAD( "sprb.4c", 0x10000, 0x4000, 0xcfe46a88 )
ROM_LOAD( "sprb.4e", 0x14000, 0x4000, 0x11c48979 )
ROM_REGION( 0x0c000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "sprm.4p", 0x00000, 0x0800, 0x4dfe2e63 ) /* chars */
ROM_CONTINUE( 0x02000, 0x0800 ) /* first and second half identical, */
ROM_CONTINUE( 0x00800, 0x0800 ) /* second half not used by the driver */
ROM_CONTINUE( 0x02800, 0x0800 )
ROM_CONTINUE( 0x00000, 0x0800 )
ROM_CONTINUE( 0x03000, 0x0800 )
ROM_CONTINUE( 0x00800, 0x0800 )
ROM_CONTINUE( 0x03800, 0x0800 )
ROM_LOAD( "sprm.4l", 0x04000, 0x0800, 0x239f2cd4 )
ROM_CONTINUE( 0x06000, 0x0800 )
ROM_CONTINUE( 0x04800, 0x0800 )
ROM_CONTINUE( 0x06800, 0x0800 )
ROM_CONTINUE( 0x05000, 0x0800 )
ROM_CONTINUE( 0x07000, 0x0800 )
ROM_CONTINUE( 0x05800, 0x0800 )
ROM_CONTINUE( 0x07800, 0x0800 )
ROM_LOAD( "sprm.4m", 0x08000, 0x0800, 0xd6d07d70 )
ROM_CONTINUE( 0x0a000, 0x0800 )
ROM_CONTINUE( 0x08800, 0x0800 )
ROM_CONTINUE( 0x0a800, 0x0800 )
ROM_CONTINUE( 0x09000, 0x0800 )
ROM_CONTINUE( 0x0b000, 0x0800 )
ROM_CONTINUE( 0x09800, 0x0800 )
ROM_CONTINUE( 0x0b800, 0x0800 )
ROM_REGION( 0x0920, REGION_PROMS )
ROM_LOAD( "sprm.2k", 0x0000, 0x0100, 0xfd8fa991 ) /* character palette red component */
ROM_LOAD( "sprb.1m", 0x0100, 0x0100, 0x8d8cccad ) /* sprite palette red component */
ROM_LOAD( "sprm.2j", 0x0200, 0x0100, 0x0e3890b4 ) /* character palette blue component */
ROM_LOAD( "sprb.1n", 0x0300, 0x0100, 0xc40e1cb2 ) /* sprite palette green component */
ROM_LOAD( "sprm.2h", 0x0400, 0x0100, 0x0478082b ) /* character palette green component */
ROM_LOAD( "sprb.1l", 0x0500, 0x0100, 0x3ec46248 ) /* sprite palette blue component */
ROM_LOAD( "sprb.5p", 0x0600, 0x0020, 0x746c6238 ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "sprm.8h", 0x0620, 0x0200, 0x875cc442 ) /* unknown */
ROM_LOAD( "sprb.6f", 0x0820, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
ROM_START( spelunk2 )
ROM_REGION( 0x24000, REGION_CPU1 ) /* main CPU */
ROM_LOAD( "sp2-a.4e", 0x00000, 0x4000, 0x96c04bbb )
ROM_LOAD( "sp2-a.4d", 0x04000, 0x4000, 0xcb38c2ff )
ROM_LOAD( "sp2-r.7d", 0x10000, 0x8000, 0x558837ea ) /* banked at 9000-9fff */
ROM_LOAD( "sp2-r.7c", 0x18000, 0x8000, 0x4b380162 ) /* banked at 9000-9fff */
ROM_LOAD( "sp2-r.7b", 0x20000, 0x4000, 0x7709a1fe ) /* banked at 8000-8fff */
ROM_REGION( 0x10000, REGION_CPU2 ) /* sound CPU */
ROM_LOAD( "sp2-a.3d", 0x8000, 0x04000, 0x839ec7e2 ) /* adpcm data */
ROM_LOAD( "sp2-a.3f", 0xc000, 0x04000, 0xad3ce898 ) /* 6803 code */
ROM_REGION( 0x18000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "sp2-r.1d", 0x00000, 0x8000, 0xc19fa4c9 ) /* tiles */
ROM_LOAD( "sp2-r.3b", 0x08000, 0x8000, 0x366604af )
ROM_LOAD( "sp2-r.1b", 0x10000, 0x8000, 0x3a0c4d47 )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "sp2-b.4k", 0x00000, 0x4000, 0x6cb67a17 ) /* sprites */
ROM_LOAD( "sp2-b.4f", 0x04000, 0x4000, 0xe4a1166f )
ROM_LOAD( "sp2-b.3n", 0x08000, 0x4000, 0xf59e8b76 )
ROM_LOAD( "sp2-b.4n", 0x0c000, 0x4000, 0xfa65bac9 )
ROM_LOAD( "sp2-b.4c", 0x10000, 0x4000, 0x1caf7013 )
ROM_LOAD( "sp2-b.4e", 0x14000, 0x4000, 0x780a463b )
ROM_REGION( 0x0c000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "sp2-r.4l", 0x00000, 0x0800, 0x6a4b2d8b ) /* chars */
ROM_CONTINUE( 0x02000, 0x0800 ) /* first and second half identical, */
ROM_CONTINUE( 0x00800, 0x0800 ) /* second half not used by the driver */
ROM_CONTINUE( 0x02800, 0x0800 )
ROM_CONTINUE( 0x00000, 0x0800 )
ROM_CONTINUE( 0x03000, 0x0800 )
ROM_CONTINUE( 0x00800, 0x0800 )
ROM_CONTINUE( 0x03800, 0x0800 )
ROM_LOAD( "sp2-r.4m", 0x04000, 0x0800, 0xe1368b61 )
ROM_CONTINUE( 0x06000, 0x0800 )
ROM_CONTINUE( 0x04800, 0x0800 )
ROM_CONTINUE( 0x06800, 0x0800 )
ROM_CONTINUE( 0x05000, 0x0800 )
ROM_CONTINUE( 0x07000, 0x0800 )
ROM_CONTINUE( 0x05800, 0x0800 )
ROM_CONTINUE( 0x07800, 0x0800 )
ROM_LOAD( "sp2-r.4p", 0x08000, 0x0800, 0xfc138e13 )
ROM_CONTINUE( 0x0a000, 0x0800 )
ROM_CONTINUE( 0x08800, 0x0800 )
ROM_CONTINUE( 0x0a800, 0x0800 )
ROM_CONTINUE( 0x09000, 0x0800 )
ROM_CONTINUE( 0x0b000, 0x0800 )
ROM_CONTINUE( 0x09800, 0x0800 )
ROM_CONTINUE( 0x0b800, 0x0800 )
ROM_REGION( 0x0a20, REGION_PROMS )
ROM_LOAD( "sp2-r.1k", 0x0000, 0x0200, 0x31c1bcdc ) /* chars red and green component */
ROM_LOAD( "sp2-r.2k", 0x0200, 0x0100, 0x1cf5987e ) /* chars blue component */
ROM_LOAD( "sp2-r.2j", 0x0300, 0x0100, 0x1acbe2a5 ) /* chars blue component */
ROM_LOAD( "sp2-b.1m", 0x0400, 0x0100, 0x906104c7 ) /* sprites red component */
ROM_LOAD( "sp2-b.1n", 0x0500, 0x0100, 0x5a564c06 ) /* sprites green component */
ROM_LOAD( "sp2-b.1l", 0x0600, 0x0100, 0x8f4a2e3c ) /* sprites blue component */
ROM_LOAD( "sp2-b.5p", 0x0700, 0x0020, 0xcd126f6a ) /* sprite height, one entry per 32 */
/* sprites. Used at run time! */
ROM_LOAD( "sp2-r.8j", 0x0720, 0x0200, 0x875cc442 ) /* unknown */
ROM_LOAD( "sp2-b.6f", 0x0920, 0x0100, 0x34d88d3c ) /* video timing? - common to the other games */
ROM_END
GAME( 1984, kungfum, 0, kungfum, kungfum, 0, ROT0, "Irem", "Kung Fu Master" )
GAME( 1984, kungfud, kungfum, kungfum, kungfum, 0, ROT0, "Irem (Data East license)", "Kung Fu Master (Data East)" )
GAME( 1984, spartanx, kungfum, kungfum, kungfum, 0, ROT0, "Irem", "Spartan X (Japan)" )
GAME( 1984, kungfub, kungfum, kungfum, kungfum, 0, ROT0, "bootleg", "Kung Fu Master (bootleg set 1)" )
GAME( 1984, kungfub2, kungfum, kungfum, kungfum, 0, ROT0, "bootleg", "Kung Fu Master (bootleg set 2)" )
GAME( 1984, battroad, 0, battroad, battroad, 0, ROT90, "Irem", "The Battle-Road" )
GAME( 1984, ldrun, 0, ldrun, ldrun, 0, ROT0, "Irem (licensed from Broderbund)", "Lode Runner (set 1)" )
GAME( 1984, ldruna, ldrun, ldrun, ldrun, 0, ROT0, "Irem (licensed from Broderbund)", "Lode Runner (set 2)" )
GAME( 1984, ldrun2, 0, ldrun2, ldrun2, 0, ROT0, "Irem (licensed from Broderbund)", "Lode Runner II - The Bungeling Strikes Back" ) /* Japanese version is called Bangeringu Teikoku No Gyakushuu */
GAME( 1985, ldrun3, 0, ldrun3, ldrun3, 0, ROT0, "Irem (licensed from Broderbund)", "Lode Runner III - Majin No Fukkatsu" )
GAME( 1986, ldrun4, 0, ldrun4, ldrun4, 0, ROT0, "Irem (licensed from Broderbund)", "Lode Runner IV - Teikoku Karano Dasshutsu" )
GAME( 1985, lotlot, 0, lotlot, lotlot, 0, ROT0, "Irem (licensed from Tokuma Shoten)", "Lot Lot" )
GAMEX(1986, kidniki, 0, kidniki, kidniki, 0, ROT0, "Irem (Data East USA license)", "Kid Niki - Radical Ninja (US)", GAME_IMPERFECT_SOUND )
GAMEX(1986, yanchamr, kidniki, kidniki, kidniki, 0, ROT0, "Irem", "Kaiketsu Yanchamaru (Japan)", GAME_IMPERFECT_SOUND )
GAME( 1985, spelunkr, 0, spelunkr, spelunkr, 0, ROT0, "Irem (licensed from Broderbund)", "Spelunker" )
GAME( 1986, spelunk2, 0, spelunk2, spelunk2, 0, ROT0, "Irem (licensed from Broderbund)", "Spelunker II" )
| 43.927078 | 208 | 0.640589 | [
"3d"
] |
102921263c32f0c13a5b9181b4ae2cba1ed571e6 | 817 | hpp | C++ | include/impl/os_windows.hpp | basaltex/aze | 1c64862e9ba2dfd2c6745e936274fd8a7be13d79 | [
"MIT"
] | null | null | null | include/impl/os_windows.hpp | basaltex/aze | 1c64862e9ba2dfd2c6745e936274fd8a7be13d79 | [
"MIT"
] | null | null | null | include/impl/os_windows.hpp | basaltex/aze | 1c64862e9ba2dfd2c6745e936274fd8a7be13d79 | [
"MIT"
] | null | null | null | ///////
#ifndef GA_OS_WINDOWS_HPP
#define GA_OS_WINDOWS_HPP
#include <string>
#include <string_view>
#include <optional>
#include <vector>
namespace os {
inline bool Executable(std::string &exe) {
(void)exe;
// NOTIMPL
return false;
}
inline bool PathRemoveFileSpec(std::string &path) {
if (path.empty()) {
return false;
}
auto p = path.c_str();
auto end = p + path.size();
while (p < end--) {
if (*end == '/' || *end == '\\') {
auto l = end - p;
path.erase(l == 0 ? 1 : l);
return true;
}
}
return false;
}
constexpr const char PathSeparator = '\\';
inline std::string Getwd() {
// NOTIMPL
return ".";
}
inline std::optional<std::string> Gitdir(std::string_view sv) {
/// NOTIMPL
return std::make_optional(std::string(sv));
}
} // namespace os
#endif
| 17.382979 | 63 | 0.604651 | [
"vector"
] |
102af8bad5fcd137bc5103f4c33a8a22dc8f21d0 | 42,905 | cpp | C++ | Vic2ToHoI4/Source/OutHoi4/OutHoi4Country.cpp | ParadoxGameConverters/Vic2ToHoI4 | ac5d77f2bcf8b9b7cb9dfe78a0bc85875600fc1c | [
"MIT"
] | 25 | 2018-12-10T03:41:49.000Z | 2021-10-04T10:42:36.000Z | Vic2ToHoI4/Source/OutHoi4/OutHoi4Country.cpp | Elfangor567/Vic2ToHoI4 | 55df397bbb65ecb690fe6bb5fcaf757d17bcc885 | [
"MIT"
] | 739 | 2018-12-13T02:01:20.000Z | 2022-03-28T02:57:13.000Z | Vic2ToHoI4/Source/OutHoi4/OutHoi4Country.cpp | Elfangor567/Vic2ToHoI4 | 55df397bbb65ecb690fe6bb5fcaf757d17bcc885 | [
"MIT"
] | 43 | 2018-12-10T03:41:58.000Z | 2022-03-22T23:55:41.000Z | #include "OutHoi4Country.h"
#include "AiStrategy/OutAiStrategy.h"
#include "Date.h"
#include "HOI4World/Diplomacy/Faction.h"
#include "HOI4World/HoI4Country.h"
#include "HOI4World/Leaders/Advisor.h"
#include "HOI4World/Leaders/CountryLeader.h"
#include "HOI4World/Military/DivisionTemplate.h"
#include "HOI4World/Names/Names.h"
#include "HOI4World/Navies/NavyNames.h"
#include "Leaders/OutAdmiral.h"
#include "Leaders/OutAdvisor.h"
#include "Leaders/OutCountryLeader.h"
#include "Leaders/OutGeneral.h"
#include "Mappers/Graphics/GraphicsMapper.h"
#include "Navies/OutLegacyNavyNames.h"
#include "Navies/OutMtgNavyNames.h"
#include "Navies/OutNavies.h"
#include "OSCompatibilityLayer.h"
#include "OutFocusTree.h"
#include "OutHoi4/Operative/OutOperative.h"
#include "OutTechnologies.h"
#include "V2World/Countries/Country.h"
#include <ranges>
#include <string>
void HoI4::outputToCommonCountriesFile(std::ostream& countriesFile, const Country& theCountry)
{
countriesFile << theCountry.getTag() << " = \"countries/"
<< commonItems::normalizeUTF8Path(theCountry.getCommonCountryFile()) << "\"\n";
}
void HoI4::outputColors(std::ostream& out, const Country& theCountry)
{
out << theCountry.getTag() << " = {\n";
out << "\tcolor " << theCountry.getColor().outputRgb() << "\n";
out << "\tcolor_ui " << theCountry.getColor().outputRgb() << "";
out << "}\n";
}
void outputNamesSet(std::ostream& namesFile,
const std::optional<std::vector<std::string>>& names,
const std::string& tabs);
void HoI4::outputToNamesFiles(std::ostream& namesFile, const Names& names, const Country& theCountry)
{
const auto primaryCulture = theCountry.getPrimaryCulture();
auto femaleSurnames = names.getFemaleSurnames(primaryCulture);
namesFile << theCountry.getTag() << " = {\n";
namesFile << "\tmale = {\n";
namesFile << "\t\tnames = {\n";
outputNamesSet(namesFile, names.getMaleNames(primaryCulture), "\t\t\t");
namesFile << "\t\t}\n";
if (!femaleSurnames->empty())
{
namesFile << "\t\tsurnames = {\n";
outputNamesSet(namesFile, names.getSurnames(primaryCulture), "\t\t");
namesFile << "\t\t}\n";
}
namesFile << "\t}\n";
namesFile << "\tfemale = {\n";
namesFile << "\t\tnames = {\n";
outputNamesSet(namesFile, names.getFemaleNames(primaryCulture), "\t\t\t");
namesFile << "\t\t}\n";
if (!femaleSurnames->empty())
{
namesFile << "\t\tsurnames = {\n";
outputNamesSet(namesFile, femaleSurnames, "\t\t");
namesFile << "\t}\n";
}
namesFile << "\t}\n";
if (femaleSurnames->empty())
{
namesFile << "\tsurnames = {\n";
outputNamesSet(namesFile, names.getSurnames(primaryCulture), "\t\t");
namesFile << "\t}\n";
}
namesFile << "\tcallsigns = {\n";
outputNamesSet(namesFile, names.getCallsigns(primaryCulture), "\t\t");
namesFile << "\t}\n";
namesFile << "}\n";
}
void outputNamesSet(std::ostream& namesFile,
const std::optional<std::vector<std::string>>& names,
const std::string& tabs)
{
if (names)
{
namesFile << tabs;
for (unsigned int i = 0; i < names->size(); i++)
{
namesFile << '\"' << (*names)[i] << '\"';
if ((i + 1) == names->size())
{
continue;
}
if (((i + 1) % 10) == 0)
{
namesFile << "\n";
namesFile << tabs;
}
else
{
namesFile << " ";
}
}
namesFile << '\n';
}
}
void HoI4::outputToUnitNamesFiles(const Country& theCountry, const Configuration& theConfiguration)
{
const auto& tag = theCountry.getTag();
std::ofstream legacyUnitNamesFile(
"output/" + theConfiguration.getOutputName() + "/common/units/names/" + tag + "_names.txt");
if (!legacyUnitNamesFile.is_open())
{
throw std::runtime_error(
"Could not open output/" + theConfiguration.getOutputName() + "/common/units/names/" + tag + "_names.txt");
}
legacyUnitNamesFile << "\xEF\xBB\xBF"; // add the BOM to make HoI4 happy
outLegacyNavyNames(legacyUnitNamesFile, theCountry.getNavyNames().getLegacyShipTypeNames(), tag);
legacyUnitNamesFile.close();
std::ofstream mtgUnitNamesFile(
"output/" + theConfiguration.getOutputName() + "/common/units/names_ships/" + tag + "_ship_names.txt");
if (!mtgUnitNamesFile.is_open())
{
throw std::runtime_error("Could not open output/" + theConfiguration.getOutputName() +
"/common/units/names_ships/" + tag + "_ship_names.txt");
}
mtgUnitNamesFile << "\xEF\xBB\xBF"; // add the BOM to make HoI4 happy
outMtgNavyNames(mtgUnitNamesFile, theCountry.getNavyNames().getMtgShipTypeNames(), tag);
mtgUnitNamesFile.close();
}
void HoI4::outputIdeaGraphics(std::ostream& ideasFile, const Country& theCountry)
{
const auto& tag = theCountry.getTag();
const auto& primaryCultureGroup = theCountry.getPrimaryCultureGroup();
ideasFile << "\tspriteType = {\n";
ideasFile << "\t\tname = \"GFX_idea_" << tag << "_communism_advisor\"\n";
ideasFile << "\t\ttexturefile = \"" << theCountry.getCommunistAdvisorPortrait() << "\"\n";
ideasFile << "\t}\n";
ideasFile << "\tspriteType = {\n";
ideasFile << "\t\tname = \"GFX_idea_" << tag << "_democratic_advisor\"\n";
ideasFile << "\t\ttexturefile = \"" << theCountry.getDemocraticAdvisorPortrait() << "\"\n";
ideasFile << "\t}\n";
ideasFile << "\tspriteType = {\n";
ideasFile << "\t\tname = \"GFX_idea_" << tag << "_neutrality_advisor\"\n";
ideasFile << "\t\ttexturefile = \"" << theCountry.getNeutralityAdvisorPortrait() << "\"\n";
ideasFile << "\t}\n";
ideasFile << "\tspriteType = {\n";
ideasFile << "\t\tname = \"GFX_idea_" << tag << "_absolutist_advisor\"\n";
ideasFile << "\t\ttexturefile = \"" << theCountry.getAbsolutistAdvisorPortrait() << "\"\n";
ideasFile << "\t}\n";
ideasFile << "\tspriteType = {\n";
ideasFile << "\t\tname = \"GFX_idea_" << tag << "_radical_advisor\"\n";
ideasFile << "\t\ttexturefile = \"" << theCountry.getRadicalAdvisorPortrait() << "\"\n";
ideasFile << "\t}\n";
ideasFile << "\tspriteType = {\n";
ideasFile << "\t\tname = \"GFX_idea_" << tag << "_fascism_advisor\"\n";
ideasFile << "\t\ttexturefile = \"" << theCountry.getFascistAdvisorPortrait() << "\"\n";
ideasFile << "\t}\n";
}
void HoI4::outputPortraits(std::ostream& portraitsFile, const HoI4::Country& theCountry)
{
const auto& armyPortraits = theCountry.getArmyPortraits();
const auto& navyPortraits = theCountry.getNavyPortraits();
const auto& femaleMilitaryPortraits = theCountry.getFemaleMilitaryPortraits();
const auto& femaleMonarchPortraits = theCountry.getFemaleMonarchPortraits();
const auto& femaleIdeologicalPortraits = theCountry.getFemaleIeologicalPortraits();
portraitsFile << theCountry.getTag() << " = {\n";
// Military
if (!armyPortraits.empty())
{
portraitsFile << "\tarmy = {\n";
// Men
portraitsFile << "\t\tmale = {\n";
for (const auto& portrait: armyPortraits)
{
portraitsFile << "\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t}\n";
// Women
portraitsFile << "\t\tfemale = {\n";
for (const auto& portrait: femaleMilitaryPortraits)
{
portraitsFile << "\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t}\n";
portraitsFile << "\t}\n";
}
if (!armyPortraits.empty() && !navyPortraits.empty())
{
portraitsFile << "\n";
}
if (!navyPortraits.empty())
{
portraitsFile << "\tnavy = {\n";
// Men
portraitsFile << "\t\tmale = {\n";
for (const auto& portrait: navyPortraits)
{
portraitsFile << "\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t}\n";
// Women
portraitsFile << "\t\tfemale = {\n";
for (const auto& portrait: femaleMilitaryPortraits)
{
portraitsFile << "\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t}\n";
portraitsFile << "\t}\n";
}
// Political
portraitsFile << "\tpolitical = {\n";
// Communism
portraitsFile << "\t\tcommunism = {\n";
// Men
const auto& maleCommunistPortraits = theCountry.getMaleCommunistPortraits();
portraitsFile << "\t\t\tmale = {\n";
for (const auto& portrait: maleCommunistPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
// Women
portraitsFile << "\t\t\tfemale = {\n";
for (const auto& portrait: femaleIdeologicalPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
portraitsFile << "\t\t}\n";
// Democracy
portraitsFile << "\t\tdemocratic = {\n";
// Men
const auto& maleDemocraticPortraits = theCountry.getMaleDemocraticPortraits();
portraitsFile << "\t\t\tmale = {\n";
for (const auto& portrait: maleDemocraticPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
// Women
portraitsFile << "\t\t\tfemale = {\n";
for (const auto& portrait: femaleIdeologicalPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
portraitsFile << "\t\t}\n";
// Fascism
portraitsFile << "\t\tfascism = {\n";
// Men
const auto& maleFascistPortraits = theCountry.getMaleFascistPortraits();
portraitsFile << "\t\t\tmale = {\n";
for (const auto& portrait: maleFascistPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
// Women
portraitsFile << "\t\t\tfemale = {\n";
for (const auto& portrait: femaleIdeologicalPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
portraitsFile << "\t\t}\n";
// Absolutism
portraitsFile << "\t\tabsolutist = {\n";
// Men
const auto& maleAbsolutistPortraits = theCountry.getMaleAbsolutistPortraits();
portraitsFile << "\t\t\tmale = {\n";
for (const auto& portrait: maleAbsolutistPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
// Women
portraitsFile << "\t\t\tfemale = {\n";
for (const auto& portrait: femaleMonarchPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
portraitsFile << "\t\t}\n";
// Neutrality
portraitsFile << "\t\tneutrality = {\n";
// Men
const auto& maleNeutralPortraits = theCountry.getMaleNeutralPortraits();
portraitsFile << "\t\t\tmale = {\n";
for (const auto& portrait: maleNeutralPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
// Women
portraitsFile << "\t\t\tfemale = {\n";
for (const auto& portrait: femaleIdeologicalPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
portraitsFile << "\t\t}\n";
// Radical
portraitsFile << "\t\tradical = {\n";
// Men
const auto& maleRadicalPortraits = theCountry.getMaleRadicalPortraits();
portraitsFile << "\t\t\tmale = {\n";
for (const auto& portrait: maleRadicalPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
// Women
portraitsFile << "\t\t\tfemale = {\n";
for (const auto& portrait: femaleIdeologicalPortraits)
{
portraitsFile << "\t\t\t\t\"" << portrait << "\"\n";
}
portraitsFile << "\t\t\t}\n";
portraitsFile << "\t\t}\n";
portraitsFile << "\t}\n";
// Operatives
portraitsFile << "\toperative = {\n";
// Men
portraitsFile << "\t\tmale = {\n";
for (const auto& operative: theCountry.getOperatives())
{
if (!operative.isFemale())
portraitsFile << "\t\t\t\"" << operative.getPortrait() << "\"\n";
}
portraitsFile << "\t\t}\n";
// Women
portraitsFile << "\t\tfemale = {\n";
for (const auto& operative: theCountry.getOperatives())
{
if (operative.isFemale())
portraitsFile << "\t\t\t\"" << operative.getPortrait() << "\"\n";
}
portraitsFile << "\t\t}\n";
portraitsFile << "\t}\n";
// End
portraitsFile << "}\n\n";
}
void outputHistory(const HoI4::Country& theCountry, const Configuration& theConfiguration);
void outputOOB(const std::vector<HoI4::DivisionTemplateType>& divisionTemplates,
const HoI4::Country& theCountry,
const Configuration& theConfiguration);
void outputCommonCountryFile(const HoI4::Country& theCountry, const Configuration& theConfiguration);
void outputAdvisorIdeas(const std::string& tag,
const std::set<HoI4::Advisor>& ideologicalAdvisors,
const Configuration& theConfiguration);
void HoI4::outputCountry(const std::set<Advisor>& ideologicalMinisters,
const std::vector<DivisionTemplateType>& divisionTemplates,
const Country& theCountry,
const Configuration& theConfiguration)
{
if (theCountry.getCapitalState())
{
outputHistory(theCountry, theConfiguration);
outputOOB(divisionTemplates, theCountry, theConfiguration);
outputCommonCountryFile(theCountry, theConfiguration);
outputAdvisorIdeas(theCountry.getTag(), ideologicalMinisters, theConfiguration);
outputAIStrategy(theCountry, theConfiguration.getOutputName());
if (auto nationalFocus = theCountry.getNationalFocus(); nationalFocus)
{
outputFocusTree(*nationalFocus,
"output/" + theConfiguration.getOutputName() + "/common/national_focus/" + theCountry.getTag() +
"_NF.txt");
}
}
}
void outputCapital(std::ostream& output, const std::optional<int>& capitalStateNum);
void outputResearchSlots(std::ostream& output, bool greatPower, bool civilized, bool unrecognized);
void outputThreat(std::ostream& output, const double& threat);
void outputWars(std::ostream& output, const std::vector<HoI4::War>& wars);
void outputOOBLines(std::ostream& output, const std::string& tag);
void outputFlags(std::ostream& output, const std::set<std::string>& flags);
void outputConvoys(std::ostream& output, const int& convoys);
void outputEquipmentStockpile(std::ostream& output,
const std::map<std::string, unsigned int>& equipmentStockpile,
const std::string& tag);
void outputPuppets(std::ostream& output,
const std::string& tag,
const std::string& governmentIdeology,
const std::map<std::string, std::string>& puppets,
const std::shared_ptr<HoI4::Country> puppetMaster);
void outputAlliances(std::ostream& output, const std::set<std::string>& allies);
void outputPolitics(std::ostream& output,
const std::string& governmentIdeology,
const date& lastElection,
const bool& areElectionsAllowed,
const std::map<std::string, int>& ideologySupport);
void outputRelations(std::ostream& output,
const std::string& tag,
const std::map<std::string, HoI4::Relations>& relations);
void outputFactions(std::ostream& output, const std::string& tag, const std::optional<HoI4::Faction>& faction);
void outputIdeas(std::ostream& output,
const bool& greatPower,
const bool& civilized,
const std::set<std::string>& ideas,
const std::string& mobilizationLaw,
const std::string& economicLaw,
const std::string& tradeLaw,
const std::string& primaryCulture,
const bool navalTreatyAdherent,
const bool greatestNavalPower,
std::optional<int> numAdherents,
const std::vector<std::string>& unbuiltCanals);
void outputStability(std::ostream& output, const int& stability);
void outputWarSupport(std::ostream& output, const int& warSupport);
void outputCommanders(std::ostream& output,
const std::vector<HoI4::General>& generals,
const std::vector<HoI4::Admiral>& admirals);
void outputOperatives(std::ostream& output,
const HoI4::Country& theCountry,
const std::vector<HoI4::Operative>& operatives);
void outputGlobalEventTargets(std::ostream& output, const std::set<std::string>& eventTargets);
void outputHistory(const HoI4::Country& theCountry, const Configuration& theConfiguration)
{
const auto& tag = theCountry.getTag();
const auto& governmentIdeology = theCountry.getGovernmentIdeology();
const auto& primaryCulture = theCountry.getPrimaryCulture();
std::ofstream output("output/" + theConfiguration.getOutputName() + "/history/countries/" +
commonItems::normalizeUTF8Path(theCountry.getFilename()));
if (!output.is_open())
{
throw std::runtime_error("Could not open output/" + theConfiguration.getOutputName() + "/history/countries/" +
commonItems::normalizeUTF8Path(theCountry.getFilename()));
}
output << "\xEF\xBB\xBF"; // add the BOM to make HoI4 happy
outputCapital(output, theCountry.getCapitalState());
if (theCountry.isGreatPower())
{
output << "set_major = yes\n";
}
outputResearchSlots(output, theCountry.isGreatPower(), theCountry.isCivilized(), theCountry.isUnrecognizedNation());
outputThreat(output, theCountry.getThreat());
outputWars(output, theCountry.getWars());
outputOOBLines(output, tag);
if (const auto& theTechnologies = theCountry.getTechnologies(); theTechnologies)
{
outputTechnology(*theTechnologies, output);
outputResearchBonuses(*theTechnologies, output);
}
outputFlags(output, theCountry.getFlags());
outputConvoys(output, theCountry.getConvoys());
outputEquipmentStockpile(output, theCountry.getEquipmentStockpile(), tag);
outputPolitics(output,
governmentIdeology,
theCountry.getLastElection(),
theCountry.areElectionsAllowed(),
theCountry.getIdeologySupport());
outputPuppets(output, tag, governmentIdeology, theCountry.getPuppets(), theCountry.getPuppetMaster());
outputAlliances(output, theCountry.getAllies());
outputRelations(output, tag, theCountry.getRelations());
outputFactions(output, tag, theCountry.getFaction());
outputIdeas(output,
theCountry.isGreatPower(),
theCountry.isCivilized(),
theCountry.getIdeas(),
theCountry.getMobilizationLaw(),
theCountry.getEconomicLaw(),
theCountry.getTradeLaw(),
primaryCulture,
theCountry.isNavalTreatyAdherent(),
theCountry.isGreatestNavalPower(),
theCountry.getNumAdherents(),
theCountry.getUnbuiltCanals());
if (theCountry.hasProvinces())
{
outputStability(output, theCountry.getStability());
outputWarSupport(output, theCountry.getWarSupport());
}
for (const auto& leader: theCountry.getLeaders())
{
HoI4::outputCountryLeader(output, leader);
}
outputCommanders(output, theCountry.getGenerals(), theCountry.getAdmirals());
outputOperatives(output, theCountry, theCountry.getOperatives());
output << theCountry.getTheShipVariants();
outputGlobalEventTargets(output, theCountry.getGlobalEventTargets());
output.close();
}
void outputCapital(std::ostream& output, const std::optional<int>& capitalStateNum)
{
if (capitalStateNum)
{
output << "capital = " << *capitalStateNum << '\n';
}
else
{
output << "capital = 1\n";
}
}
void outputResearchSlots(std::ostream& output, bool greatPower, bool civilized, bool unrecognized)
{
if (greatPower)
{
output << "set_research_slots = 4\n";
}
else if (civilized)
{
output << "set_research_slots = 3\n";
}
else if (unrecognized)
{
output << "set_research_slots = 0\n";
}
else
{
output << "set_research_slots = 2\n";
}
}
void outputThreat(std::ostream& output, const double& threat)
{
if (threat > std::numeric_limits<float>::epsilon())
{
output << "add_named_threat = { threat = " << threat << " name = infamy }\n";
}
output << "\n";
}
void outputWars(std::ostream& output, const std::vector<HoI4::War>& wars)
{
for (const auto& war: wars)
{
output << war;
}
}
void outputOOBLines(std::ostream& output, const std::string& tag)
{
output << "oob = \"" << tag << "_OOB\"\n";
output << "if = {\n";
output << "\tlimit = { has_dlc = \"Man the Guns\" }\n";
output << "\t\tset_naval_oob = \"" << tag << "_1936_naval_mtg\"\n";
output << "\telse = { \n";
output << "\t\tset_naval_oob = \"" << tag << "_1936_naval_legacy\"\n";
output << "\t}\n";
output << "}\n";
output << "\n";
}
void outputFlags(std::ostream& output, const std::set<std::string>& flags)
{
if (!flags.empty())
{
output << "\n";
}
for (const auto& flag: flags)
{
output << "set_country_flag = " << flag << "\n";
}
}
void outputConvoys(std::ostream& output, const int& convoys)
{
output << "set_convoys = " << convoys << '\n';
output << "\n";
}
void outputEquipmentStockpile(std::ostream& output,
const std::map<std::string, unsigned int>& equipmentStockpile,
const std::string& tag)
{
for (const auto& [type, amount]: equipmentStockpile)
{
if (amount > 0)
{
output << "add_equipment_to_stockpile = ";
output << "{ type = " << type << " amount = " << amount << " producer = " << tag << " }\n";
}
}
output << "\n";
}
void outputPolitics(std::ostream& output,
const std::string& governmentIdeology,
const date& lastElection,
const bool& areElectionsAllowed,
const std::map<std::string, int>& ideologySupport)
{
output << "set_politics = {\n";
output << " ruling_party = " << governmentIdeology << "\n";
output << " last_election = \"" << lastElection << "\"\n";
output << " election_frequency = 48\n";
if (areElectionsAllowed)
{
output << " elections_allowed = yes\n";
}
else
{
output << " elections_allowed = no\n";
}
output << "}\n";
output << "\n";
output << "set_popularities = {\n";
for (const auto& ideology: ideologySupport)
{
output << "\t" << ideology.first << " = " << ideology.second << "\n";
}
output << "}\n";
output << "\n";
}
void outputPuppets(std::ostream& output,
const std::string& tag,
const std::string& governmentIdeology,
const std::map<std::string, std::string>& puppets,
const std::shared_ptr<HoI4::Country> puppetMaster)
{
if (!puppets.empty())
{
output << "# DIPLOMACY\n";
output << "if = {\n";
output << " limit = {\n";
output << " has_dlc = \"Together for Victory\"\n";
output << " }\n";
for (const auto& [puppet, level]: puppets)
{
if (governmentIdeology == "fascism")
{
output << " set_autonomy = {\n";
output << " target = " << puppet << "\n";
output << " autonomous_state = autonomy_integrated_puppet\n";
}
else
{
output << " set_autonomy = {\n";
output << " target = " << puppet << "\n";
output << " autonomous_state = " << level << "\n";
output << " freedom_level = 0.4\n";
}
output << " }\n";
}
output << " else = {\n";
for (const auto& puppet: puppets | std::views::keys)
{
if (governmentIdeology == "fascism")
{
output << " set_autonomy = {\n";
output << " target = " << puppet << "\n";
output << " autonomous_state = autonomy_puppet\n";
output << " }\n";
}
else
{
output << " puppet = " << puppet << "\n";
}
}
output << " }\n";
output << "}\n";
output << "\n";
output << "if = {\n";
output << " limit = {has_dlc = \"Together for Victory\" }\n";
output << "\n";
output << " add_to_tech_sharing_group = " << tag << "_research\n";
output << "}\n\n";
}
if (puppetMaster)
{
output << "if = {\n";
output << " limit = {has_dlc = \"Together for Victory\" }\n";
output << "\n";
output << " add_to_tech_sharing_group = " << puppetMaster->getTag() << "_research\n";
output << "}\n\n";
}
}
void outputAlliances(std::ostream& output, const std::set<std::string>& allies)
{
for (const auto& ally: allies)
{
output << "give_guarantee = " << ally << "\n";
output << "diplomatic_relation = { country = " << ally << " relation = non_aggression_pact }\n";
output << "\n";
}
}
void outputRelations(std::ostream& output,
const std::string& tag,
const std::map<std::string, HoI4::Relations>& relations)
{
for (const auto& [relationTarget, relation]: relations)
{
if (relationTarget == tag)
{
continue;
}
if (relation.getRelations() != 0)
{
output << "add_opinion_modifier = { target = " << relationTarget << " modifier = ";
const auto relationsValue = relation.getRelations();
if (relationsValue < 0)
{
output << "negative_";
}
else
{
output << "positive_";
}
output << abs(relationsValue) << " }\n";
}
if (relation.hasMilitaryAccess())
{
output << "give_military_access = " << relationTarget << "\n";
}
if (const auto& truceDuration = relation.getTruceDuration(); truceDuration)
{
output << "set_truce = { target = " << relationTarget << " days = " << *truceDuration << " }\n";
}
}
output << "\n";
}
void outputFactions(std::ostream& output, const std::string& tag, const std::optional<HoI4::Faction>& faction)
{
if (faction && (faction->getLeader()->getTag() == tag))
{
const std::string allianceName = faction->getFactionName().has_value()
? faction->getFactionName().value()
: ("\"Alliance Of [" + tag + ".GetName]\"");
output << "create_faction = " + allianceName + "\n";
for (const auto& factionMember: faction->getMembers())
{
output << "add_to_faction = " + factionMember->getTag() + "\n";
}
}
output << '\n';
}
void outputIdeas(std::ostream& output,
const bool& greatPower,
const bool& civilized,
const std::set<std::string>& ideas,
const std::string& mobilizationLaw,
const std::string& economicLaw,
const std::string& tradeLaw,
const std::string& primaryCulture,
const bool navalTreatyAdherent,
const bool greatestNavalPower,
std::optional<int> numAdherents,
const std::vector<std::string>& unbuiltCanals)
{
if (navalTreatyAdherent)
{
output << "if = {\n";
output << "\tlimit = { has_dlc = \"Man the Guns\" }\n";
output << "\tadd_ideas = MTG_naval_treaty_adherent\n";
if (greatestNavalPower)
{
output << "\tset_global_flag = MTG_second_london_conference\n";
}
if (numAdherents)
{
output << "\tset_global_flag = { flag = MTG_naval_treaty_signatories value = " << *numAdherents << " }\n";
}
output << "}\n";
}
for (const auto& unbuiltCanal: unbuiltCanals)
{
output << "set_global_flag = " << unbuiltCanal << "\n";
}
output << "add_ideas = {\n";
if (greatPower)
{
output << "\tgreat_power\n";
}
if (!civilized)
{
output << "\tuncivilized\n";
}
for (const auto& idea: ideas)
{
output << "\t" << idea << "\n";
}
output << "\t" << mobilizationLaw << "\n";
output << "\t" << economicLaw << "\n";
output << "\t" << tradeLaw << "\n";
output << "\tculture_" << primaryCulture << "\n";
output << "}\n";
}
void outputStability(std::ostream& output, const int& stability)
{
output << "set_stability = 0." << stability << "\n";
}
void outputWarSupport(std::ostream& output, const int& warSupport)
{
output << "set_war_support = 0." << warSupport << "\n";
}
void outputCommanders(std::ostream& output,
const std::vector<HoI4::General>& generals,
const std::vector<HoI4::Admiral>& admirals)
{
for (const auto& general: generals)
{
output << general;
output << "\n";
}
for (const auto& admiral: admirals)
{
output << admiral;
output << "\n";
}
}
void outputOperatives(std::ostream& output,
const HoI4::Country& theCountry,
const std::vector<HoI4::Operative>& operatives)
{
if (operatives.empty())
{
return;
}
output << "if = {\n";
output << "\tlimit = {\n";
output << "\t\thas_dlc = \"La Resistance\"\n";
output << "\t}\n";
if (theCountry.getPuppetMaster()) // Prevents colonies from having more than 1 wrong ethnic operative
{
output << operatives[0] << "\n";
}
else
{
for (const auto& operative: operatives)
{
output << operative;
output << "\n";
}
}
output << "}\n";
}
void outputOOB(const std::vector<HoI4::DivisionTemplateType>& divisionTemplates,
const HoI4::Country& theCountry,
const Configuration& theConfiguration)
{
const auto& tag = theCountry.getTag();
std::ofstream output("output/" + theConfiguration.getOutputName() + "/history/units/" + tag + "_OOB.txt");
if (!output.is_open())
{
throw std::runtime_error(
"Could not open output/" + theConfiguration.getOutputName() + "/history/units/" + tag + "_OOB.txt");
}
output << "\xEF\xBB\xBF"; // add the BOM to make HoI4 happy
output << "start_equipment_factor = 0\n";
for (auto& divisionTemplate: divisionTemplates)
{
output << divisionTemplate;
output << "\n";
}
const auto& technologies = theCountry.getTechnologies();
if (technologies)
{
output << "### No BHU air forces ###\n";
output << "instant_effect = {\n";
if (technologies->hasTechnology("infantry_weapons1"))
{
output << "\tadd_equipment_production = {\n";
output << "\t\tequipment = {\n";
output << "\t\t\ttype = infantry_equipment_1\n";
output << "\t\t\tcreator = \"" << tag << "\"\n";
output << "\t\t}\n";
output << "\t\trequested_factories = 5\n";
output << "\t\tprogress = 0.88\n";
output << "\t\tefficiency = 100\n";
output << "\t}\n";
}
else
{
output << "\tadd_equipment_production = {\n";
output << "\t\tequipment = {\n";
output << "\t\t\ttype = infantry_equipment_0\n";
output << "\t\t\tcreator = \"" << tag << "\"\n";
output << "\t\t}\n";
output << "\t\trequested_factories = 5\n";
output << "\t\tprogress = 0.88\n";
output << "\t\tefficiency = 100\n";
output << "\t}\n";
}
if (technologies->hasTechnology("gw_artillery"))
{
output << "\tadd_equipment_production = {\n";
output << "\t\tequipment = {\n";
output << "\t\t\ttype = artillery_equipment_1\n";
output << "\t\t\tcreator = \"" << tag << "\"\n";
output << "\t\t}\n";
output << "\t\trequested_factories = 2\n";
output << "\t\tprogress = 0.88\n";
output << "\t\tefficiency = 100\n";
output << "\t}\n";
}
if (technologies->hasTechnology("fighter1"))
{
output << "\tadd_equipment_production = {\n";
output << "\t\tequipment = {\n";
output << "\t\t\ttype = fighter_equipment_1\n";
output << "\t\t\tcreator = \"" << tag << "\"\n";
output << "\t\t}\n";
output << "\t\trequested_factories = 5\n";
output << "\t\tprogress = 0.88\n";
output << "\t\tefficiency = 100\n";
output << "\t}\n";
}
else if (technologies->hasTechnology("early_fighter"))
{
output << "\tadd_equipment_production = {\n";
output << "\t\tequipment = {\n";
output << "\t\t\ttype = fighter_equipment_0\n";
output << "\t\t\tcreator = \"" << tag << "\"\n";
output << "\t\t}\n";
output << "\t\trequested_factories = 5\n";
output << "\t\tprogress = 0.88\n";
output << "\t\tefficiency = 100\n";
output << "\t}\n";
}
}
output << "\tadd_equipment_production = {\n";
output << "\t\tequipment = {\n";
output << "\t\t\ttype = convoy_1\n";
output << "\t\t\tcreator = \"" << tag << "\"\n";
output << "\t\t}\n";
output << "\t\trequested_factories = 10\n";
output << "\t\tprogress = 0.50\n";
output << "\t\tamount = 100\n";
output << "\t}\n";
output << "}\n";
output << "units = {\n";
output << theCountry.getArmy();
output << "}\n";
if (auto& planes = theCountry.getPlanes(); !planes.empty())
{
output << "air_wings = {\n";
output << "\t" << *theCountry.getCapitalState() << " = {\n";
for (auto& plane: planes)
{
output << plane;
}
output << "\t}\n";
output << "}\n";
}
output.close();
auto& navies = theCountry.getNavies();
std::ofstream legacyNavy(
"output/" + theConfiguration.getOutputName() + "/history/units/" + tag + "_1936_naval_legacy.txt");
outputLegacyNavies(navies, *technologies, tag, legacyNavy);
std::ofstream mtgNavy(
"output/" + theConfiguration.getOutputName() + "/history/units/" + tag + "_1936_naval_mtg.txt");
outputMtgNavies(navies, *technologies, tag, mtgNavy);
}
void outputCommonCountryFile(const HoI4::Country& theCountry, const Configuration& theConfiguration)
{
const auto& commonCountryFile = theCountry.getCommonCountryFile();
std::ofstream output("output/" + theConfiguration.getOutputName() + "/common/countries/" +
commonItems::normalizeUTF8Path(commonCountryFile));
if (!output.is_open())
{
throw std::runtime_error("Could not open output/" + theConfiguration.getOutputName() + "/common/countries/" +
commonItems::normalizeUTF8Path(commonCountryFile));
}
auto& graphicalCulture = theCountry.getGraphicalCulture();
auto& graphicalCulture2d = theCountry.getGraphicalCulture2d();
if (!graphicalCulture.empty() && !graphicalCulture2d.empty())
{
output << "graphical_culture = " << graphicalCulture << "\n";
output << "graphical_culture_2d = " << graphicalCulture2d << "\n";
}
output << "color " << theCountry.getColor() << "\n";
output.close();
}
void outputAdvisorIdeas(const std::string& tag,
const std::set<HoI4::Advisor>& ideologicalAdvisors,
const Configuration& theConfiguration)
{
std::ofstream ideasFile("output/" + theConfiguration.getOutputName() + "/common/ideas/" + tag + ".txt");
if (!ideasFile.is_open())
{
throw std::runtime_error(
"Could not open output/" + theConfiguration.getOutputName() + "/common/ideas/" + tag + ".txt");
}
ideasFile << "ideas = {\n";
ideasFile << "\tpolitical_advisor = {\n";
for (auto& ideologicalAdvisor: ideologicalAdvisors)
{
outputAdvisor(ideasFile, tag, ideologicalAdvisor);
}
ideasFile << "\t}\n";
ideasFile << "\t# TECHNOLOGY\n";
ideasFile << "\ttank_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\tdesigner = yes\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_tank_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_tank_manufacturer_1\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = tank_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tarmor = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { tank_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\t}\n";
ideasFile << "\n";
ideasFile << "\tnaval_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\tdesigner = yes\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_naval_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_naval_manufacturer_1\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = naval_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tnaval_equipment = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { naval_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\t}\n";
ideasFile << "\n";
ideasFile << "\taircraft_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\tdesigner = yes\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_light_aircraft_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_air_manufacturer_1\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = light_aircraft_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tair_equipment = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { light_aircraft_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_medium_aircraft_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_air_manufacturer_3\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = medium_aircraft_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tair_equipment = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { medium_aircraft_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_heavy_aircraft_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_air_manufacturer_2\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = heavy_aircraft_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tair_equipment = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { heavy_aircraft_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_naval_aircraft_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_naval_manufacturer_2\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = naval_aircraft_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tair_equipment = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { naval_aircraft_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\t}\n";
ideasFile << "\n";
ideasFile << "\tindustrial_concern = {\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_industrial_concern = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_industrial_concern_1\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = industrial_concern limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tindustry = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { industrial_concern }\n";
ideasFile << "\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_electronics_concern = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_electronics_concern_1\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = electronics_concern limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\telectronics = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { electronics_concern }\n";
ideasFile << "\t\t}\n";
ideasFile << "\t}\n";
ideasFile << "\n";
ideasFile << "\tmateriel_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\tdesigner = yes\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_motorized_equipment_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_motorized_equipment_manufacturer_3\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = motorized_equipment_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tmotorized_equipment = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { motorized_equipment_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_infantry_equipment_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_infantry_equipment_manufacturer_2\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = infantry_equipment_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tinfantry_weapons = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { infantry_equipment_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t" << tag << "_artillery_manufacturer = {\n";
ideasFile << "\n";
ideasFile << "\t\t\tpicture = generic_artillery_manufacturer_2\n";
ideasFile << "\n";
ideasFile << "\t\t\tallowed = {\n";
ideasFile << "\t\t\t\toriginal_tag = " << tag << "\n";
ideasFile << "\t\t\t\tNOT = {\n";
ideasFile << "\t\t\t\t\thas_available_idea_with_traits = { idea = artillery_manufacturer limit = 1 }\n";
ideasFile << "\t\t\t\t}\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\tcost = 150\n";
ideasFile << "\t\t\tremoval_cost = 10\n";
ideasFile << "\n";
ideasFile << "\t\t\tresearch_bonus = {\n";
ideasFile << "\t\t\t\tartillery = 0.15\n";
ideasFile << "\t\t\t}\n";
ideasFile << "\n";
ideasFile << "\t\t\ttraits = { artillery_manufacturer }\n";
ideasFile << "\t\t}\n";
ideasFile << "\t}\n";
ideasFile << "}\n";
}
void HoI4::reportIndustry(std::ostream& out, const Country& theCountry)
{
if (theCountry.hasProvinces())
{
out << theCountry.getTag() << ',';
out << theCountry.getMilitaryFactories() << ',';
out << theCountry.getCivilianFactories() << ',';
out << theCountry.getDockyards() << ',';
out << theCountry.getMilitaryFactories() + theCountry.getCivilianFactories() + theCountry.getDockyards() << '\n';
}
}
void outputGlobalEventTargets(std::ostream& output, const std::set<std::string>& eventTargets)
{
for (const auto& eventTarget: eventTargets)
{
output << "save_global_event_target_as = " << eventTarget << "\n";
}
}
| 31.478357 | 117 | 0.638154 | [
"vector"
] |
102e1b0676d72fecfdf9846a5a883ba9be2ae83e | 1,044 | cpp | C++ | inference-engine/tests/functional/plugin/myriad/shared_tests_instances/skip_tests_config.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 2 | 2021-02-26T15:46:19.000Z | 2021-05-16T20:48:13.000Z | inference-engine/tests/functional/plugin/myriad/shared_tests_instances/skip_tests_config.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 1 | 2020-12-22T05:01:12.000Z | 2020-12-23T09:49:43.000Z | inference-engine/tests/functional/plugin/myriad/shared_tests_instances/skip_tests_config.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include <string>
#include "functional_test_utils/skip_tests_config.hpp"
std::vector<std::string> disabledTestPatterns() {
return {
// Not supported activation types
".*ActivationLayerTest\\.CompareWithRefs/Tanh.*netPRC=FP32.*",
".*ActivationLayerTest\\.CompareWithRefs/Exp.*netPRC=FP32.*",
".*ActivationLayerTest\\.CompareWithRefs/Log.*netPRC=FP32.*",
".*ActivationLayerTest\\.CompareWithRefs/Sigmoid.*netPRC=FP32.*",
".*ActivationLayerTest\\.CompareWithRefs/Relu.*netPRC=FP32.*",
// TODO: Issue: 26268
".*ConcatLayerTest.*axis=0.*",
// TODO: Issue 31197
R"(.*(IEClassBasicTestP).*smoke_registerPluginsXMLUnicodePath.*)",
// TODO: Issue: 34206
R"(.*(IEClassLoadNetwork).*(QueryNetworkMULTIWithHETERONoThrow_V10|QueryNetworkHETEROWithMULTINoThrow_V10).*)",
// TODO: Issue: 34348
R"(.*IEClassGetAvailableDevices.*)",
};
}
| 37.285714 | 119 | 0.666667 | [
"vector"
] |
1036811ca02c3f41cf3d3ce2620924236fa9d23c | 31,733 | cpp | C++ | Chapter08/chapter8_tutorials/universal_robot/ur_kinematics/src/ur_moveit_plugin.cpp | PacktPublishing/Robot-Operating-System-Cookbook | d94ef672a483782922ca8b134f6de749af8e0a10 | [
"MIT"
] | 53 | 2018-09-13T05:11:03.000Z | 2022-02-28T04:09:58.000Z | Chapter08/chapter8_tutorials/universal_robot/ur_kinematics/src/ur_moveit_plugin.cpp | PacktPublishing/Robot-Operating-System-Cookbook | d94ef672a483782922ca8b134f6de749af8e0a10 | [
"MIT"
] | 2 | 2018-09-30T08:32:22.000Z | 2019-04-12T13:37:43.000Z | Chapter08/chapter8_tutorials/universal_robot/ur_kinematics/src/ur_moveit_plugin.cpp | PacktPublishing/Robot-Operating-System-Cookbook | d94ef672a483782922ca8b134f6de749af8e0a10 | [
"MIT"
] | 31 | 2018-09-16T06:05:13.000Z | 2021-09-10T18:10:37.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Georgia Tech
* 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 Georgia Tech nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Kelsey Hawkins */
/* Based on orignal source from Willow Garage. License copied below */
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, 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 the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Sachin Chitta, David Lu!!, Ugo Cupcic */
#include <class_loader/class_loader.h>
//#include <tf/transform_datatypes.h>
#include <tf_conversions/tf_kdl.h>
#include <kdl_parser/kdl_parser.hpp>
// URDF, SRDF
#include <urdf_model/model.h>
#include <srdfdom/model.h>
#include <moveit/rdf_loader/rdf_loader.h>
// UR kin
#include <ur_kinematics/ur_moveit_plugin.h>
#include <ur_kinematics/ur_kin.h>
//register KDLKinematics as a KinematicsBase implementation
CLASS_LOADER_REGISTER_CLASS(ur_kinematics::URKinematicsPlugin, kinematics::KinematicsBase)
namespace ur_kinematics
{
URKinematicsPlugin::URKinematicsPlugin():active_(false) {}
void URKinematicsPlugin::getRandomConfiguration(KDL::JntArray &jnt_array, bool lock_redundancy) const
{
std::vector<double> jnt_array_vector(dimension_, 0.0);
state_->setToRandomPositions(joint_model_group_);
state_->copyJointGroupPositions(joint_model_group_, &jnt_array_vector[0]);
for (std::size_t i = 0; i < dimension_; ++i)
{
if (lock_redundancy)
if (isRedundantJoint(i))
continue;
jnt_array(i) = jnt_array_vector[i];
}
}
bool URKinematicsPlugin::isRedundantJoint(unsigned int index) const
{
for (std::size_t j=0; j < redundant_joint_indices_.size(); ++j)
if (redundant_joint_indices_[j] == index)
return true;
return false;
}
void URKinematicsPlugin::getRandomConfiguration(const KDL::JntArray &seed_state,
const std::vector<double> &consistency_limits,
KDL::JntArray &jnt_array,
bool lock_redundancy) const
{
std::vector<double> values(dimension_, 0.0);
std::vector<double> near(dimension_, 0.0);
for (std::size_t i = 0 ; i < dimension_; ++i)
near[i] = seed_state(i);
// Need to resize the consistency limits to remove mimic joints
std::vector<double> consistency_limits_mimic;
for(std::size_t i = 0; i < dimension_; ++i)
{
if(!mimic_joints_[i].active)
continue;
consistency_limits_mimic.push_back(consistency_limits[i]);
}
joint_model_group_->getVariableRandomPositionsNearBy(state_->getRandomNumberGenerator(), values, near, consistency_limits_mimic);
for (std::size_t i = 0; i < dimension_; ++i)
{
bool skip = false;
if (lock_redundancy)
for (std::size_t j = 0; j < redundant_joint_indices_.size(); ++j)
if (redundant_joint_indices_[j] == i)
{
skip = true;
break;
}
if (skip)
continue;
jnt_array(i) = values[i];
}
}
bool URKinematicsPlugin::checkConsistency(const KDL::JntArray& seed_state,
const std::vector<double> &consistency_limits,
const KDL::JntArray& solution) const
{
for (std::size_t i = 0; i < dimension_; ++i)
if (fabs(seed_state(i) - solution(i)) > consistency_limits[i])
return false;
return true;
}
bool URKinematicsPlugin::initialize(const std::string &robot_description,
const std::string& group_name,
const std::string& base_frame,
const std::string& tip_frame,
double search_discretization)
{
setValues(robot_description, group_name, base_frame, tip_frame, search_discretization);
ros::NodeHandle private_handle("~");
rdf_loader::RDFLoader rdf_loader(robot_description_);
const boost::shared_ptr<srdf::Model> &srdf = rdf_loader.getSRDF();
#if ROS_VERSION_MINIMUM(1, 13, 0)
const std::shared_ptr<urdf::ModelInterface>& urdf_model = rdf_loader.getURDF();
#else
const boost::shared_ptr<urdf::ModelInterface>& urdf_model = rdf_loader.getURDF();
#endif
if (!urdf_model || !srdf)
{
ROS_ERROR_NAMED("kdl","URDF and SRDF must be loaded for KDL kinematics solver to work.");
return false;
}
robot_model_.reset(new robot_model::RobotModel(urdf_model, srdf));
robot_model::JointModelGroup* joint_model_group = robot_model_->getJointModelGroup(group_name);
if (!joint_model_group)
return false;
if(!joint_model_group->isChain())
{
ROS_ERROR_NAMED("kdl","Group '%s' is not a chain", group_name.c_str());
return false;
}
if(!joint_model_group->isSingleDOFJoints())
{
ROS_ERROR_NAMED("kdl","Group '%s' includes joints that have more than 1 DOF", group_name.c_str());
return false;
}
KDL::Tree kdl_tree;
if (!kdl_parser::treeFromUrdfModel(*urdf_model, kdl_tree))
{
ROS_ERROR_NAMED("kdl","Could not initialize tree object");
return false;
}
if (!kdl_tree.getChain(base_frame_, getTipFrame(), kdl_chain_))
{
ROS_ERROR_NAMED("kdl","Could not initialize chain object");
return false;
}
dimension_ = joint_model_group->getActiveJointModels().size() + joint_model_group->getMimicJointModels().size();
for (std::size_t i=0; i < joint_model_group->getJointModels().size(); ++i)
{
if(joint_model_group->getJointModels()[i]->getType() == moveit::core::JointModel::REVOLUTE || joint_model_group->getJointModels()[i]->getType() == moveit::core::JointModel::PRISMATIC)
{
ik_chain_info_.joint_names.push_back(joint_model_group->getJointModelNames()[i]);
const std::vector<moveit_msgs::JointLimits> &jvec = joint_model_group->getJointModels()[i]->getVariableBoundsMsg();
ik_chain_info_.limits.insert(ik_chain_info_.limits.end(), jvec.begin(), jvec.end());
}
}
fk_chain_info_.joint_names = ik_chain_info_.joint_names;
fk_chain_info_.limits = ik_chain_info_.limits;
if(!joint_model_group->hasLinkModel(getTipFrame()))
{
ROS_ERROR_NAMED("kdl","Could not find tip name in joint group '%s'", group_name.c_str());
return false;
}
ik_chain_info_.link_names.push_back(getTipFrame());
fk_chain_info_.link_names = joint_model_group->getLinkModelNames();
joint_min_.resize(ik_chain_info_.limits.size());
joint_max_.resize(ik_chain_info_.limits.size());
for(unsigned int i=0; i < ik_chain_info_.limits.size(); i++)
{
joint_min_(i) = ik_chain_info_.limits[i].min_position;
joint_max_(i) = ik_chain_info_.limits[i].max_position;
}
// Get Solver Parameters
int max_solver_iterations;
double epsilon;
bool position_ik;
private_handle.param("max_solver_iterations", max_solver_iterations, 500);
private_handle.param("epsilon", epsilon, 1e-5);
private_handle.param(group_name+"/position_only_ik", position_ik, false);
ROS_DEBUG_NAMED("kdl","Looking in private handle: %s for param name: %s",
private_handle.getNamespace().c_str(),
(group_name+"/position_only_ik").c_str());
if(position_ik)
ROS_INFO_NAMED("kdl","Using position only ik");
num_possible_redundant_joints_ = kdl_chain_.getNrOfJoints() - joint_model_group->getMimicJointModels().size() - (position_ik? 3:6);
// Check for mimic joints
bool has_mimic_joints = joint_model_group->getMimicJointModels().size() > 0;
std::vector<unsigned int> redundant_joints_map_index;
std::vector<kdl_kinematics_plugin::JointMimic> mimic_joints;
unsigned int joint_counter = 0;
for (std::size_t i = 0; i < kdl_chain_.getNrOfSegments(); ++i)
{
const robot_model::JointModel *jm = robot_model_->getJointModel(kdl_chain_.segments[i].getJoint().getName());
//first check whether it belongs to the set of active joints in the group
if (jm->getMimic() == NULL && jm->getVariableCount() > 0)
{
kdl_kinematics_plugin::JointMimic mimic_joint;
mimic_joint.reset(joint_counter);
mimic_joint.joint_name = kdl_chain_.segments[i].getJoint().getName();
mimic_joint.active = true;
mimic_joints.push_back(mimic_joint);
++joint_counter;
continue;
}
if (joint_model_group->hasJointModel(jm->getName()))
{
if (jm->getMimic() && joint_model_group->hasJointModel(jm->getMimic()->getName()))
{
kdl_kinematics_plugin::JointMimic mimic_joint;
mimic_joint.reset(joint_counter);
mimic_joint.joint_name = kdl_chain_.segments[i].getJoint().getName();
mimic_joint.offset = jm->getMimicOffset();
mimic_joint.multiplier = jm->getMimicFactor();
mimic_joints.push_back(mimic_joint);
continue;
}
}
}
for (std::size_t i = 0; i < mimic_joints.size(); ++i)
{
if(!mimic_joints[i].active)
{
const robot_model::JointModel* joint_model = joint_model_group->getJointModel(mimic_joints[i].joint_name)->getMimic();
for(std::size_t j=0; j < mimic_joints.size(); ++j)
{
if(mimic_joints[j].joint_name == joint_model->getName())
{
mimic_joints[i].map_index = mimic_joints[j].map_index;
}
}
}
}
mimic_joints_ = mimic_joints;
// Setup the joint state groups that we need
state_.reset(new robot_state::RobotState(robot_model_));
state_2_.reset(new robot_state::RobotState(robot_model_));
// Store things for when the set of redundant joints may change
position_ik_ = position_ik;
joint_model_group_ = joint_model_group;
max_solver_iterations_ = max_solver_iterations;
epsilon_ = epsilon;
private_handle.param<std::string>("arm_prefix", arm_prefix_, "");
ur_joint_names_.push_back(arm_prefix_ + "shoulder_pan_joint");
ur_joint_names_.push_back(arm_prefix_ + "shoulder_lift_joint");
ur_joint_names_.push_back(arm_prefix_ + "elbow_joint");
ur_joint_names_.push_back(arm_prefix_ + "wrist_1_joint");
ur_joint_names_.push_back(arm_prefix_ + "wrist_2_joint");
ur_joint_names_.push_back(arm_prefix_ + "wrist_3_joint");
ur_link_names_.push_back(arm_prefix_ + "base_link"); // 0
ur_link_names_.push_back(arm_prefix_ + "ur_base_link"); // 1
ur_link_names_.push_back(arm_prefix_ + "shoulder_link"); // 2
ur_link_names_.push_back(arm_prefix_ + "upper_arm_link"); // 3
ur_link_names_.push_back(arm_prefix_ + "forearm_link"); // 4
ur_link_names_.push_back(arm_prefix_ + "wrist_1_link"); // 5
ur_link_names_.push_back(arm_prefix_ + "wrist_2_link"); // 6
ur_link_names_.push_back(arm_prefix_ + "wrist_3_link"); // 7
ur_link_names_.push_back(arm_prefix_ + "ee_link"); // 8
ur_joint_inds_start_ = getJointIndex(ur_joint_names_[0]);
// check to make sure the serial chain is properly defined in the model
int cur_ur_joint_ind, last_ur_joint_ind = ur_joint_inds_start_;
for(int i=1; i<6; i++) {
cur_ur_joint_ind = getJointIndex(ur_joint_names_[i]);
if(cur_ur_joint_ind < 0) {
ROS_ERROR_NAMED("kdl",
"Kin chain provided in model doesn't contain standard UR joint '%s'.",
ur_joint_names_[i].c_str());
return false;
}
if(cur_ur_joint_ind != last_ur_joint_ind + 1) {
ROS_ERROR_NAMED("kdl",
"Kin chain provided in model doesn't have proper serial joint order: '%s'.",
ur_joint_names_[i].c_str());
return false;
}
last_ur_joint_ind = cur_ur_joint_ind;
}
// if successful, the kinematic chain includes a serial chain of the UR joints
kdl_tree.getChain(getBaseFrame(), ur_link_names_.front(), kdl_base_chain_);
kdl_tree.getChain(ur_link_names_.back(), getTipFrame(), kdl_tip_chain_);
// weights for redundant solution selection
ik_weights_.resize(6);
if(private_handle.hasParam("ik_weights")) {
private_handle.getParam("ik_weights", ik_weights_);
} else {
ik_weights_[0] = 1.0;
ik_weights_[1] = 1.0;
ik_weights_[2] = 0.1;
ik_weights_[3] = 0.1;
ik_weights_[4] = 0.3;
ik_weights_[5] = 0.3;
}
active_ = true;
ROS_DEBUG_NAMED("kdl","KDL solver initialized");
return true;
}
bool URKinematicsPlugin::setRedundantJoints(const std::vector<unsigned int> &redundant_joints)
{
if(num_possible_redundant_joints_ < 0)
{
ROS_ERROR_NAMED("kdl","This group cannot have redundant joints");
return false;
}
if(redundant_joints.size() > num_possible_redundant_joints_)
{
ROS_ERROR_NAMED("kdl","This group can only have %d redundant joints", num_possible_redundant_joints_);
return false;
}
std::vector<unsigned int> redundant_joints_map_index;
unsigned int counter = 0;
for(std::size_t i=0; i < dimension_; ++i)
{
bool is_redundant_joint = false;
for(std::size_t j=0; j < redundant_joints.size(); ++j)
{
if(i == redundant_joints[j])
{
is_redundant_joint = true;
counter++;
break;
}
}
if(!is_redundant_joint)
{
// check for mimic
if(mimic_joints_[i].active)
{
redundant_joints_map_index.push_back(counter);
counter++;
}
}
}
for(std::size_t i=0; i < redundant_joints_map_index.size(); ++i)
ROS_DEBUG_NAMED("kdl","Redundant joint map index: %d %d", (int) i, (int) redundant_joints_map_index[i]);
redundant_joints_map_index_ = redundant_joints_map_index;
redundant_joint_indices_ = redundant_joints;
return true;
}
int URKinematicsPlugin::getJointIndex(const std::string &name) const
{
for (unsigned int i=0; i < ik_chain_info_.joint_names.size(); i++) {
if (ik_chain_info_.joint_names[i] == name)
return i;
}
return -1;
}
int URKinematicsPlugin::getKDLSegmentIndex(const std::string &name) const
{
int i=0;
while (i < (int)kdl_chain_.getNrOfSegments()) {
if (kdl_chain_.getSegment(i).getName() == name) {
return i+1;
}
i++;
}
return -1;
}
bool URKinematicsPlugin::timedOut(const ros::WallTime &start_time, double duration) const
{
return ((ros::WallTime::now()-start_time).toSec() >= duration);
}
bool URKinematicsPlugin::getPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
const IKCallbackFn solution_callback = 0;
std::vector<double> consistency_limits;
return searchPositionIK(ik_pose,
ik_seed_state,
default_timeout_,
solution,
solution_callback,
error_code,
consistency_limits,
options);
}
bool URKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
const IKCallbackFn solution_callback = 0;
std::vector<double> consistency_limits;
return searchPositionIK(ik_pose,
ik_seed_state,
timeout,
solution,
solution_callback,
error_code,
consistency_limits,
options);
}
bool URKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
const std::vector<double> &consistency_limits,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
const IKCallbackFn solution_callback = 0;
return searchPositionIK(ik_pose,
ik_seed_state,
timeout,
solution,
solution_callback,
error_code,
consistency_limits,
options);
}
bool URKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
std::vector<double> consistency_limits;
return searchPositionIK(ik_pose,
ik_seed_state,
timeout,
solution,
solution_callback,
error_code,
consistency_limits,
options);
}
bool URKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
const std::vector<double> &consistency_limits,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
return searchPositionIK(ik_pose,
ik_seed_state,
timeout,
solution,
solution_callback,
error_code,
consistency_limits,
options);
}
typedef std::pair<int, double> idx_double;
bool comparator(const idx_double& l, const idx_double& r)
{ return l.second < r.second; }
bool URKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const std::vector<double> &consistency_limits,
const kinematics::KinematicsQueryOptions &options) const
{
ros::WallTime n1 = ros::WallTime::now();
if(!active_) {
ROS_ERROR_NAMED("kdl","kinematics not active");
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
if(ik_seed_state.size() != dimension_) {
ROS_ERROR_STREAM_NAMED("kdl","Seed state must have size " << dimension_ << " instead of size " << ik_seed_state.size());
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
if(!consistency_limits.empty() && consistency_limits.size() != dimension_) {
ROS_ERROR_STREAM_NAMED("kdl","Consistency limits be empty or must have size " << dimension_ << " instead of size " << consistency_limits.size());
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
KDL::JntArray jnt_seed_state(dimension_);
for(int i=0; i<dimension_; i++)
jnt_seed_state(i) = ik_seed_state[i];
solution.resize(dimension_);
KDL::ChainFkSolverPos_recursive fk_solver_base(kdl_base_chain_);
KDL::ChainFkSolverPos_recursive fk_solver_tip(kdl_tip_chain_);
KDL::JntArray jnt_pos_test(jnt_seed_state);
KDL::JntArray jnt_pos_base(ur_joint_inds_start_);
KDL::JntArray jnt_pos_tip(dimension_ - 6 - ur_joint_inds_start_);
KDL::Frame pose_base, pose_tip;
KDL::Frame kdl_ik_pose;
KDL::Frame kdl_ik_pose_ur_chain;
double homo_ik_pose[4][4];
double q_ik_sols[8][6]; // maximum of 8 IK solutions
uint16_t num_sols;
while(1) {
if(timedOut(n1, timeout)) {
ROS_DEBUG_NAMED("kdl","IK timed out");
error_code.val = error_code.TIMED_OUT;
return false;
}
/////////////////////////////////////////////////////////////////////////////
// find transformation from robot base to UR base and UR tip to robot tip
for(uint32_t i=0; i<jnt_pos_base.rows(); i++)
jnt_pos_base(i) = jnt_pos_test(i);
for(uint32_t i=0; i<jnt_pos_tip.rows(); i++)
jnt_pos_tip(i) = jnt_pos_test(i + ur_joint_inds_start_ + 6);
for(uint32_t i=0; i<jnt_seed_state.rows(); i++)
solution[i] = jnt_pos_test(i);
if(fk_solver_base.JntToCart(jnt_pos_base, pose_base) < 0) {
ROS_ERROR_NAMED("kdl", "Could not compute FK for base chain");
return false;
}
if(fk_solver_tip.JntToCart(jnt_pos_tip, pose_tip) < 0) {
ROS_ERROR_NAMED("kdl", "Could not compute FK for tip chain");
return false;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Convert into query for analytic solver
tf::poseMsgToKDL(ik_pose, kdl_ik_pose);
kdl_ik_pose_ur_chain = pose_base.Inverse() * kdl_ik_pose * pose_tip.Inverse();
kdl_ik_pose_ur_chain.Make4x4((double*) homo_ik_pose);
#if KDL_OLD_BUG_FIX
// in older versions of KDL, setting this flag might be necessary
for(int i=0; i<3; i++) homo_ik_pose[i][3] *= 1000; // strange KDL fix
#endif
/////////////////////////////////////////////////////////////////////////////
// Do the analytic IK
num_sols = inverse((double*) homo_ik_pose, (double*) q_ik_sols,
jnt_pos_test(ur_joint_inds_start_+5));
uint16_t num_valid_sols;
std::vector< std::vector<double> > q_ik_valid_sols;
for(uint16_t i=0; i<num_sols; i++)
{
bool valid = true;
std::vector< double > valid_solution;
valid_solution.assign(6,0.0);
for(uint16_t j=0; j<6; j++)
{
if((q_ik_sols[i][j] <= ik_chain_info_.limits[j].max_position) && (q_ik_sols[i][j] >= ik_chain_info_.limits[j].min_position))
{
valid_solution[j] = q_ik_sols[i][j];
valid = true;
continue;
}
else if ((q_ik_sols[i][j] > ik_chain_info_.limits[j].max_position) && (q_ik_sols[i][j]-2*M_PI > ik_chain_info_.limits[j].min_position))
{
valid_solution[j] = q_ik_sols[i][j]-2*M_PI;
valid = true;
continue;
}
else if ((q_ik_sols[i][j] < ik_chain_info_.limits[j].min_position) && (q_ik_sols[i][j]+2*M_PI < ik_chain_info_.limits[j].max_position))
{
valid_solution[j] = q_ik_sols[i][j]+2*M_PI;
valid = true;
continue;
}
else
{
valid = false;
break;
}
}
if(valid)
{
q_ik_valid_sols.push_back(valid_solution);
}
}
// use weighted absolute deviations to determine the solution closest the seed state
std::vector<idx_double> weighted_diffs;
for(uint16_t i=0; i<q_ik_valid_sols.size(); i++) {
double cur_weighted_diff = 0;
for(uint16_t j=0; j<6; j++) {
// solution violates the consistency_limits, throw it out
double abs_diff = std::fabs(ik_seed_state[ur_joint_inds_start_+j] - q_ik_valid_sols[i][j]);
if(!consistency_limits.empty() && abs_diff > consistency_limits[ur_joint_inds_start_+j]) {
cur_weighted_diff = std::numeric_limits<double>::infinity();
break;
}
cur_weighted_diff += ik_weights_[j] * abs_diff;
}
weighted_diffs.push_back(idx_double(i, cur_weighted_diff));
}
std::sort(weighted_diffs.begin(), weighted_diffs.end(), comparator);
#if 0
printf("start\n");
printf(" q %1.2f, %1.2f, %1.2f, %1.2f, %1.2f, %1.2f\n", ik_seed_state[1], ik_seed_state[2], ik_seed_state[3], ik_seed_state[4], ik_seed_state[5], ik_seed_state[6]);
for(uint16_t i=0; i<weighted_diffs.size(); i++) {
int cur_idx = weighted_diffs[i].first;
printf("diff %f, i %d, q %1.2f, %1.2f, %1.2f, %1.2f, %1.2f, %1.2f\n", weighted_diffs[i].second, cur_idx, q_ik_valid_sols[cur_idx][0], q_ik_valid_sols[cur_idx][1], q_ik_valid_sols[cur_idx][2], q_ik_valid_sols[cur_idx][3], q_ik_valid_sols[cur_idx][4], q_ik_valid_sols[cur_idx][5]);
}
printf("end\n");
#endif
for(uint16_t i=0; i<weighted_diffs.size(); i++) {
if(weighted_diffs[i].second == std::numeric_limits<double>::infinity()) {
// rest are infinity, no more feasible solutions
break;
}
// copy the best solution to the output
int cur_idx = weighted_diffs[i].first;
solution = q_ik_valid_sols[cur_idx];
// see if this solution passes the callback function test
if(!solution_callback.empty())
solution_callback(ik_pose, solution, error_code);
else
error_code.val = error_code.SUCCESS;
if(error_code.val == error_code.SUCCESS) {
#if 0
std::vector<std::string> fk_link_names;
fk_link_names.push_back(ur_link_names_.back());
std::vector<geometry_msgs::Pose> fk_poses;
getPositionFK(fk_link_names, solution, fk_poses);
KDL::Frame kdl_fk_pose;
tf::poseMsgToKDL(fk_poses[0], kdl_fk_pose);
printf("FK(solution) - pose \n");
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++)
printf("%1.6f ", kdl_fk_pose(i, j)-kdl_ik_pose(i, j));
printf("\n");
}
#endif
return true;
}
}
// none of the solutions were both consistent and passed the solution callback
if(options.lock_redundant_joints) {
ROS_DEBUG_NAMED("kdl","Will not pertubate redundant joints to find solution");
break;
}
if(dimension_ == 6) {
ROS_DEBUG_NAMED("kdl","No other joints to pertubate, cannot find solution");
break;
}
// randomly pertubate other joints and try again
if(!consistency_limits.empty()) {
getRandomConfiguration(jnt_seed_state, consistency_limits, jnt_pos_test, false);
} else {
getRandomConfiguration(jnt_pos_test, false);
}
}
ROS_DEBUG_NAMED("kdl","An IK that satisifes the constraints and is collision free could not be found");
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
bool URKinematicsPlugin::getPositionFK(const std::vector<std::string> &link_names,
const std::vector<double> &joint_angles,
std::vector<geometry_msgs::Pose> &poses) const
{
ros::WallTime n1 = ros::WallTime::now();
if(!active_)
{
ROS_ERROR_NAMED("kdl","kinematics not active");
return false;
}
poses.resize(link_names.size());
if(joint_angles.size() != dimension_)
{
ROS_ERROR_NAMED("kdl","Joint angles vector must have size: %d",dimension_);
return false;
}
KDL::Frame p_out;
geometry_msgs::PoseStamped pose;
tf::Stamped<tf::Pose> tf_pose;
KDL::JntArray jnt_pos_in(dimension_);
for(unsigned int i=0; i < dimension_; i++)
{
jnt_pos_in(i) = joint_angles[i];
}
KDL::ChainFkSolverPos_recursive fk_solver(kdl_chain_);
bool valid = true;
for(unsigned int i=0; i < poses.size(); i++)
{
ROS_DEBUG_NAMED("kdl","End effector index: %d",getKDLSegmentIndex(link_names[i]));
if(fk_solver.JntToCart(jnt_pos_in,p_out,getKDLSegmentIndex(link_names[i])) >=0)
{
tf::poseKDLToMsg(p_out,poses[i]);
}
else
{
ROS_ERROR_NAMED("kdl","Could not compute FK for %s",link_names[i].c_str());
valid = false;
}
}
return valid;
}
const std::vector<std::string>& URKinematicsPlugin::getJointNames() const
{
return ik_chain_info_.joint_names;
}
const std::vector<std::string>& URKinematicsPlugin::getLinkNames() const
{
return ik_chain_info_.link_names;
}
} // namespace
| 37.777381 | 285 | 0.630826 | [
"object",
"vector",
"model"
] |
103fa0f5faf841c78c14dbb1679d7296e0913ba7 | 7,073 | cc | C++ | paddle/fluid/framework/ir/fc_fuse_pass.cc | XiaoguangHu01/Paddle | af37285870439a6410851eb0cc8a1b5849ee203a | [
"Apache-2.0"
] | null | null | null | paddle/fluid/framework/ir/fc_fuse_pass.cc | XiaoguangHu01/Paddle | af37285870439a6410851eb0cc8a1b5849ee203a | [
"Apache-2.0"
] | 1 | 2021-01-25T09:40:19.000Z | 2021-01-25T09:40:19.000Z | paddle/fluid/framework/ir/fc_fuse_pass.cc | XiaoguangHu01/Paddle | af37285870439a6410851eb0cc8a1b5849ee203a | [
"Apache-2.0"
] | 3 | 2021-01-07T12:51:20.000Z | 2021-01-08T04:31:16.000Z | // Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/ir/fc_fuse_pass.h"
#include <string>
#include <vector>
#include "paddle/fluid/framework/ir/graph_helper.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/platform/enforce.h"
namespace paddle {
namespace framework {
namespace ir {
void FCFusePass::ApplyImpl(ir::Graph* graph) const {
PADDLE_ENFORCE_NOT_NULL(
graph, platform::errors::InvalidArgument("Graph cannot be nullptr."));
FusePassBase::Init("fc_fuse", graph);
int found_fc_count = 0;
for (bool with_relu : {true, false}) {
found_fc_count += ApplyFCPattern(graph, with_relu);
}
AddStatis(found_fc_count);
}
int FCFusePass::ApplyFCPattern(Graph* graph, bool with_relu) const {
GraphPatternDetector gpd;
auto* x = gpd.mutable_pattern()
->NewNode("fc_fuse/x")
->AsInput()
->assert_is_op_input("mul", "X");
patterns::FC fc_pattern(gpd.mutable_pattern(), "fc_fuse");
fc_pattern(x, true /*with bias*/, with_relu);
int found_fc_count = 0;
auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
Graph* g) {
if (subgraph.count(x) <= 0) {
LOG(WARNING) << "The subgraph is empty.";
return;
}
VLOG(4) << "handle FC fuse";
GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
GET_IR_NODE_FROM_SUBGRAPH(bias, bias, fc_pattern);
GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out,
fc_pattern);
GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
Node* relu = nullptr;
Node* relu_out = nullptr;
if (with_relu) {
GET_IR_NODE_FROM_SUBGRAPH(tmp_relu, relu, fc_pattern);
GET_IR_NODE_FROM_SUBGRAPH(tmp_relu_out, relu_out, fc_pattern);
relu = tmp_relu;
relu_out = tmp_relu_out;
}
// Create an FC Node.
OpDesc desc;
desc.SetType("fc");
// Set inputs of fc
desc.SetInput("Input", {subgraph.at(x)->Name()});
desc.SetInput("W", {w->Name()});
desc.SetInput("Bias", {bias->Name()});
// Set output of fc
std::string fc_out_name =
with_relu ? relu_out->Name() : elementwise_add_out->Name();
desc.SetOutput("Out", std::vector<std::string>({fc_out_name}));
// Set attrs of fc
desc.SetAttr("in_num_col_dims", mul->Op()->GetAttr("x_num_col_dims"));
std::string activation_type = with_relu ? "relu" : "";
desc.SetAttr("activation_type", activation_type);
// This is to add padding for dimension 128 on concern of MKL performance
bool use_gpu = Has("use_gpu") ? Get<bool>("use_gpu") : false;
bool use_fc_padding =
Has("use_fc_padding") ? Get<bool>("use_fc_padding") : true;
const std::string& w_name = patterns::UniqueKey(w->Name());
VarDesc w_key(w_name);
w_key.SetPersistable(true);
auto* w_node = g->CreateVarNode(&w_key);
if (!use_gpu && use_fc_padding) {
auto* scope = param_scope();
auto* weight = scope->FindVar(w->Name())->GetMutable<LoDTensor>();
auto* weight_data = weight->data<float>();
auto weight_dims = weight->dims();
int weight_num = product(weight_dims);
int w_h = weight_dims[0];
int w_w = weight_dims[1];
if (w_h % 128 == 0 && w_w % 128 == 0) {
auto* w_var = scope->Var(w_name);
auto* w_tensor = w_var->GetMutable<framework::LoDTensor>();
auto* weight_data_tmp = new float[weight_num];
for (int i = 0; i < w_h; i++) {
memcpy(weight_data_tmp + i * w_w, weight_data + i * w_w,
w_w * sizeof(float));
}
w_tensor->Resize(DDim{weight_dims[0] + 4, weight_dims[1] + 4});
auto* weight_data_new =
w_tensor->mutable_data<float>(platform::CPUPlace());
for (int i = 0; i < w_h; i++) {
memcpy(weight_data_new + i * (w_w + 4), weight_data_tmp + i * w_w,
w_w * sizeof(float));
}
delete[] weight_data_tmp;
desc.SetInput("W", {w_name});
desc.SetAttr("padding_weights", true);
desc.Flush();
}
}
// For anakin subgraph int8
// When in anakin subgraph int8 mode, the pattern like "fake_quant + mul +
// fake_dequant" can be detected by the quant_dequant_fuse_pass. This pass
// will add "input_scale", "weight_scale" which are extracted from
// fake_quant op and fake_dequant op to mul op, and then delete the
// fake_quant op and fake_dequant op in the graph. If the mul op has the
// scale info, we should add those to the fused fc.
auto* mul_op_desc = mul->Op();
if (mul_op_desc->HasAttr("enable_int8")) {
desc.SetAttr("enable_int8", mul_op_desc->GetAttr("enable_int8"));
desc.SetAttr("Input_scale", mul_op_desc->GetAttr("X_scale"));
desc.SetAttr("weight_scale", mul_op_desc->GetAttr("weight_scale"));
if (mul_op_desc->HasAttr("out_scale"))
desc.SetAttr("out_scale", mul_op_desc->GetAttr("out_scale"));
auto elementwise_desc = elementwise_add->Op();
if (elementwise_desc->HasAttr("out_scale"))
desc.SetAttr("out_scale", elementwise_desc->GetAttr("out_scale"));
}
auto fc_node = g->CreateOpNode(&desc); // OpDesc will be copied.
if (with_relu) {
GraphSafeRemoveNodes(
graph, {mul, elementwise_add, mul_out, elementwise_add_out, relu});
} else {
GraphSafeRemoveNodes(graph, {mul, elementwise_add, mul_out});
}
IR_NODE_LINK_TO(subgraph.at(x), fc_node);
if (desc.GetAttrIfExists<bool>("padding_weights")) {
IR_NODE_LINK_TO(w_node, fc_node);
} else {
GraphSafeRemoveNodes(g, {w_node});
IR_NODE_LINK_TO(w, fc_node);
}
IR_NODE_LINK_TO(bias, fc_node);
if (with_relu) {
IR_NODE_LINK_TO(fc_node, relu_out);
} else {
IR_NODE_LINK_TO(fc_node, elementwise_add_out);
}
found_fc_count++;
};
gpd(graph, handler);
return found_fc_count;
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(fc_fuse_pass, paddle::framework::ir::FCFusePass)
.RequirePassAttr("use_gpu");
REGISTER_PASS_CAPABILITY(fc_fuse_pass)
.AddCombination(
paddle::framework::compatible::OpVersionComparatorCombination()
.EQ("mul", 0)
.LE("elementwise_add", 1)
.EQ("relu", 0)
.EQ("fc", 0));
| 36.647668 | 78 | 0.652199 | [
"vector"
] |
1040077b02a464794663d5e05f6003228cece2f8 | 51,635 | cpp | C++ | OgreMain/src/OgreFrustum.cpp | Sukesh16/121212 | f7bcfae219af453247172c13d4484141ccf8e978 | [
"MIT"
] | null | null | null | OgreMain/src/OgreFrustum.cpp | Sukesh16/121212 | f7bcfae219af453247172c13d4484141ccf8e978 | [
"MIT"
] | null | null | null | OgreMain/src/OgreFrustum.cpp | Sukesh16/121212 | f7bcfae219af453247172c13d4484141ccf8e978 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreFrustum.h"
#include "OgreMath.h"
#include "OgreMatrix3.h"
#include "OgreSphere.h"
#include "OgreException.h"
#include "OgreRoot.h"
#include "OgreCamera.h"
#include "OgreHardwareBufferManager.h"
#include "OgreHardwareVertexBuffer.h"
#include "OgreMaterialManager.h"
#include "OgreRenderSystem.h"
#include "OgreMovablePlane.h"
namespace Ogre {
String Frustum::msMovableType = "Frustum";
const Real Frustum::INFINITE_FAR_PLANE_ADJUST = 0.00001;
//-----------------------------------------------------------------------
Frustum::Frustum(const String& name) :
mProjType(PT_PERSPECTIVE),
mFOVy(Radian(Math::PI/4.0f)),
mFarDist(100000.0f),
mNearDist(100.0f),
mAspect(1.33333333333333f),
mOrthoHeight(1000),
mFrustumOffset(Vector2::ZERO),
mFocalLength(1.0f),
mLastParentOrientation(Quaternion::IDENTITY),
mLastParentPosition(Vector3::ZERO),
mRecalcFrustum(true),
mRecalcView(true),
mRecalcFrustumPlanes(true),
mRecalcWorldSpaceCorners(true),
mRecalcVertexData(true),
mCustomViewMatrix(false),
mCustomProjMatrix(false),
mFrustumExtentsManuallySet(false),
mOrientationMode(OR_DEGREE_0),
mReflect(false),
mLinkedReflectPlane(0),
mObliqueDepthProjection(false),
mLinkedObliqueProjPlane(0)
{
// Initialise material
mMaterial = MaterialManager::getSingleton().getDefaultMaterial(false);
// Alter superclass members
mVisible = false;
mParentNode = 0;
mName = name;
mLastLinkedReflectionPlane.normal = Vector3::ZERO;
mLastLinkedObliqueProjPlane.normal = Vector3::ZERO;
updateView();
updateFrustum();
}
//-----------------------------------------------------------------------
Frustum::~Frustum()
{
// Do nothing
}
//-----------------------------------------------------------------------
void Frustum::setFOVy(const Radian& fov)
{
mFOVy = fov;
invalidateFrustum();
}
//-----------------------------------------------------------------------
const Radian& Frustum::getFOVy(void) const
{
return mFOVy;
}
//-----------------------------------------------------------------------
void Frustum::setFarClipDistance(Real farPlane)
{
mFarDist = farPlane;
invalidateFrustum();
}
//-----------------------------------------------------------------------
Real Frustum::getFarClipDistance(void) const
{
return mFarDist;
}
//-----------------------------------------------------------------------
void Frustum::setNearClipDistance(Real nearPlane)
{
if (nearPlane <= 0)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Near clip distance must be greater than zero.",
"Frustum::setNearClipDistance");
mNearDist = nearPlane;
invalidateFrustum();
}
//-----------------------------------------------------------------------
Real Frustum::getNearClipDistance(void) const
{
return mNearDist;
}
//---------------------------------------------------------------------
void Frustum::setFrustumOffset(const Vector2& offset)
{
mFrustumOffset = offset;
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::setFrustumOffset(Real horizontal, Real vertical)
{
setFrustumOffset(Vector2(horizontal, vertical));
}
//---------------------------------------------------------------------
const Vector2& Frustum::getFrustumOffset() const
{
return mFrustumOffset;
}
//---------------------------------------------------------------------
void Frustum::setFocalLength(Real focalLength)
{
if (focalLength <= 0)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Focal length must be greater than zero.",
"Frustum::setFocalLength");
}
mFocalLength = focalLength;
invalidateFrustum();
}
//---------------------------------------------------------------------
Real Frustum::getFocalLength() const
{
return mFocalLength;
}
//-----------------------------------------------------------------------
const Matrix4& Frustum::getProjectionMatrix(void) const
{
updateFrustum();
return mProjMatrix;
}
//-----------------------------------------------------------------------
const Matrix4& Frustum::getProjectionMatrixWithRSDepth(void) const
{
updateFrustum();
return mProjMatrixRSDepth;
}
//-----------------------------------------------------------------------
const Matrix4& Frustum::getProjectionMatrixRS(void) const
{
updateFrustum();
return mProjMatrixRS;
}
//-----------------------------------------------------------------------
const Matrix4& Frustum::getViewMatrix(void) const
{
updateView();
return mViewMatrix;
}
//-----------------------------------------------------------------------
const Plane* Frustum::getFrustumPlanes(void) const
{
// Make any pending updates to the calculated frustum planes
updateFrustumPlanes();
return mFrustumPlanes;
}
//-----------------------------------------------------------------------
const Plane& Frustum::getFrustumPlane(unsigned short plane) const
{
// Make any pending updates to the calculated frustum planes
updateFrustumPlanes();
return mFrustumPlanes[plane];
}
//-----------------------------------------------------------------------
bool Frustum::isVisible(const AxisAlignedBox& bound, FrustumPlane* culledBy) const
{
// Null boxes always invisible
if (bound.isNull()) return false;
// Infinite boxes always visible
if (bound.isInfinite()) return true;
// Make any pending updates to the calculated frustum planes
updateFrustumPlanes();
// Get centre of the box
Vector3 centre = bound.getCenter();
// Get the half-size of the box
Vector3 halfSize = bound.getHalfSize();
// For each plane, see if all points are on the negative side
// If so, object is not visible
for (int plane = 0; plane < 6; ++plane)
{
// Skip far plane if infinite view frustum
if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0)
continue;
Plane::Side side = mFrustumPlanes[plane].getSide(centre, halfSize);
if (side == Plane::NEGATIVE_SIDE)
{
// ALL corners on negative side therefore out of view
if (culledBy)
*culledBy = (FrustumPlane)plane;
return false;
}
}
return true;
}
//-----------------------------------------------------------------------
bool Frustum::isVisible(const Vector3& vert, FrustumPlane* culledBy) const
{
// Make any pending updates to the calculated frustum planes
updateFrustumPlanes();
// For each plane, see if all points are on the negative side
// If so, object is not visible
for (int plane = 0; plane < 6; ++plane)
{
// Skip far plane if infinite view frustum
if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0)
continue;
if (mFrustumPlanes[plane].getSide(vert) == Plane::NEGATIVE_SIDE)
{
// ALL corners on negative side therefore out of view
if (culledBy)
*culledBy = (FrustumPlane)plane;
return false;
}
}
return true;
}
//-----------------------------------------------------------------------
bool Frustum::isVisible(const Sphere& sphere, FrustumPlane* culledBy) const
{
// Make any pending updates to the calculated frustum planes
updateFrustumPlanes();
// For each plane, see if sphere is on negative side
// If so, object is not visible
for (int plane = 0; plane < 6; ++plane)
{
// Skip far plane if infinite view frustum
if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0)
continue;
// If the distance from sphere center to plane is negative, and 'more negative'
// than the radius of the sphere, sphere is outside frustum
if (mFrustumPlanes[plane].getDistance(sphere.getCenter()) < -sphere.getRadius())
{
// ALL corners on negative side therefore out of view
if (culledBy)
*culledBy = (FrustumPlane)plane;
return false;
}
}
return true;
}
//---------------------------------------------------------------------
uint32 Frustum::getTypeFlags(void) const
{
return SceneManager::FRUSTUM_TYPE_MASK;
}
//-----------------------------------------------------------------------
RealRect Frustum::calcProjectionParameters() const
{
if (mCustomProjMatrix)
{
// Convert clipspace corners to camera space
Matrix4 invProj = mProjMatrix.inverse();
Vector3 topLeft(-0.5f, 0.5f, 0.0f);
Vector3 bottomRight(0.5f, -0.5f, 0.0f);
topLeft = invProj * topLeft;
bottomRight = invProj * bottomRight;
return RealRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
}
else
{
if (mFrustumExtentsManuallySet)
{
return mExtents;
}
// Calculate general projection parameters
else if (mProjType == PT_PERSPECTIVE)
{
Radian thetaY (mFOVy * 0.5f);
Real tanThetaY = Math::Tan(thetaY);
Real tanThetaX = tanThetaY * mAspect;
Real nearFocal = mNearDist / mFocalLength;
Real nearOffsetX = mFrustumOffset.x * nearFocal;
Real nearOffsetY = mFrustumOffset.y * nearFocal;
Real half_w = tanThetaX * mNearDist;
Real half_h = tanThetaY * mNearDist;
mExtents = RealRect(-half_w + nearOffsetX, +half_h + nearOffsetY,
+half_w + nearOffsetX, -half_h + nearOffsetY);
}
else
{
// Unknown how to apply frustum offset to orthographic camera, just ignore here
Real half_w = getOrthoWindowWidth() * 0.5f;
Real half_h = getOrthoWindowHeight() * 0.5f;
mExtents = RealRect(-half_w, +half_h, +half_w, -half_h);
}
return mExtents;
}
}
//-----------------------------------------------------------------------
void Frustum::updateFrustumImpl(void) const
{
// Common calcs
RealRect rect = calcProjectionParameters();
if (!OGRE_NO_VIEWPORT_ORIENTATIONMODE && mOrientationMode != OR_PORTRAIT)
{
std::swap(rect.left, rect.bottom);
std::swap(rect.right, rect.top);
}
Real left = rect.left, right = rect.right, top = rect.top, bottom = rect.bottom;
if (!mCustomProjMatrix)
{
// The code below will dealing with general projection
// parameters, similar glFrustum and glOrtho.
// Doesn't optimise manually except division operator, so the
// code more self-explaining.
Real inv_w = 1 / (right - left);
Real inv_h = 1 / (top - bottom);
Real inv_d = 1 / (mFarDist - mNearDist);
// Recalc if frustum params changed
if (mProjType == PT_PERSPECTIVE)
{
// Calc matrix elements
Real A = 2 * mNearDist * inv_w;
Real B = 2 * mNearDist * inv_h;
Real C = (right + left) * inv_w;
Real D = (top + bottom) * inv_h;
Real q, qn;
if (mFarDist == 0)
{
// Infinite far plane
q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
qn = mNearDist * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2);
}
else
{
q = - (mFarDist + mNearDist) * inv_d;
qn = -2 * (mFarDist * mNearDist) * inv_d;
}
// NB: This creates 'uniform' perspective projection matrix,
// which depth range [-1,1], right-handed rules
//
// [ A 0 C 0 ]
// [ 0 B D 0 ]
// [ 0 0 q qn ]
// [ 0 0 -1 0 ]
//
// A = 2 * near / (right - left)
// B = 2 * near / (top - bottom)
// C = (right + left) / (right - left)
// D = (top + bottom) / (top - bottom)
// q = - (far + near) / (far - near)
// qn = - 2 * (far * near) / (far - near)
mProjMatrix = Matrix4::ZERO;
mProjMatrix[0][0] = A;
mProjMatrix[0][2] = C;
mProjMatrix[1][1] = B;
mProjMatrix[1][2] = D;
mProjMatrix[2][2] = q;
mProjMatrix[2][3] = qn;
mProjMatrix[3][2] = -1;
if (mObliqueDepthProjection)
{
// Translate the plane into view space
// Don't use getViewMatrix here, incase overrided by
// camera and return a cull frustum view matrix
updateView();
Plane plane = mViewMatrix * mObliqueProjPlane;
// Thanks to Eric Lenyel for posting this calculation
// at www.terathon.com
// Calculate the clip-space corner point opposite the
// clipping plane
// as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
// transform it into camera space by multiplying it
// by the inverse of the projection matrix
/* generalised version
Vector4 q = matrix.inverse() *
Vector4(Math::Sign(plane.normal.x),
Math::Sign(plane.normal.y), 1.0f, 1.0f);
*/
Vector4 qVec;
qVec.x = (Math::Sign(plane.normal.x) + mProjMatrix[0][2]) / mProjMatrix[0][0];
qVec.y = (Math::Sign(plane.normal.y) + mProjMatrix[1][2]) / mProjMatrix[1][1];
qVec.z = -1;
qVec.w = (1 + mProjMatrix[2][2]) / mProjMatrix[2][3];
// Calculate the scaled plane vector
Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d);
Vector4 c = clipPlane4d * (2 / (clipPlane4d.dotProduct(qVec)));
// Replace the third row of the projection matrix
mProjMatrix[2][0] = c.x;
mProjMatrix[2][1] = c.y;
mProjMatrix[2][2] = c.z + 1;
mProjMatrix[2][3] = c.w;
}
} // perspective
else if (mProjType == PT_ORTHOGRAPHIC)
{
Real A = 2 * inv_w;
Real B = 2 * inv_h;
Real C = - (right + left) * inv_w;
Real D = - (top + bottom) * inv_h;
Real q, qn;
if (mFarDist == 0)
{
// Can not do infinite far plane here, avoid divided zero only
q = - Frustum::INFINITE_FAR_PLANE_ADJUST / mNearDist;
qn = - Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
}
else
{
q = - 2 * inv_d;
qn = - (mFarDist + mNearDist) * inv_d;
}
// NB: This creates 'uniform' orthographic projection matrix,
// which depth range [-1,1], right-handed rules
//
// [ A 0 0 C ]
// [ 0 B 0 D ]
// [ 0 0 q qn ]
// [ 0 0 0 1 ]
//
// A = 2 * / (right - left)
// B = 2 * / (top - bottom)
// C = - (right + left) / (right - left)
// D = - (top + bottom) / (top - bottom)
// q = - 2 / (far - near)
// qn = - (far + near) / (far - near)
mProjMatrix = Matrix4::ZERO;
mProjMatrix[0][0] = A;
mProjMatrix[0][3] = C;
mProjMatrix[1][1] = B;
mProjMatrix[1][3] = D;
mProjMatrix[2][2] = q;
mProjMatrix[2][3] = qn;
mProjMatrix[3][3] = 1;
} // ortho
} // !mCustomProjMatrix
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
// Deal with orientation mode
mProjMatrix = mProjMatrix * Quaternion(Degree(mOrientationMode * 90.f), Vector3::UNIT_Z);
#endif
RenderSystem* renderSystem = Root::getSingleton().getRenderSystem();
if(renderSystem)
{
// API specific
renderSystem->_convertProjectionMatrix(mProjMatrix, mProjMatrixRS);
renderSystem->_convertProjectionMatrix(mProjMatrix, mProjMatrixRSDepth, true);
}
else
{
mProjMatrixRS = mProjMatrix;
mProjMatrixRSDepth = mProjMatrix;
}
// Calculate bounding box (local)
// Box is from 0, down -Z, max dimensions as determined from far plane
// If infinite view frustum just pick a far value
Real farDist = (mFarDist == 0) ? 100000 : mFarDist;
// Near plane bounds
Vector3 min(left, bottom, -farDist);
Vector3 max(right, top, 0);
if (mCustomProjMatrix)
{
// Some custom projection matrices can have unusual inverted settings
// So make sure the AABB is the right way around to start with
Vector3 tmp = min;
min.makeFloor(max);
max.makeCeil(tmp);
}
if (mProjType == PT_PERSPECTIVE)
{
// Merge with far plane bounds
Real radio = farDist / mNearDist;
min.makeFloor(Vector3(left * radio, bottom * radio, -farDist));
max.makeCeil(Vector3(right * radio, top * radio, 0));
}
mBoundingBox.setExtents(min, max);
mRecalcFrustum = false;
// Signal to update frustum clipping planes
mRecalcFrustumPlanes = true;
}
//-----------------------------------------------------------------------
void Frustum::updateFrustum(void) const
{
if (isFrustumOutOfDate())
{
updateFrustumImpl();
}
}
//-----------------------------------------------------------------------
void Frustum::updateVertexData(void) const
{
if (mRecalcVertexData)
{
if (mVertexData.vertexBufferBinding->getBufferCount() <= 0)
{
// Initialise vertex & index data
mVertexData.vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION);
mVertexData.vertexCount = 32;
mVertexData.vertexStart = 0;
mVertexData.vertexBufferBinding->setBinding( 0,
HardwareBufferManager::getSingleton().createVertexBuffer(
sizeof(float)*3, 32, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY) );
}
// Note: Even though we can dealing with general projection matrix here,
// but because it's incompatibly with infinite far plane, thus, we
// still need to working with projection parameters.
// Calc near plane corners
const RealRect vp = calcProjectionParameters();
Real vpLeft = vp.left, vpRight = vp.right, vpBottom = vp.bottom, vpTop = vp.top;
// Treat infinite fardist as some arbitrary far value
Real farDist = (mFarDist == 0) ? 100000 : mFarDist;
// Calc far plane corners
Real radio = mProjType == PT_PERSPECTIVE ? farDist / mNearDist : 1;
Real farLeft = vpLeft * radio;
Real farRight = vpRight * radio;
Real farBottom = vpBottom * radio;
Real farTop = vpTop * radio;
// Calculate vertex positions (local)
// 0 is the origin
// 1, 2, 3, 4 are the points on the near plane, top left first, clockwise
// 5, 6, 7, 8 are the points on the far plane, top left first, clockwise
HardwareVertexBufferSharedPtr vbuf = mVertexData.vertexBufferBinding->getBuffer(0);
float* pFloat = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
// near plane (remember frustum is going in -Z direction)
*pFloat++ = vpLeft; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = vpRight; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = vpRight; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = vpRight; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = vpRight; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = vpLeft; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = vpLeft; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = vpLeft; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
// far plane (remember frustum is going in -Z direction)
*pFloat++ = farLeft; *pFloat++ = farTop; *pFloat++ = -farDist;
*pFloat++ = farRight; *pFloat++ = farTop; *pFloat++ = -farDist;
*pFloat++ = farRight; *pFloat++ = farTop; *pFloat++ = -farDist;
*pFloat++ = farRight; *pFloat++ = farBottom; *pFloat++ = -farDist;
*pFloat++ = farRight; *pFloat++ = farBottom; *pFloat++ = -farDist;
*pFloat++ = farLeft; *pFloat++ = farBottom; *pFloat++ = -farDist;
*pFloat++ = farLeft; *pFloat++ = farBottom; *pFloat++ = -farDist;
*pFloat++ = farLeft; *pFloat++ = farTop; *pFloat++ = -farDist;
// Sides of the pyramid
*pFloat++ = 0.0f; *pFloat++ = 0.0f; *pFloat++ = 0.0f;
*pFloat++ = vpLeft; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = 0.0f; *pFloat++ = 0.0f; *pFloat++ = 0.0f;
*pFloat++ = vpRight; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = 0.0f; *pFloat++ = 0.0f; *pFloat++ = 0.0f;
*pFloat++ = vpRight; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = 0.0f; *pFloat++ = 0.0f; *pFloat++ = 0.0f;
*pFloat++ = vpLeft; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
// Sides of the box
*pFloat++ = vpLeft; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = farLeft; *pFloat++ = farTop; *pFloat++ = -farDist;
*pFloat++ = vpRight; *pFloat++ = vpTop; *pFloat++ = -mNearDist;
*pFloat++ = farRight; *pFloat++ = farTop; *pFloat++ = -farDist;
*pFloat++ = vpRight; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = farRight; *pFloat++ = farBottom; *pFloat++ = -farDist;
*pFloat++ = vpLeft; *pFloat++ = vpBottom; *pFloat++ = -mNearDist;
*pFloat++ = farLeft; *pFloat++ = farBottom; *pFloat++ = -farDist;
vbuf->unlock();
mRecalcVertexData = false;
}
}
//-----------------------------------------------------------------------
bool Frustum::isViewOutOfDate(void) const
{
// Attached to node?
if (mParentNode)
{
if (mRecalcView ||
mParentNode->_getDerivedOrientation() != mLastParentOrientation ||
mParentNode->_getDerivedPosition() != mLastParentPosition)
{
// Ok, we're out of date with SceneNode we're attached to
mLastParentOrientation = mParentNode->_getDerivedOrientation();
mLastParentPosition = mParentNode->_getDerivedPosition();
mRecalcView = true;
}
}
// Deriving reflection from linked plane?
if (mLinkedReflectPlane &&
!(mLastLinkedReflectionPlane == mLinkedReflectPlane->_getDerivedPlane()))
{
mReflectPlane = mLinkedReflectPlane->_getDerivedPlane();
mReflectMatrix = Math::buildReflectionMatrix(mReflectPlane);
mLastLinkedReflectionPlane = mLinkedReflectPlane->_getDerivedPlane();
mRecalcView = true;
}
return mRecalcView;
}
//-----------------------------------------------------------------------
bool Frustum::isFrustumOutOfDate(void) const
{
// Deriving custom near plane from linked plane?
if (mObliqueDepthProjection)
{
// Out of date when view out of data since plane needs to be in view space
if (isViewOutOfDate())
{
mRecalcFrustum = true;
}
// Update derived plane
if (mLinkedObliqueProjPlane &&
!(mLastLinkedObliqueProjPlane == mLinkedObliqueProjPlane->_getDerivedPlane()))
{
mObliqueProjPlane = mLinkedObliqueProjPlane->_getDerivedPlane();
mLastLinkedObliqueProjPlane = mObliqueProjPlane;
mRecalcFrustum = true;
}
}
return mRecalcFrustum;
}
//-----------------------------------------------------------------------
void Frustum::updateViewImpl(void) const
{
// ----------------------
// Update the view matrix
// ----------------------
// Get orientation from quaternion
if (!mCustomViewMatrix)
{
Matrix3 rot;
const Quaternion& orientation = getOrientationForViewUpdate();
const Vector3& position = getPositionForViewUpdate();
mViewMatrix = Math::makeViewMatrix(position, orientation, mReflect? &mReflectMatrix : 0);
}
mRecalcView = false;
// Signal to update frustum clipping planes
mRecalcFrustumPlanes = true;
// Signal to update world space corners
mRecalcWorldSpaceCorners = true;
// Signal to update frustum if oblique plane enabled,
// since plane needs to be in view space
if (mObliqueDepthProjection)
{
mRecalcFrustum = true;
}
}
//---------------------------------------------------------------------
void Frustum::calcViewMatrixRelative(const Vector3& relPos, Matrix4& matToUpdate) const
{
Matrix4 matTrans = Matrix4::IDENTITY;
matTrans.setTrans(relPos);
matToUpdate = getViewMatrix() * matTrans;
}
//-----------------------------------------------------------------------
void Frustum::updateView(void) const
{
if (isViewOutOfDate())
{
updateViewImpl();
}
}
//-----------------------------------------------------------------------
void Frustum::updateFrustumPlanesImpl(void) const
{
// -------------------------
// Update the frustum planes
// -------------------------
Matrix4 combo = mProjMatrix * mViewMatrix;
mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.x = combo[3][0] + combo[0][0];
mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.y = combo[3][1] + combo[0][1];
mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.z = combo[3][2] + combo[0][2];
mFrustumPlanes[FRUSTUM_PLANE_LEFT].d = combo[3][3] + combo[0][3];
mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal.x = combo[3][0] - combo[0][0];
mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal.y = combo[3][1] - combo[0][1];
mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal.z = combo[3][2] - combo[0][2];
mFrustumPlanes[FRUSTUM_PLANE_RIGHT].d = combo[3][3] - combo[0][3];
mFrustumPlanes[FRUSTUM_PLANE_TOP].normal.x = combo[3][0] - combo[1][0];
mFrustumPlanes[FRUSTUM_PLANE_TOP].normal.y = combo[3][1] - combo[1][1];
mFrustumPlanes[FRUSTUM_PLANE_TOP].normal.z = combo[3][2] - combo[1][2];
mFrustumPlanes[FRUSTUM_PLANE_TOP].d = combo[3][3] - combo[1][3];
mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal.x = combo[3][0] + combo[1][0];
mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal.y = combo[3][1] + combo[1][1];
mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal.z = combo[3][2] + combo[1][2];
mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].d = combo[3][3] + combo[1][3];
mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.x = combo[3][0] + combo[2][0];
mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.y = combo[3][1] + combo[2][1];
mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.z = combo[3][2] + combo[2][2];
mFrustumPlanes[FRUSTUM_PLANE_NEAR].d = combo[3][3] + combo[2][3];
mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.x = combo[3][0] - combo[2][0];
mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.y = combo[3][1] - combo[2][1];
mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.z = combo[3][2] - combo[2][2];
mFrustumPlanes[FRUSTUM_PLANE_FAR].d = combo[3][3] - combo[2][3];
// Renormalise any normals which were not unit length
for(int i=0; i<6; i++ )
{
Real length = mFrustumPlanes[i].normal.normalise();
mFrustumPlanes[i].d /= length;
}
mRecalcFrustumPlanes = false;
}
//-----------------------------------------------------------------------
void Frustum::updateFrustumPlanes(void) const
{
updateView();
updateFrustum();
if (mRecalcFrustumPlanes)
{
updateFrustumPlanesImpl();
}
}
//-----------------------------------------------------------------------
void Frustum::updateWorldSpaceCornersImpl(void) const
{
Matrix4 eyeToWorld = mViewMatrix.inverseAffine();
// Note: Even though we can dealing with general projection matrix here,
// but because it's incompatibly with infinite far plane, thus, we
// still need to working with projection parameters.
// Calc near plane corners
RealRect vp = calcProjectionParameters();
Real nearLeft = vp.left, nearRight = vp.right, nearBottom = vp.bottom, nearTop = vp.top;
// Treat infinite fardist as some arbitrary far value
Real farDist = (mFarDist == 0) ? 100000 : mFarDist;
// Calc far palne corners
Real radio = mProjType == PT_PERSPECTIVE ? farDist / mNearDist : 1;
Real farLeft = nearLeft * radio;
Real farRight = nearRight * radio;
Real farBottom = nearBottom * radio;
Real farTop = nearTop * radio;
// near
mWorldSpaceCorners[0] = eyeToWorld.transformAffine(Vector3(nearRight, nearTop, -mNearDist));
mWorldSpaceCorners[1] = eyeToWorld.transformAffine(Vector3(nearLeft, nearTop, -mNearDist));
mWorldSpaceCorners[2] = eyeToWorld.transformAffine(Vector3(nearLeft, nearBottom, -mNearDist));
mWorldSpaceCorners[3] = eyeToWorld.transformAffine(Vector3(nearRight, nearBottom, -mNearDist));
// far
mWorldSpaceCorners[4] = eyeToWorld.transformAffine(Vector3(farRight, farTop, -farDist));
mWorldSpaceCorners[5] = eyeToWorld.transformAffine(Vector3(farLeft, farTop, -farDist));
mWorldSpaceCorners[6] = eyeToWorld.transformAffine(Vector3(farLeft, farBottom, -farDist));
mWorldSpaceCorners[7] = eyeToWorld.transformAffine(Vector3(farRight, farBottom, -farDist));
mRecalcWorldSpaceCorners = false;
}
//-----------------------------------------------------------------------
void Frustum::updateWorldSpaceCorners(void) const
{
updateView();
if (mRecalcWorldSpaceCorners)
{
updateWorldSpaceCornersImpl();
}
}
//-----------------------------------------------------------------------
Real Frustum::getAspectRatio(void) const
{
return mAspect;
}
//-----------------------------------------------------------------------
void Frustum::setAspectRatio(Real r)
{
mAspect = r;
invalidateFrustum();
}
//-----------------------------------------------------------------------
const AxisAlignedBox& Frustum::getBoundingBox(void) const
{
return mBoundingBox;
}
//-----------------------------------------------------------------------
void Frustum::_updateRenderQueue(RenderQueue* queue)
{
if (mDebugDisplay)
{
// Add self
queue->addRenderable(this);
}
}
//-----------------------------------------------------------------------
const String& Frustum::getMovableType(void) const
{
return msMovableType;
}
//-----------------------------------------------------------------------
Real Frustum::getBoundingRadius(void) const
{
return (mFarDist == 0)? 100000 : mFarDist;
}
//-----------------------------------------------------------------------
const MaterialPtr& Frustum::getMaterial(void) const
{
return mMaterial;
}
//-----------------------------------------------------------------------
void Frustum::setMaterial(const MaterialPtr& mat) {
mMaterial = mat;
}
//-----------------------------------------------------------------------
void Frustum::getRenderOperation(RenderOperation& op)
{
updateVertexData();
op.operationType = RenderOperation::OT_LINE_LIST;
op.useIndexes = false;
op.useGlobalInstancingVertexBufferIsAvailable = false;
op.vertexData = &mVertexData;
}
//-----------------------------------------------------------------------
void Frustum::getWorldTransforms(Matrix4* xform) const
{
if (mParentNode)
*xform = mParentNode->_getFullTransform();
else
*xform = Matrix4::IDENTITY;
}
//-----------------------------------------------------------------------
Real Frustum::getSquaredViewDepth(const Camera* cam) const
{
// Calc from centre
if (mParentNode)
return (cam->getDerivedPosition()
- mParentNode->_getDerivedPosition()).squaredLength();
else
return 0;
}
//-----------------------------------------------------------------------
const LightList& Frustum::getLights(void) const
{
// N/A
static LightList ll;
return ll;
}
//-----------------------------------------------------------------------
void Frustum::_notifyCurrentCamera(Camera* cam)
{
// Make sure bounding box up-to-date
updateFrustum();
MovableObject::_notifyCurrentCamera(cam);
}
// -------------------------------------------------------------------
void Frustum::invalidateFrustum() const
{
mRecalcFrustum = true;
mRecalcFrustumPlanes = true;
mRecalcWorldSpaceCorners = true;
mRecalcVertexData = true;
}
// -------------------------------------------------------------------
void Frustum::invalidateView() const
{
mRecalcView = true;
mRecalcFrustumPlanes = true;
mRecalcWorldSpaceCorners = true;
}
// -------------------------------------------------------------------
const Vector3* Frustum::getWorldSpaceCorners(void) const
{
updateWorldSpaceCorners();
return mWorldSpaceCorners;
}
//-----------------------------------------------------------------------
void Frustum::setProjectionType(ProjectionType pt)
{
mProjType = pt;
invalidateFrustum();
}
//-----------------------------------------------------------------------
ProjectionType Frustum::getProjectionType(void) const
{
return mProjType;
}
//-----------------------------------------------------------------------
const Vector3& Frustum::getPositionForViewUpdate(void) const
{
return mLastParentPosition;
}
//-----------------------------------------------------------------------
const Quaternion& Frustum::getOrientationForViewUpdate(void) const
{
return mLastParentOrientation;
}
//-----------------------------------------------------------------------
void Frustum::enableReflection(const Plane& p)
{
mReflect = true;
mReflectPlane = p;
mLinkedReflectPlane = 0;
mReflectMatrix = Math::buildReflectionMatrix(p);
invalidateView();
}
//-----------------------------------------------------------------------
void Frustum::enableReflection(const MovablePlane* p)
{
mReflect = true;
mLinkedReflectPlane = p;
mReflectPlane = mLinkedReflectPlane->_getDerivedPlane();
mReflectMatrix = Math::buildReflectionMatrix(mReflectPlane);
mLastLinkedReflectionPlane = mLinkedReflectPlane->_getDerivedPlane();
invalidateView();
}
//-----------------------------------------------------------------------
void Frustum::disableReflection(void)
{
mReflect = false;
mLinkedReflectPlane = 0;
mLastLinkedReflectionPlane.normal = Vector3::ZERO;
invalidateView();
}
//---------------------------------------------------------------------
bool Frustum::projectSphere(const Sphere& sphere,
Real* left, Real* top, Real* right, Real* bottom) const
{
// See http://www.gamasutra.com/features/20021011/lengyel_06.htm
// Transform light position into camera space
updateView();
Vector3 eyeSpacePos = mViewMatrix.transformAffine(sphere.getCenter());
// initialise
*left = *bottom = -1.0f;
*right = *top = 1.0f;
if (eyeSpacePos.z < 0)
{
updateFrustum();
const Matrix4& projMatrix = getProjectionMatrix();
Real r = sphere.getRadius();
Real rsq = r * r;
// early-exit
if (eyeSpacePos.squaredLength() <= rsq)
return false;
Real Lxz = Math::Sqr(eyeSpacePos.x) + Math::Sqr(eyeSpacePos.z);
Real Lyz = Math::Sqr(eyeSpacePos.y) + Math::Sqr(eyeSpacePos.z);
// Find the tangent planes to the sphere
// XZ first
// calculate quadratic discriminant: b*b - 4ac
// x = Nx
// a = Lx^2 + Lz^2
// b = -2rLx
// c = r^2 - Lz^2
Real a = Lxz;
Real b = -2.0f * r * eyeSpacePos.x;
Real c = rsq - Math::Sqr(eyeSpacePos.z);
Real D = b*b - 4.0f*a*c;
// two roots?
if (D > 0)
{
Real sqrootD = Math::Sqrt(D);
// solve the quadratic to get the components of the normal
Real Nx0 = (-b + sqrootD) / (2 * a);
Real Nx1 = (-b - sqrootD) / (2 * a);
// Derive Z from this
Real Nz0 = (r - Nx0 * eyeSpacePos.x) / eyeSpacePos.z;
Real Nz1 = (r - Nx1 * eyeSpacePos.x) / eyeSpacePos.z;
// Get the point of tangency
// Only consider points of tangency in front of the camera
Real Pz0 = (Lxz - rsq) / (eyeSpacePos.z - ((Nz0 / Nx0) * eyeSpacePos.x));
if (Pz0 < 0)
{
// Project point onto near plane in worldspace
Real nearx0 = (Nz0 * mNearDist) / Nx0;
// now we need to map this to viewport coords
// use projection matrix since that will take into account all factors
Vector3 relx0 = projMatrix * Vector3(nearx0, 0, -mNearDist);
// find out whether this is a left side or right side
Real Px0 = -(Pz0 * Nz0) / Nx0;
if (Px0 > eyeSpacePos.x)
{
*right = std::min(*right, relx0.x);
}
else
{
*left = std::max(*left, relx0.x);
}
}
Real Pz1 = (Lxz - rsq) / (eyeSpacePos.z - ((Nz1 / Nx1) * eyeSpacePos.x));
if (Pz1 < 0)
{
// Project point onto near plane in worldspace
Real nearx1 = (Nz1 * mNearDist) / Nx1;
// now we need to map this to viewport coords
// use projection matrix since that will take into account all factors
Vector3 relx1 = projMatrix * Vector3(nearx1, 0, -mNearDist);
// find out whether this is a left side or right side
Real Px1 = -(Pz1 * Nz1) / Nx1;
if (Px1 > eyeSpacePos.x)
{
*right = std::min(*right, relx1.x);
}
else
{
*left = std::max(*left, relx1.x);
}
}
}
// Now YZ
// calculate quadratic discriminant: b*b - 4ac
// x = Ny
// a = Ly^2 + Lz^2
// b = -2rLy
// c = r^2 - Lz^2
a = Lyz;
b = -2.0f * r * eyeSpacePos.y;
c = rsq - Math::Sqr(eyeSpacePos.z);
D = b*b - 4.0f*a*c;
// two roots?
if (D > 0)
{
Real sqrootD = Math::Sqrt(D);
// solve the quadratic to get the components of the normal
Real Ny0 = (-b + sqrootD) / (2 * a);
Real Ny1 = (-b - sqrootD) / (2 * a);
// Derive Z from this
Real Nz0 = (r - Ny0 * eyeSpacePos.y) / eyeSpacePos.z;
Real Nz1 = (r - Ny1 * eyeSpacePos.y) / eyeSpacePos.z;
// Get the point of tangency
// Only consider points of tangency in front of the camera
Real Pz0 = (Lyz - rsq) / (eyeSpacePos.z - ((Nz0 / Ny0) * eyeSpacePos.y));
if (Pz0 < 0)
{
// Project point onto near plane in worldspace
Real neary0 = (Nz0 * mNearDist) / Ny0;
// now we need to map this to viewport coords
// use projection matriy since that will take into account all factors
Vector3 rely0 = projMatrix * Vector3(0, neary0, -mNearDist);
// find out whether this is a top side or bottom side
Real Py0 = -(Pz0 * Nz0) / Ny0;
if (Py0 > eyeSpacePos.y)
{
*top = std::min(*top, rely0.y);
}
else
{
*bottom = std::max(*bottom, rely0.y);
}
}
Real Pz1 = (Lyz - rsq) / (eyeSpacePos.z - ((Nz1 / Ny1) * eyeSpacePos.y));
if (Pz1 < 0)
{
// Project point onto near plane in worldspace
Real neary1 = (Nz1 * mNearDist) / Ny1;
// now we need to map this to viewport coords
// use projection matriy since that will take into account all factors
Vector3 rely1 = projMatrix * Vector3(0, neary1, -mNearDist);
// find out whether this is a top side or bottom side
Real Py1 = -(Pz1 * Nz1) / Ny1;
if (Py1 > eyeSpacePos.y)
{
*top = std::min(*top, rely1.y);
}
else
{
*bottom = std::max(*bottom, rely1.y);
}
}
}
}
return (*left != -1.0f) || (*top != 1.0f) || (*right != 1.0f) || (*bottom != -1.0f);
}
//---------------------------------------------------------------------
void Frustum::enableCustomNearClipPlane(const MovablePlane* plane)
{
mObliqueDepthProjection = true;
mLinkedObliqueProjPlane = plane;
mObliqueProjPlane = plane->_getDerivedPlane();
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::enableCustomNearClipPlane(const Plane& plane)
{
mObliqueDepthProjection = true;
mLinkedObliqueProjPlane = 0;
mObliqueProjPlane = plane;
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::disableCustomNearClipPlane(void)
{
mObliqueDepthProjection = false;
mLinkedObliqueProjPlane = 0;
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::setCustomViewMatrix(bool enable, const Matrix4& viewMatrix)
{
mCustomViewMatrix = enable;
if (enable)
{
assert(viewMatrix.isAffine());
mViewMatrix = viewMatrix;
}
invalidateView();
}
//---------------------------------------------------------------------
void Frustum::setCustomProjectionMatrix(bool enable, const Matrix4& projMatrix)
{
mCustomProjMatrix = enable;
if (enable)
{
mProjMatrix = projMatrix;
}
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::setOrthoWindow(Real w, Real h)
{
mOrthoHeight = h;
mAspect = w / h;
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::setOrthoWindowHeight(Real h)
{
mOrthoHeight = h;
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::setOrthoWindowWidth(Real w)
{
mOrthoHeight = w / mAspect;
invalidateFrustum();
}
//---------------------------------------------------------------------
Real Frustum::getOrthoWindowHeight() const
{
return mOrthoHeight;
}
//---------------------------------------------------------------------
Real Frustum::getOrthoWindowWidth() const
{
return mOrthoHeight * mAspect;
}
//---------------------------------------------------------------------
void Frustum::visitRenderables(Renderable::Visitor* visitor,
bool debugRenderables)
{
// Only displayed in debug
if (debugRenderables)
{
visitor->visit(this, 0, true);
}
}
//---------------------------------------------------------------------
void Frustum::setFrustumExtents(Real left, Real right, Real top, Real bottom)
{
mFrustumExtentsManuallySet = true;
mExtents = RealRect(left, top, right, bottom);
invalidateFrustum();
}
//---------------------------------------------------------------------
void Frustum::resetFrustumExtents()
{
mFrustumExtentsManuallySet = false;
invalidateFrustum();
}
//---------------------------------------------------------------------
RealRect Frustum::getFrustumExtents() const
{
updateFrustum();
return mExtents;
}
void Frustum::getFrustumExtents(Real& outleft, Real& outright, Real& outtop, Real& outbottom) const
{
updateFrustum();
outleft = mExtents.left;
outright = mExtents.right;
outtop = mExtents.top;
outbottom = mExtents.bottom;
}
//---------------------------------------------------------------------
PlaneBoundedVolume Frustum::getPlaneBoundedVolume()
{
updateFrustumPlanes();
PlaneBoundedVolume volume;
volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_NEAR]);
volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_FAR]);
volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_BOTTOM]);
volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_TOP]);
volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_LEFT]);
volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_RIGHT]);
return volume;
}
//---------------------------------------------------------------------
void Frustum::setOrientationMode(OrientationMode orientationMode)
{
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"Setting Frustrum orientation mode is not supported",
__FUNCTION__);
#endif
mOrientationMode = orientationMode;
invalidateFrustum();
}
//---------------------------------------------------------------------
OrientationMode Frustum::getOrientationMode() const
{
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"Getting Frustrum orientation mode is not supported",
__FUNCTION__);
#endif
return mOrientationMode;
}
} // namespace Ogre
| 37.607429 | 103 | 0.482696 | [
"object",
"vector",
"transform"
] |
104159b3ffe82a6e7ae6cfd1d7f21d5908b9bbdf | 2,510 | cpp | C++ | hphp/runtime/base/req-root.cpp | donsbot/hhvm | ac98a590f75c569e1249b6c1145c7512c7bd240e | [
"PHP-3.01",
"Zend-2.0"
] | 9,491 | 2015-01-01T00:30:28.000Z | 2022-03-31T20:22:11.000Z | hphp/runtime/base/req-root.cpp | donsbot/hhvm | ac98a590f75c569e1249b6c1145c7512c7bd240e | [
"PHP-3.01",
"Zend-2.0"
] | 4,796 | 2015-01-01T00:26:31.000Z | 2022-03-31T01:09:05.000Z | hphp/runtime/base/req-root.cpp | donsbot/hhvm | ac98a590f75c569e1249b6c1145c7512c7bd240e | [
"PHP-3.01",
"Zend-2.0"
] | 2,126 | 2015-01-01T11:13:29.000Z | 2022-03-28T19:58:15.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/req-root.h"
#include "hphp/runtime/base/typed-value.h"
#include "hphp/runtime/base/type-string.h"
#include "hphp/runtime/base/type-array.h"
#include "hphp/runtime/base/type-object.h"
#include "hphp/runtime/base/type-variant.h"
#include "hphp/runtime/base/ini-setting.h"
#include "hphp/util/safe-cast.h"
namespace HPHP {
namespace req {
uint32_t req::root_handle::addRootHandle() {
auto& handles = tl_heap->m_root_handles;
auto id = safe_cast<uint32_t>(handles.size());
handles.push_back(this);
return id;
}
uint32_t req::root_handle::stealRootHandle(root_handle* s) {
assertx(s->m_id != INVALID);
auto& handles = tl_heap->m_root_handles;
auto id = s->m_id;
handles[id] = this;
s->m_id = INVALID;
return id;
}
void req::root_handle::delRootHandle() {
auto& handles = tl_heap->m_root_handles;
auto last = handles.back();
handles[last->m_id = m_id] = last;
m_id = INVALID;
handles.pop_back();
}
template<class T> void root<T>::scan(type_scan::Scanner& scanner) const {
scanner.scan(*static_cast<const T*>(this));
}
template<class T> void root<T>::detach() {
T::detach();
}
template<> void req::root<TypedValue>::scan(type_scan::Scanner& scanner) const {
scanner.scan(*static_cast<const TypedValue*>(this));
}
template<> void req::root<TypedValue>::detach() {
m_type = KindOfNull;
}
template struct root<String>;
template struct root<Array>;
template struct root<Object>;
template struct root<Variant>;
template struct root<IniSettingMap>;
}}
| 33.026316 | 80 | 0.58247 | [
"object"
] |
104175f8d32f5838bb3f487479ac0ff3b7d2a93a | 479 | cpp | C++ | aws-cpp-sdk-mq/source/model/ListTagsRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-mq/source/model/ListTagsRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-mq/source/model/ListTagsRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mq/model/ListTagsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::MQ::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
ListTagsRequest::ListTagsRequest() :
m_resourceArnHasBeenSet(false)
{
}
Aws::String ListTagsRequest::SerializePayload() const
{
return {};
}
| 17.107143 | 69 | 0.726514 | [
"model"
] |
1041ac85dc30b4d76784c1e522229800f6c44100 | 3,017 | cpp | C++ | libredex/Mutators.cpp | sjndhkl/redex | f6da510e67da284b0093bf01e2e9357d8b963cfd | [
"BSD-3-Clause"
] | null | null | null | libredex/Mutators.cpp | sjndhkl/redex | f6da510e67da284b0093bf01e2e9357d8b963cfd | [
"BSD-3-Clause"
] | null | null | null | libredex/Mutators.cpp | sjndhkl/redex | f6da510e67da284b0093bf01e2e9357d8b963cfd | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "DexUtil.h"
#include "Mutators.h"
#include "Transform.h"
namespace {
void drop_this(DexMethod* method) {
auto const& code = method->get_code();
if (!code) return;
auto nregs = code->get_registers_size();
auto nins = code->get_ins_size();
auto const this_reg = nregs - nins;
assert_log(nregs >= 1, "Too few regs: %s\n", SHOW(method));
assert_log(nins >= 1, "Too few in regs: %s\n", SHOW(method));
code->set_registers_size(nregs - 1);
code->set_ins_size(nins - 1);
for (auto& mie : InstructionIterable(code->get_entries())) {
auto insn = mie.insn;
if (insn->dests_size() && !insn->dest_is_src()) {
auto dest = insn->dest();
assert(dest != this_reg);
assert(!insn->dest_is_wide() || insn->dest() != (this_reg - 1));
if (dest > this_reg) {
insn->set_dest(dest - 1);
}
}
for (unsigned i = 0; i < insn->srcs_size(); i++) {
auto src = insn->src(i);
assert_log(src != this_reg, "method: %s\ninsn: %s\n", SHOW(method), SHOW(insn));
assert(!insn->src_is_wide(i) || insn->src(i) != (this_reg - 1));
if (src > this_reg) {
insn->set_src(i, src - 1);
}
}
if (insn->has_range() && insn->range_base() > this_reg) {
insn->set_range_base(insn->range_base() - 1);
}
}
}
}
namespace mutators {
void make_static(DexMethod* method, KeepThis keep /* = Yes */) {
auto proto = method->get_proto();
auto params = proto->get_args()->get_type_list();
auto clstype = method->get_class();
if (keep == KeepThis::Yes) {
// make `this` an explicit parameter
params.push_front(clstype);
auto new_args = DexTypeList::make_type_list(std::move(params));
auto new_proto = DexProto::make_proto(proto->get_rtype(), new_args);
DexMethodRef ref;
ref.proto = new_proto;
method->change(ref, true /* rename_on_collision */);
auto& code = method->get_code();
// If the debug info param count doesn't match the param count in the
// method signature, ART will not parse any of the debug info for the
// method. Note that this shows up as a runtime error and not a
// verification error. To avoid that, we insert a nullptr here.
if (code) {
auto& debug = code->get_debug_item();
if (debug) {
auto& param_names = debug->get_param_names();
param_names.insert(param_names.begin(), nullptr);
}
}
} else {
drop_this(method);
}
method->set_access(method->get_access() | ACC_STATIC);
// changing the method proto means that we need to change its position in the
// dmethod list
auto cls = type_class(clstype);
cls->remove_method(method);
method->set_virtual(false);
cls->add_method(method);
}
}
| 33.153846 | 86 | 0.64004 | [
"transform"
] |
1041f63aa2e295b6999ae82a7b6b9bcddaa0ea1f | 40,767 | cpp | C++ | lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp | c834606877/llvm-project | 01de58136ae4971b8d7d32a765092121f9975377 | [
"Apache-2.0"
] | 5 | 2021-02-21T22:35:08.000Z | 2022-02-01T18:22:50.000Z | lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp | c834606877/llvm-project | 01de58136ae4971b8d7d32a765092121f9975377 | [
"Apache-2.0"
] | null | null | null | lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp | c834606877/llvm-project | 01de58136ae4971b8d7d32a765092121f9975377 | [
"Apache-2.0"
] | 1 | 2021-03-30T11:22:52.000Z | 2021-03-30T11:22:52.000Z | //===-- ProcessMinidump.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "ProcessMinidump.h"
#include "ThreadMinidump.h"
#include "lldb/Core/DumpDataExtractor.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandObject.h"
#include "lldb/Interpreter/CommandObjectMultiword.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Interpreter/OptionArgParser.h"
#include "lldb/Interpreter/OptionGroupBoolean.h"
#include "lldb/Target/JITLoaderList.h"
#include "lldb/Target/MemoryRegionInfo.h"
#include "lldb/Target/SectionLoadList.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/UnixSignals.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/State.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Threading.h"
#include "Plugins/Process/Utility/StopInfoMachException.h"
#include <memory>
using namespace lldb;
using namespace lldb_private;
using namespace minidump;
LLDB_PLUGIN_DEFINE(ProcessMinidump)
namespace {
/// A minimal ObjectFile implementation providing a dummy object file for the
/// cases when the real module binary is not available. This allows the module
/// to show up in "image list" and symbols to be added to it.
class PlaceholderObjectFile : public ObjectFile {
public:
PlaceholderObjectFile(const lldb::ModuleSP &module_sp,
const ModuleSpec &module_spec, lldb::addr_t base,
lldb::addr_t size)
: ObjectFile(module_sp, &module_spec.GetFileSpec(), /*file_offset*/ 0,
/*length*/ 0, /*data_sp*/ nullptr, /*data_offset*/ 0),
m_arch(module_spec.GetArchitecture()), m_uuid(module_spec.GetUUID()),
m_base(base), m_size(size) {
m_symtab_up = std::make_unique<Symtab>(this);
}
static ConstString GetStaticPluginName() {
return ConstString("placeholder");
}
ConstString GetPluginName() override { return GetStaticPluginName(); }
uint32_t GetPluginVersion() override { return 1; }
bool ParseHeader() override { return true; }
Type CalculateType() override { return eTypeUnknown; }
Strata CalculateStrata() override { return eStrataUnknown; }
uint32_t GetDependentModules(FileSpecList &file_list) override { return 0; }
bool IsExecutable() const override { return false; }
ArchSpec GetArchitecture() override { return m_arch; }
UUID GetUUID() override { return m_uuid; }
Symtab *GetSymtab() override { return m_symtab_up.get(); }
bool IsStripped() override { return true; }
ByteOrder GetByteOrder() const override { return m_arch.GetByteOrder(); }
uint32_t GetAddressByteSize() const override {
return m_arch.GetAddressByteSize();
}
Address GetBaseAddress() override {
return Address(m_sections_up->GetSectionAtIndex(0), 0);
}
void CreateSections(SectionList &unified_section_list) override {
m_sections_up = std::make_unique<SectionList>();
auto section_sp = std::make_shared<Section>(
GetModule(), this, /*sect_id*/ 0, ConstString(".module_image"),
eSectionTypeOther, m_base, m_size, /*file_offset*/ 0, /*file_size*/ 0,
/*log2align*/ 0, /*flags*/ 0);
section_sp->SetPermissions(ePermissionsReadable | ePermissionsExecutable);
m_sections_up->AddSection(section_sp);
unified_section_list.AddSection(std::move(section_sp));
}
bool SetLoadAddress(Target &target, addr_t value,
bool value_is_offset) override {
assert(!value_is_offset);
assert(value == m_base);
// Create sections if they haven't been created already.
GetModule()->GetSectionList();
assert(m_sections_up->GetNumSections(0) == 1);
target.GetSectionLoadList().SetSectionLoadAddress(
m_sections_up->GetSectionAtIndex(0), m_base);
return true;
}
void Dump(Stream *s) override {
s->Format("Placeholder object file for {0} loaded at [{1:x}-{2:x})\n",
GetFileSpec(), m_base, m_base + m_size);
}
lldb::addr_t GetBaseImageAddress() const { return m_base; }
private:
ArchSpec m_arch;
UUID m_uuid;
lldb::addr_t m_base;
lldb::addr_t m_size;
};
/// Duplicate the HashElfTextSection() from the breakpad sources.
///
/// Breakpad, a Google crash log reporting tool suite, creates minidump files
/// for many different architectures. When using Breakpad to create ELF
/// minidumps, it will check for a GNU build ID when creating a minidump file
/// and if one doesn't exist in the file, it will say the UUID of the file is a
/// checksum of up to the first 4096 bytes of the .text section. Facebook also
/// uses breakpad and modified this hash to avoid collisions so we can
/// calculate and check for this as well.
///
/// The breakpad code might end up hashing up to 15 bytes that immediately
/// follow the .text section in the file, so this code must do exactly what it
/// does so we can get an exact match for the UUID.
///
/// \param[in] module_sp The module to grab the .text section from.
///
/// \param[in/out] breakpad_uuid A vector that will receive the calculated
/// breakpad .text hash.
///
/// \param[in/out] facebook_uuid A vector that will receive the calculated
/// facebook .text hash.
///
void HashElfTextSection(ModuleSP module_sp, std::vector<uint8_t> &breakpad_uuid,
std::vector<uint8_t> &facebook_uuid) {
SectionList *sect_list = module_sp->GetSectionList();
if (sect_list == nullptr)
return;
SectionSP sect_sp = sect_list->FindSectionByName(ConstString(".text"));
if (!sect_sp)
return;
constexpr size_t kMDGUIDSize = 16;
constexpr size_t kBreakpadPageSize = 4096;
// The breakpad code has a bug where it might access beyond the end of a
// .text section by up to 15 bytes, so we must ensure we round up to the
// next kMDGUIDSize byte boundary.
DataExtractor data;
const size_t text_size = sect_sp->GetFileSize();
const size_t read_size = std::min<size_t>(
llvm::alignTo(text_size, kMDGUIDSize), kBreakpadPageSize);
sect_sp->GetObjectFile()->GetData(sect_sp->GetFileOffset(), read_size, data);
breakpad_uuid.assign(kMDGUIDSize, 0);
facebook_uuid.assign(kMDGUIDSize, 0);
// The only difference between the breakpad hash and the facebook hash is the
// hashing of the text section size into the hash prior to hashing the .text
// contents.
for (size_t i = 0; i < kMDGUIDSize; i++)
facebook_uuid[i] ^= text_size % 255;
// This code carefully duplicates how the hash was created in Breakpad
// sources, including the error where it might has an extra 15 bytes past the
// end of the .text section if the .text section is less than a page size in
// length.
const uint8_t *ptr = data.GetDataStart();
const uint8_t *ptr_end = data.GetDataEnd();
while (ptr < ptr_end) {
for (unsigned i = 0; i < kMDGUIDSize; i++) {
breakpad_uuid[i] ^= ptr[i];
facebook_uuid[i] ^= ptr[i];
}
ptr += kMDGUIDSize;
}
}
} // namespace
ConstString ProcessMinidump::GetPluginNameStatic() {
static ConstString g_name("minidump");
return g_name;
}
const char *ProcessMinidump::GetPluginDescriptionStatic() {
return "Minidump plug-in.";
}
lldb::ProcessSP ProcessMinidump::CreateInstance(lldb::TargetSP target_sp,
lldb::ListenerSP listener_sp,
const FileSpec *crash_file) {
if (!crash_file)
return nullptr;
lldb::ProcessSP process_sp;
// Read enough data for the Minidump header
constexpr size_t header_size = sizeof(Header);
auto DataPtr = FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(),
header_size, 0);
if (!DataPtr)
return nullptr;
lldbassert(DataPtr->GetByteSize() == header_size);
if (identify_magic(toStringRef(DataPtr->GetData())) != llvm::file_magic::minidump)
return nullptr;
auto AllData =
FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(), -1, 0);
if (!AllData)
return nullptr;
return std::make_shared<ProcessMinidump>(target_sp, listener_sp, *crash_file,
std::move(AllData));
}
bool ProcessMinidump::CanDebug(lldb::TargetSP target_sp,
bool plugin_specified_by_name) {
return true;
}
ProcessMinidump::ProcessMinidump(lldb::TargetSP target_sp,
lldb::ListenerSP listener_sp,
const FileSpec &core_file,
DataBufferSP core_data)
: Process(target_sp, listener_sp), m_core_file(core_file),
m_core_data(std::move(core_data)), m_is_wow64(false) {}
ProcessMinidump::~ProcessMinidump() {
Clear();
// We need to call finalize on the process before destroying ourselves to
// make sure all of the broadcaster cleanup goes as planned. If we destruct
// this class, then Process::~Process() might have problems trying to fully
// destroy the broadcaster.
Finalize();
}
void ProcessMinidump::Initialize() {
static llvm::once_flag g_once_flag;
llvm::call_once(g_once_flag, []() {
PluginManager::RegisterPlugin(GetPluginNameStatic(),
GetPluginDescriptionStatic(),
ProcessMinidump::CreateInstance);
});
}
void ProcessMinidump::Terminate() {
PluginManager::UnregisterPlugin(ProcessMinidump::CreateInstance);
}
Status ProcessMinidump::DoLoadCore() {
auto expected_parser = MinidumpParser::Create(m_core_data);
if (!expected_parser)
return Status(expected_parser.takeError());
m_minidump_parser = std::move(*expected_parser);
Status error;
// Do we support the minidump's architecture?
ArchSpec arch = GetArchitecture();
switch (arch.GetMachine()) {
case llvm::Triple::x86:
case llvm::Triple::x86_64:
case llvm::Triple::arm:
case llvm::Triple::aarch64:
// Any supported architectures must be listed here and also supported in
// ThreadMinidump::CreateRegisterContextForFrame().
break;
default:
error.SetErrorStringWithFormat("unsupported minidump architecture: %s",
arch.GetArchitectureName());
return error;
}
GetTarget().SetArchitecture(arch, true /*set_platform*/);
m_thread_list = m_minidump_parser->GetThreads();
m_active_exception = m_minidump_parser->GetExceptionStream();
SetUnixSignals(UnixSignals::Create(GetArchitecture()));
ReadModuleList();
llvm::Optional<lldb::pid_t> pid = m_minidump_parser->GetPid();
if (!pid) {
GetTarget().GetDebugger().GetAsyncErrorStream()->PutCString(
"Unable to retrieve process ID from minidump file, setting process ID "
"to 1.\n");
pid = 1;
}
SetID(pid.getValue());
return error;
}
ConstString ProcessMinidump::GetPluginName() { return GetPluginNameStatic(); }
uint32_t ProcessMinidump::GetPluginVersion() { return 1; }
Status ProcessMinidump::DoDestroy() { return Status(); }
void ProcessMinidump::RefreshStateAfterStop() {
if (!m_active_exception)
return;
constexpr uint32_t BreakpadDumpRequested = 0xFFFFFFFF;
if (m_active_exception->ExceptionRecord.ExceptionCode ==
BreakpadDumpRequested) {
// This "ExceptionCode" value is a sentinel that is sometimes used
// when generating a dump for a process that hasn't crashed.
// TODO: The definition and use of this "dump requested" constant
// in Breakpad are actually Linux-specific, and for similar use
// cases on Mac/Windows it defines different constants, referring
// to them as "simulated" exceptions; consider moving this check
// down to the OS-specific paths and checking each OS for its own
// constant.
return;
}
lldb::StopInfoSP stop_info;
lldb::ThreadSP stop_thread;
Process::m_thread_list.SetSelectedThreadByID(m_active_exception->ThreadId);
stop_thread = Process::m_thread_list.GetSelectedThread();
ArchSpec arch = GetArchitecture();
if (arch.GetTriple().getOS() == llvm::Triple::Linux) {
uint32_t signo = m_active_exception->ExceptionRecord.ExceptionCode;
if (signo == 0) {
// No stop.
return;
}
stop_info = StopInfo::CreateStopReasonWithSignal(
*stop_thread, signo);
} else if (arch.GetTriple().getVendor() == llvm::Triple::Apple) {
stop_info = StopInfoMachException::CreateStopReasonWithMachException(
*stop_thread, m_active_exception->ExceptionRecord.ExceptionCode, 2,
m_active_exception->ExceptionRecord.ExceptionFlags,
m_active_exception->ExceptionRecord.ExceptionAddress, 0);
} else {
std::string desc;
llvm::raw_string_ostream desc_stream(desc);
desc_stream << "Exception "
<< llvm::format_hex(
m_active_exception->ExceptionRecord.ExceptionCode, 8)
<< " encountered at address "
<< llvm::format_hex(
m_active_exception->ExceptionRecord.ExceptionAddress, 8);
stop_info = StopInfo::CreateStopReasonWithException(
*stop_thread, desc_stream.str().c_str());
}
stop_thread->SetStopInfo(stop_info);
}
bool ProcessMinidump::IsAlive() { return true; }
bool ProcessMinidump::WarnBeforeDetach() const { return false; }
size_t ProcessMinidump::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
Status &error) {
// Don't allow the caching that lldb_private::Process::ReadMemory does since
// we have it all cached in our dump file anyway.
return DoReadMemory(addr, buf, size, error);
}
size_t ProcessMinidump::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
Status &error) {
llvm::ArrayRef<uint8_t> mem = m_minidump_parser->GetMemory(addr, size);
if (mem.empty()) {
error.SetErrorString("could not parse memory info");
return 0;
}
std::memcpy(buf, mem.data(), mem.size());
return mem.size();
}
ArchSpec ProcessMinidump::GetArchitecture() {
if (!m_is_wow64) {
return m_minidump_parser->GetArchitecture();
}
llvm::Triple triple;
triple.setVendor(llvm::Triple::VendorType::UnknownVendor);
triple.setArch(llvm::Triple::ArchType::x86);
triple.setOS(llvm::Triple::OSType::Win32);
return ArchSpec(triple);
}
static MemoryRegionInfo GetMemoryRegionInfo(const MemoryRegionInfos ®ions,
lldb::addr_t load_addr) {
MemoryRegionInfo region;
auto pos = llvm::upper_bound(regions, load_addr);
if (pos != regions.begin() &&
std::prev(pos)->GetRange().Contains(load_addr)) {
return *std::prev(pos);
}
if (pos == regions.begin())
region.GetRange().SetRangeBase(0);
else
region.GetRange().SetRangeBase(std::prev(pos)->GetRange().GetRangeEnd());
if (pos == regions.end())
region.GetRange().SetRangeEnd(UINT64_MAX);
else
region.GetRange().SetRangeEnd(pos->GetRange().GetRangeBase());
region.SetReadable(MemoryRegionInfo::eNo);
region.SetWritable(MemoryRegionInfo::eNo);
region.SetExecutable(MemoryRegionInfo::eNo);
region.SetMapped(MemoryRegionInfo::eNo);
return region;
}
void ProcessMinidump::BuildMemoryRegions() {
if (m_memory_regions)
return;
m_memory_regions.emplace();
bool is_complete;
std::tie(*m_memory_regions, is_complete) =
m_minidump_parser->BuildMemoryRegions();
if (is_complete)
return;
MemoryRegionInfos to_add;
ModuleList &modules = GetTarget().GetImages();
SectionLoadList &load_list = GetTarget().GetSectionLoadList();
modules.ForEach([&](const ModuleSP &module_sp) {
SectionList *sections = module_sp->GetSectionList();
for (size_t i = 0; i < sections->GetSize(); ++i) {
SectionSP section_sp = sections->GetSectionAtIndex(i);
addr_t load_addr = load_list.GetSectionLoadAddress(section_sp);
if (load_addr == LLDB_INVALID_ADDRESS)
continue;
MemoryRegionInfo::RangeType section_range(load_addr,
section_sp->GetByteSize());
MemoryRegionInfo region =
::GetMemoryRegionInfo(*m_memory_regions, load_addr);
if (region.GetMapped() != MemoryRegionInfo::eYes &&
region.GetRange().GetRangeBase() <= section_range.GetRangeBase() &&
section_range.GetRangeEnd() <= region.GetRange().GetRangeEnd()) {
to_add.emplace_back();
to_add.back().GetRange() = section_range;
to_add.back().SetLLDBPermissions(section_sp->GetPermissions());
to_add.back().SetMapped(MemoryRegionInfo::eYes);
to_add.back().SetName(module_sp->GetFileSpec().GetPath().c_str());
}
}
return true;
});
m_memory_regions->insert(m_memory_regions->end(), to_add.begin(),
to_add.end());
llvm::sort(*m_memory_regions);
}
Status ProcessMinidump::GetMemoryRegionInfo(lldb::addr_t load_addr,
MemoryRegionInfo ®ion) {
BuildMemoryRegions();
region = ::GetMemoryRegionInfo(*m_memory_regions, load_addr);
return Status();
}
Status ProcessMinidump::GetMemoryRegions(MemoryRegionInfos ®ion_list) {
BuildMemoryRegions();
region_list = *m_memory_regions;
return Status();
}
void ProcessMinidump::Clear() { Process::m_thread_list.Clear(); }
bool ProcessMinidump::UpdateThreadList(ThreadList &old_thread_list,
ThreadList &new_thread_list) {
for (const minidump::Thread &thread : m_thread_list) {
LocationDescriptor context_location = thread.Context;
// If the minidump contains an exception context, use it
if (m_active_exception != nullptr &&
m_active_exception->ThreadId == thread.ThreadId) {
context_location = m_active_exception->ThreadContext;
}
llvm::ArrayRef<uint8_t> context;
if (!m_is_wow64)
context = m_minidump_parser->GetThreadContext(context_location);
else
context = m_minidump_parser->GetThreadContextWow64(thread);
lldb::ThreadSP thread_sp(new ThreadMinidump(*this, thread, context));
new_thread_list.AddThread(thread_sp);
}
return new_thread_list.GetSize(false) > 0;
}
ModuleSP ProcessMinidump::GetOrCreateModule(UUID minidump_uuid,
llvm::StringRef name,
ModuleSpec module_spec) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
Status error;
ModuleSP module_sp =
GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
if (!module_sp)
return module_sp;
// We consider the module to be a match if the minidump UUID is a
// prefix of the actual UUID, or if either of the UUIDs are empty.
const auto dmp_bytes = minidump_uuid.GetBytes();
const auto mod_bytes = module_sp->GetUUID().GetBytes();
const bool match = dmp_bytes.empty() || mod_bytes.empty() ||
mod_bytes.take_front(dmp_bytes.size()) == dmp_bytes;
if (match) {
LLDB_LOG(log, "Partial uuid match for {0}.", name);
return module_sp;
}
// Breakpad generates minindump files, and if there is no GNU build
// ID in the binary, it will calculate a UUID by hashing first 4096
// bytes of the .text section and using that as the UUID for a module
// in the minidump. Facebook uses a modified breakpad client that
// uses a slightly modified this hash to avoid collisions. Check for
// UUIDs from the minindump that match these cases and accept the
// module we find if they do match.
std::vector<uint8_t> breakpad_uuid;
std::vector<uint8_t> facebook_uuid;
HashElfTextSection(module_sp, breakpad_uuid, facebook_uuid);
if (dmp_bytes == llvm::ArrayRef<uint8_t>(breakpad_uuid)) {
LLDB_LOG(log, "Breakpad .text hash match for {0}.", name);
return module_sp;
}
if (dmp_bytes == llvm::ArrayRef<uint8_t>(facebook_uuid)) {
LLDB_LOG(log, "Facebook .text hash match for {0}.", name);
return module_sp;
}
// The UUID wasn't a partial match and didn't match the .text hash
// so remove the module from the target, we will need to create a
// placeholder object file.
GetTarget().GetImages().Remove(module_sp);
module_sp.reset();
return module_sp;
}
void ProcessMinidump::ReadModuleList() {
std::vector<const minidump::Module *> filtered_modules =
m_minidump_parser->GetFilteredModuleList();
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
for (auto module : filtered_modules) {
std::string name = cantFail(m_minidump_parser->GetMinidumpFile().getString(
module->ModuleNameRVA));
const uint64_t load_addr = module->BaseOfImage;
const uint64_t load_size = module->SizeOfImage;
LLDB_LOG(log, "found module: name: {0} {1:x10}-{2:x10} size: {3}", name,
load_addr, load_addr + load_size, load_size);
// check if the process is wow64 - a 32 bit windows process running on a
// 64 bit windows
if (llvm::StringRef(name).endswith_lower("wow64.dll")) {
m_is_wow64 = true;
}
const auto uuid = m_minidump_parser->GetModuleUUID(module);
auto file_spec = FileSpec(name, GetArchitecture().GetTriple());
ModuleSpec module_spec(file_spec, uuid);
module_spec.GetArchitecture() = GetArchitecture();
Status error;
// Try and find a module with a full UUID that matches. This function will
// add the module to the target if it finds one.
lldb::ModuleSP module_sp = GetTarget().GetOrCreateModule(module_spec,
true /* notify */, &error);
if (module_sp) {
LLDB_LOG(log, "Full uuid match for {0}.", name);
} else {
// We couldn't find a module with an exactly-matching UUID. Sometimes
// a minidump UUID is only a partial match or is a hash. So try again
// without specifying the UUID, then again without specifying the
// directory if that fails. This will allow us to find modules with
// partial matches or hash UUIDs in user-provided sysroots or search
// directories (target.exec-search-paths).
ModuleSpec partial_module_spec = module_spec;
partial_module_spec.GetUUID().Clear();
module_sp = GetOrCreateModule(uuid, name, partial_module_spec);
if (!module_sp) {
partial_module_spec.GetFileSpec().GetDirectory().Clear();
module_sp = GetOrCreateModule(uuid, name, partial_module_spec);
}
}
if (module_sp) {
// Watch out for place holder modules that have different paths, but the
// same UUID. If the base address is different, create a new module. If
// we don't then we will end up setting the load address of a different
// PlaceholderObjectFile and an assertion will fire.
auto *objfile = module_sp->GetObjectFile();
if (objfile && objfile->GetPluginName() ==
PlaceholderObjectFile::GetStaticPluginName()) {
if (((PlaceholderObjectFile *)objfile)->GetBaseImageAddress() !=
load_addr)
module_sp.reset();
}
}
if (!module_sp) {
// We failed to locate a matching local object file. Fortunately, the
// minidump format encodes enough information about each module's memory
// range to allow us to create placeholder modules.
//
// This enables most LLDB functionality involving address-to-module
// translations (ex. identifing the module for a stack frame PC) and
// modules/sections commands (ex. target modules list, ...)
LLDB_LOG(log,
"Unable to locate the matching object file, creating a "
"placeholder module for: {0}",
name);
module_sp = Module::CreateModuleFromObjectFile<PlaceholderObjectFile>(
module_spec, load_addr, load_size);
GetTarget().GetImages().Append(module_sp, true /* notify */);
}
bool load_addr_changed = false;
module_sp->SetLoadAddress(GetTarget(), load_addr, false,
load_addr_changed);
}
}
bool ProcessMinidump::GetProcessInfo(ProcessInstanceInfo &info) {
info.Clear();
info.SetProcessID(GetID());
info.SetArchitecture(GetArchitecture());
lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
if (module_sp) {
const bool add_exe_file_as_first_arg = false;
info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
add_exe_file_as_first_arg);
}
return true;
}
// For minidumps there's no runtime generated code so we don't need JITLoader(s)
// Avoiding them will also speed up minidump loading since JITLoaders normally
// try to set up symbolic breakpoints, which in turn may force loading more
// debug information than needed.
JITLoaderList &ProcessMinidump::GetJITLoaders() {
if (!m_jit_loaders_up) {
m_jit_loaders_up = std::make_unique<JITLoaderList>();
}
return *m_jit_loaders_up;
}
#define INIT_BOOL(VAR, LONG, SHORT, DESC) \
VAR(LLDB_OPT_SET_1, false, LONG, SHORT, DESC, false, true)
#define APPEND_OPT(VAR) \
m_option_group.Append(&VAR, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1)
class CommandObjectProcessMinidumpDump : public CommandObjectParsed {
private:
OptionGroupOptions m_option_group;
OptionGroupBoolean m_dump_all;
OptionGroupBoolean m_dump_directory;
OptionGroupBoolean m_dump_linux_cpuinfo;
OptionGroupBoolean m_dump_linux_proc_status;
OptionGroupBoolean m_dump_linux_lsb_release;
OptionGroupBoolean m_dump_linux_cmdline;
OptionGroupBoolean m_dump_linux_environ;
OptionGroupBoolean m_dump_linux_auxv;
OptionGroupBoolean m_dump_linux_maps;
OptionGroupBoolean m_dump_linux_proc_stat;
OptionGroupBoolean m_dump_linux_proc_uptime;
OptionGroupBoolean m_dump_linux_proc_fd;
OptionGroupBoolean m_dump_linux_all;
OptionGroupBoolean m_fb_app_data;
OptionGroupBoolean m_fb_build_id;
OptionGroupBoolean m_fb_version;
OptionGroupBoolean m_fb_java_stack;
OptionGroupBoolean m_fb_dalvik;
OptionGroupBoolean m_fb_unwind;
OptionGroupBoolean m_fb_error_log;
OptionGroupBoolean m_fb_app_state;
OptionGroupBoolean m_fb_abort;
OptionGroupBoolean m_fb_thread;
OptionGroupBoolean m_fb_logcat;
OptionGroupBoolean m_fb_all;
void SetDefaultOptionsIfNoneAreSet() {
if (m_dump_all.GetOptionValue().GetCurrentValue() ||
m_dump_linux_all.GetOptionValue().GetCurrentValue() ||
m_fb_all.GetOptionValue().GetCurrentValue() ||
m_dump_directory.GetOptionValue().GetCurrentValue() ||
m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue() ||
m_dump_linux_proc_status.GetOptionValue().GetCurrentValue() ||
m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue() ||
m_dump_linux_cmdline.GetOptionValue().GetCurrentValue() ||
m_dump_linux_environ.GetOptionValue().GetCurrentValue() ||
m_dump_linux_auxv.GetOptionValue().GetCurrentValue() ||
m_dump_linux_maps.GetOptionValue().GetCurrentValue() ||
m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue() ||
m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue() ||
m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue() ||
m_fb_app_data.GetOptionValue().GetCurrentValue() ||
m_fb_build_id.GetOptionValue().GetCurrentValue() ||
m_fb_version.GetOptionValue().GetCurrentValue() ||
m_fb_java_stack.GetOptionValue().GetCurrentValue() ||
m_fb_dalvik.GetOptionValue().GetCurrentValue() ||
m_fb_unwind.GetOptionValue().GetCurrentValue() ||
m_fb_error_log.GetOptionValue().GetCurrentValue() ||
m_fb_app_state.GetOptionValue().GetCurrentValue() ||
m_fb_abort.GetOptionValue().GetCurrentValue() ||
m_fb_thread.GetOptionValue().GetCurrentValue() ||
m_fb_logcat.GetOptionValue().GetCurrentValue())
return;
// If no options were set, then dump everything
m_dump_all.GetOptionValue().SetCurrentValue(true);
}
bool DumpAll() const {
return m_dump_all.GetOptionValue().GetCurrentValue();
}
bool DumpDirectory() const {
return DumpAll() ||
m_dump_directory.GetOptionValue().GetCurrentValue();
}
bool DumpLinux() const {
return DumpAll() || m_dump_linux_all.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxCPUInfo() const {
return DumpLinux() ||
m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxProcStatus() const {
return DumpLinux() ||
m_dump_linux_proc_status.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxProcStat() const {
return DumpLinux() ||
m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxLSBRelease() const {
return DumpLinux() ||
m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxCMDLine() const {
return DumpLinux() ||
m_dump_linux_cmdline.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxEnviron() const {
return DumpLinux() ||
m_dump_linux_environ.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxAuxv() const {
return DumpLinux() ||
m_dump_linux_auxv.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxMaps() const {
return DumpLinux() ||
m_dump_linux_maps.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxProcUptime() const {
return DumpLinux() ||
m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue();
}
bool DumpLinuxProcFD() const {
return DumpLinux() ||
m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue();
}
bool DumpFacebook() const {
return DumpAll() || m_fb_all.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookAppData() const {
return DumpFacebook() || m_fb_app_data.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookBuildID() const {
return DumpFacebook() || m_fb_build_id.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookVersionName() const {
return DumpFacebook() || m_fb_version.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookJavaStack() const {
return DumpFacebook() || m_fb_java_stack.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookDalvikInfo() const {
return DumpFacebook() || m_fb_dalvik.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookUnwindSymbols() const {
return DumpFacebook() || m_fb_unwind.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookErrorLog() const {
return DumpFacebook() || m_fb_error_log.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookAppStateLog() const {
return DumpFacebook() || m_fb_app_state.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookAbortReason() const {
return DumpFacebook() || m_fb_abort.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookThreadName() const {
return DumpFacebook() || m_fb_thread.GetOptionValue().GetCurrentValue();
}
bool DumpFacebookLogcat() const {
return DumpFacebook() || m_fb_logcat.GetOptionValue().GetCurrentValue();
}
public:
CommandObjectProcessMinidumpDump(CommandInterpreter &interpreter)
: CommandObjectParsed(interpreter, "process plugin dump",
"Dump information from the minidump file.", nullptr),
m_option_group(),
INIT_BOOL(m_dump_all, "all", 'a',
"Dump the everything in the minidump."),
INIT_BOOL(m_dump_directory, "directory", 'd',
"Dump the minidump directory map."),
INIT_BOOL(m_dump_linux_cpuinfo, "cpuinfo", 'C',
"Dump linux /proc/cpuinfo."),
INIT_BOOL(m_dump_linux_proc_status, "status", 's',
"Dump linux /proc/<pid>/status."),
INIT_BOOL(m_dump_linux_lsb_release, "lsb-release", 'r',
"Dump linux /etc/lsb-release."),
INIT_BOOL(m_dump_linux_cmdline, "cmdline", 'c',
"Dump linux /proc/<pid>/cmdline."),
INIT_BOOL(m_dump_linux_environ, "environ", 'e',
"Dump linux /proc/<pid>/environ."),
INIT_BOOL(m_dump_linux_auxv, "auxv", 'x',
"Dump linux /proc/<pid>/auxv."),
INIT_BOOL(m_dump_linux_maps, "maps", 'm',
"Dump linux /proc/<pid>/maps."),
INIT_BOOL(m_dump_linux_proc_stat, "stat", 'S',
"Dump linux /proc/<pid>/stat."),
INIT_BOOL(m_dump_linux_proc_uptime, "uptime", 'u',
"Dump linux process uptime."),
INIT_BOOL(m_dump_linux_proc_fd, "fd", 'f',
"Dump linux /proc/<pid>/fd."),
INIT_BOOL(m_dump_linux_all, "linux", 'l',
"Dump all linux streams."),
INIT_BOOL(m_fb_app_data, "fb-app-data", 1,
"Dump Facebook application custom data."),
INIT_BOOL(m_fb_build_id, "fb-build-id", 2,
"Dump the Facebook build ID."),
INIT_BOOL(m_fb_version, "fb-version", 3,
"Dump Facebook application version string."),
INIT_BOOL(m_fb_java_stack, "fb-java-stack", 4,
"Dump Facebook java stack."),
INIT_BOOL(m_fb_dalvik, "fb-dalvik-info", 5,
"Dump Facebook Dalvik info."),
INIT_BOOL(m_fb_unwind, "fb-unwind-symbols", 6,
"Dump Facebook unwind symbols."),
INIT_BOOL(m_fb_error_log, "fb-error-log", 7,
"Dump Facebook error log."),
INIT_BOOL(m_fb_app_state, "fb-app-state-log", 8,
"Dump Facebook java stack."),
INIT_BOOL(m_fb_abort, "fb-abort-reason", 9,
"Dump Facebook abort reason."),
INIT_BOOL(m_fb_thread, "fb-thread-name", 10,
"Dump Facebook thread name."),
INIT_BOOL(m_fb_logcat, "fb-logcat", 11,
"Dump Facebook logcat."),
INIT_BOOL(m_fb_all, "facebook", 12, "Dump all Facebook streams.") {
APPEND_OPT(m_dump_all);
APPEND_OPT(m_dump_directory);
APPEND_OPT(m_dump_linux_cpuinfo);
APPEND_OPT(m_dump_linux_proc_status);
APPEND_OPT(m_dump_linux_lsb_release);
APPEND_OPT(m_dump_linux_cmdline);
APPEND_OPT(m_dump_linux_environ);
APPEND_OPT(m_dump_linux_auxv);
APPEND_OPT(m_dump_linux_maps);
APPEND_OPT(m_dump_linux_proc_stat);
APPEND_OPT(m_dump_linux_proc_uptime);
APPEND_OPT(m_dump_linux_proc_fd);
APPEND_OPT(m_dump_linux_all);
APPEND_OPT(m_fb_app_data);
APPEND_OPT(m_fb_build_id);
APPEND_OPT(m_fb_version);
APPEND_OPT(m_fb_java_stack);
APPEND_OPT(m_fb_dalvik);
APPEND_OPT(m_fb_unwind);
APPEND_OPT(m_fb_error_log);
APPEND_OPT(m_fb_app_state);
APPEND_OPT(m_fb_abort);
APPEND_OPT(m_fb_thread);
APPEND_OPT(m_fb_logcat);
APPEND_OPT(m_fb_all);
m_option_group.Finalize();
}
~CommandObjectProcessMinidumpDump() override {}
Options *GetOptions() override { return &m_option_group; }
bool DoExecute(Args &command, CommandReturnObject &result) override {
const size_t argc = command.GetArgumentCount();
if (argc > 0) {
result.AppendErrorWithFormat("'%s' take no arguments, only options",
m_cmd_name.c_str());
result.SetStatus(eReturnStatusFailed);
return false;
}
SetDefaultOptionsIfNoneAreSet();
ProcessMinidump *process = static_cast<ProcessMinidump *>(
m_interpreter.GetExecutionContext().GetProcessPtr());
result.SetStatus(eReturnStatusSuccessFinishResult);
Stream &s = result.GetOutputStream();
MinidumpParser &minidump = *process->m_minidump_parser;
if (DumpDirectory()) {
s.Printf("RVA SIZE TYPE StreamType\n");
s.Printf("---------- ---------- ---------- --------------------------\n");
for (const auto &stream_desc : minidump.GetMinidumpFile().streams())
s.Printf(
"0x%8.8x 0x%8.8x 0x%8.8x %s\n", (uint32_t)stream_desc.Location.RVA,
(uint32_t)stream_desc.Location.DataSize,
(unsigned)(StreamType)stream_desc.Type,
MinidumpParser::GetStreamTypeAsString(stream_desc.Type).data());
s.Printf("\n");
}
auto DumpTextStream = [&](StreamType stream_type,
llvm::StringRef label) -> void {
auto bytes = minidump.GetStream(stream_type);
if (!bytes.empty()) {
if (label.empty())
label = MinidumpParser::GetStreamTypeAsString(stream_type);
s.Printf("%s:\n%s\n\n", label.data(), bytes.data());
}
};
auto DumpBinaryStream = [&](StreamType stream_type,
llvm::StringRef label) -> void {
auto bytes = minidump.GetStream(stream_type);
if (!bytes.empty()) {
if (label.empty())
label = MinidumpParser::GetStreamTypeAsString(stream_type);
s.Printf("%s:\n", label.data());
DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
process->GetAddressByteSize());
DumpDataExtractor(data, &s, 0, lldb::eFormatBytesWithASCII, 1,
bytes.size(), 16, 0, 0, 0);
s.Printf("\n\n");
}
};
if (DumpLinuxCPUInfo())
DumpTextStream(StreamType::LinuxCPUInfo, "/proc/cpuinfo");
if (DumpLinuxProcStatus())
DumpTextStream(StreamType::LinuxProcStatus, "/proc/PID/status");
if (DumpLinuxLSBRelease())
DumpTextStream(StreamType::LinuxLSBRelease, "/etc/lsb-release");
if (DumpLinuxCMDLine())
DumpTextStream(StreamType::LinuxCMDLine, "/proc/PID/cmdline");
if (DumpLinuxEnviron())
DumpTextStream(StreamType::LinuxEnviron, "/proc/PID/environ");
if (DumpLinuxAuxv())
DumpBinaryStream(StreamType::LinuxAuxv, "/proc/PID/auxv");
if (DumpLinuxMaps())
DumpTextStream(StreamType::LinuxMaps, "/proc/PID/maps");
if (DumpLinuxProcStat())
DumpTextStream(StreamType::LinuxProcStat, "/proc/PID/stat");
if (DumpLinuxProcUptime())
DumpTextStream(StreamType::LinuxProcUptime, "uptime");
if (DumpLinuxProcFD())
DumpTextStream(StreamType::LinuxProcFD, "/proc/PID/fd");
if (DumpFacebookAppData())
DumpTextStream(StreamType::FacebookAppCustomData,
"Facebook App Data");
if (DumpFacebookBuildID()) {
auto bytes = minidump.GetStream(StreamType::FacebookBuildID);
if (bytes.size() >= 4) {
DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
process->GetAddressByteSize());
lldb::offset_t offset = 0;
uint32_t build_id = data.GetU32(&offset);
s.Printf("Facebook Build ID:\n");
s.Printf("%u\n", build_id);
s.Printf("\n");
}
}
if (DumpFacebookVersionName())
DumpTextStream(StreamType::FacebookAppVersionName,
"Facebook Version String");
if (DumpFacebookJavaStack())
DumpTextStream(StreamType::FacebookJavaStack,
"Facebook Java Stack");
if (DumpFacebookDalvikInfo())
DumpTextStream(StreamType::FacebookDalvikInfo,
"Facebook Dalvik Info");
if (DumpFacebookUnwindSymbols())
DumpBinaryStream(StreamType::FacebookUnwindSymbols,
"Facebook Unwind Symbols Bytes");
if (DumpFacebookErrorLog())
DumpTextStream(StreamType::FacebookDumpErrorLog,
"Facebook Error Log");
if (DumpFacebookAppStateLog())
DumpTextStream(StreamType::FacebookAppStateLog,
"Faceook Application State Log");
if (DumpFacebookAbortReason())
DumpTextStream(StreamType::FacebookAbortReason,
"Facebook Abort Reason");
if (DumpFacebookThreadName())
DumpTextStream(StreamType::FacebookThreadName,
"Facebook Thread Name");
if (DumpFacebookLogcat())
DumpTextStream(StreamType::FacebookLogcat,
"Facebook Logcat");
return true;
}
};
class CommandObjectMultiwordProcessMinidump : public CommandObjectMultiword {
public:
CommandObjectMultiwordProcessMinidump(CommandInterpreter &interpreter)
: CommandObjectMultiword(interpreter, "process plugin",
"Commands for operating on a ProcessMinidump process.",
"process plugin <subcommand> [<subcommand-options>]") {
LoadSubCommand("dump",
CommandObjectSP(new CommandObjectProcessMinidumpDump(interpreter)));
}
~CommandObjectMultiwordProcessMinidump() override {}
};
CommandObject *ProcessMinidump::GetPluginCommandObject() {
if (!m_command_sp)
m_command_sp = std::make_shared<CommandObjectMultiwordProcessMinidump>(
GetTarget().GetDebugger().GetCommandInterpreter());
return m_command_sp.get();
}
| 39.274566 | 84 | 0.681728 | [
"object",
"vector"
] |
104206d5c3f978b622095a5a3b88f965df77742f | 2,173 | cc | C++ | k-closest-points-to-origin.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | k-closest-points-to-origin.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | k-closest-points-to-origin.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
#include <queue>
#include <random>
class Solution
{
private:
std::mt19937 dev{ std::random_device{}() };
public:
std::vector<std::vector<int>> kClosest(std::vector<std::vector<int>> &points, int k)
{
return kClosestLinearSelect(points, k);
}
std::vector<std::vector<int>> kClosestSort(std::vector<std::vector<int>> &points, int k) // O(NlogN), O(logN)
{
std::sort(points.begin(), points.end(),
[](const auto &a, const auto &b) {
return a[0] * a[0] - b[1] * b[1] < b[0] * b[0] - a[1] * a[1];
});
std::vector<std::vector<int>> res(k, std::vector<int>{2, 0});
for (int i = 0; i < k; i++)
{
res[i][0] = points[i][0];
res[i][1] = points[i][1];
}
return res;
}
int getDist(const std::vector<int> &point)
{
return point[0] * point[0] + point[1] * point[1];
}
void kClosestLinearSelectImpl(std::vector<std::vector<int>> &points, int k, int left, int right)
{
if (k == 0)
return;
int pivot_ind = std::uniform_int_distribution<int>{left, right - 1}(dev);
std::swap(points[left], points[pivot_ind]);
int pivot_dist = getDist(points[left]);
int i = left, j = left + 1;
for (; j < right; j++)
if (getDist(points[j]) < pivot_dist)
std::swap(points[j], points[++i]);
std::swap(points[left], points[i]);
int elem_count = i - left + 1;
if (elem_count <= k)
kClosestLinearSelectImpl(points, k - elem_count, i + 1, right);
else
kClosestLinearSelectImpl(points, k, left, i);
}
std::vector<std::vector<int>> kClosestLinearSelect(std::vector<std::vector<int>> &points, int k) // O(N), O(logN)
{
kClosestLinearSelectImpl(points, k, 0, points.size());
std::vector<std::vector<int>> res(k, std::vector<int>(2, 0));
for (int i = 0; i < k; i++)
{
res[i][0] = points[i][0];
res[i][1] = points[i][1];
}
return res;
}
}; | 28.973333 | 117 | 0.513116 | [
"vector"
] |
104322f08fcf436fd4bb94d0be9fc5b872b06360 | 5,530 | cpp | C++ | tools/skpinfo.cpp | InvictrixRom/external_skia | 5d1778b530aa0b845b8d6996815665f7cc44bf38 | [
"BSD-3-Clause"
] | 4 | 2019-10-18T05:53:30.000Z | 2021-08-21T07:36:37.000Z | tools/skpinfo.cpp | InvictrixRom/external_skia | 5d1778b530aa0b845b8d6996815665f7cc44bf38 | [
"BSD-3-Clause"
] | 4 | 2016-04-08T23:04:42.000Z | 2017-06-16T21:46:02.000Z | tools/skpinfo.cpp | InvictrixRom/external_skia | 5d1778b530aa0b845b8d6996815665f7cc44bf38 | [
"BSD-3-Clause"
] | 7 | 2017-09-30T23:06:11.000Z | 2019-05-30T08:54:33.000Z | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCommandLineFlags.h"
#include "SkPicture.h"
#include "SkPictureData.h"
#include "SkStream.h"
#include "SkFontDescriptor.h"
DEFINE_string2(input, i, "", "skp on which to report");
DEFINE_bool2(version, v, true, "version");
DEFINE_bool2(cullRect, c, true, "cullRect");
DEFINE_bool2(flags, f, true, "flags");
DEFINE_bool2(tags, t, true, "tags");
DEFINE_bool2(quiet, q, false, "quiet");
// This tool can print simple information about an SKP but its main use
// is just to check if an SKP has been truncated during the recording
// process.
// return codes:
static const int kSuccess = 0;
static const int kTruncatedFile = 1;
static const int kNotAnSKP = 2;
static const int kInvalidTag = 3;
static const int kMissingInput = 4;
static const int kIOError = 5;
int main(int argc, char** argv) {
SkCommandLineFlags::SetUsage("Prints information about an skp file");
SkCommandLineFlags::Parse(argc, argv);
if (FLAGS_input.count() != 1) {
if (!FLAGS_quiet) {
SkDebugf("Missing input file\n");
}
return kMissingInput;
}
SkFILEStream stream(FLAGS_input[0]);
if (!stream.isValid()) {
if (!FLAGS_quiet) {
SkDebugf("Couldn't open file\n");
}
return kIOError;
}
size_t totStreamSize = stream.getLength();
SkPictInfo info;
if (!SkPicture::InternalOnly_StreamIsSKP(&stream, &info)) {
return kNotAnSKP;
}
if (FLAGS_version && !FLAGS_quiet) {
SkDebugf("Version: %d\n", info.getVersion());
}
if (FLAGS_cullRect && !FLAGS_quiet) {
SkDebugf("Cull Rect: %f,%f,%f,%f\n",
info.fCullRect.fLeft, info.fCullRect.fTop,
info.fCullRect.fRight, info.fCullRect.fBottom);
}
if (FLAGS_flags && !FLAGS_quiet) {
SkDebugf("Flags: ");
bool needsSeparator = false;
if (info.fFlags & SkPictInfo::kCrossProcess_Flag) {
SkDebugf("kCrossProcess");
needsSeparator = true;
}
if (info.fFlags & SkPictInfo::kScalarIsFloat_Flag) {
if (needsSeparator) {
SkDebugf("|");
}
SkDebugf("kScalarIsFloat");
needsSeparator = true;
}
if (info.fFlags & SkPictInfo::kPtrIs64Bit_Flag) {
if (needsSeparator) {
SkDebugf("|");
}
SkDebugf("kPtrIs64Bit");
}
SkDebugf("\n");
}
if (!stream.readBool()) {
// If we read true there's a picture playback object flattened
// in the file; if false, there isn't a playback, so we're done
// reading the file.
return kSuccess;
}
for (;;) {
uint32_t tag = stream.readU32();
if (SK_PICT_EOF_TAG == tag) {
break;
}
uint32_t chunkSize = stream.readU32();
size_t curPos = stream.getPosition();
// "move" doesn't error out when seeking beyond the end of file
// so we need a preemptive check here.
if (curPos+chunkSize > totStreamSize) {
if (!FLAGS_quiet) {
SkDebugf("truncated file\n");
}
return kTruncatedFile;
}
// Not all the tags store the chunk size (in bytes). Three
// of them store tag-specific size information (e.g., number of
// fonts) instead. This forces us to early exit when those
// chunks are encountered.
switch (tag) {
case SK_PICT_READER_TAG:
if (FLAGS_tags && !FLAGS_quiet) {
SkDebugf("SK_PICT_READER_TAG %d\n", chunkSize);
}
break;
case SK_PICT_FACTORY_TAG:
if (FLAGS_tags && !FLAGS_quiet) {
SkDebugf("SK_PICT_FACTORY_TAG %d\n", chunkSize);
}
break;
case SK_PICT_TYPEFACE_TAG: {
if (FLAGS_tags && !FLAGS_quiet) {
SkDebugf("SK_PICT_TYPEFACE_TAG %d\n", chunkSize);
}
const int count = SkToInt(chunkSize);
for (int i = 0; i < count; i++) {
SkFontDescriptor desc;
if (!SkFontDescriptor::Deserialize(&stream, &desc)) {
if (!FLAGS_quiet) {
SkDebugf("File corruption in SkFontDescriptor\n");
}
return kInvalidTag;
}
}
// clear this since we've consumed all the typefaces
chunkSize = 0;
break;
}
case SK_PICT_PICTURE_TAG:
if (FLAGS_tags && !FLAGS_quiet) {
SkDebugf("SK_PICT_PICTURE_TAG %d\n", chunkSize);
SkDebugf("Exiting early due to format limitations\n");
}
return kSuccess; // TODO: need to store size in bytes
break;
case SK_PICT_BUFFER_SIZE_TAG:
if (FLAGS_tags && !FLAGS_quiet) {
SkDebugf("SK_PICT_BUFFER_SIZE_TAG %d\n", chunkSize);
}
break;
default:
if (!FLAGS_quiet) {
SkDebugf("Unknown tag %d\n", chunkSize);
}
return kInvalidTag;
}
if (!stream.move(chunkSize)) {
if (!FLAGS_quiet) {
SkDebugf("seek error\n");
}
return kTruncatedFile;
}
}
return kSuccess;
}
| 31.067416 | 74 | 0.551899 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.