text
string | size
int64 | token_count
int64 |
|---|---|---|
// Copyright (C) 2012-2019 The VPaint Developers.
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT
//
// 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 "ProperCycle.h"
#include "KeyEdge.h"
#include "../SaveAndLoad.h"
#include <QMessageBox>
namespace VectorAnimationComplex
{
ProperCycle::ProperCycle()
{
// invalid by default, nothing to do (since edges_ is empty)
}
ProperCycle::ProperCycle(const KeyEdgeSet & edgeSetConst)
{
// If no edge, then invalid
if(edgeSetConst.isEmpty())
return;
// if not all edges at same time, then invalid
KeyEdge * first = *edgeSetConst.begin();
Time t = first->time();
for(KeyEdge * iedge: edgeSetConst)
{
if(iedge->time() != t)
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not all edges are on same time"));
return;
}
}
// copy the set to be able to modify it
KeyEdgeSet edgeSet = edgeSetConst;
// insert first edge
halfedges_ << KeyHalfedge(first, true);
edgeSet.erase(edgeSet.begin());
// check case where it's a pure loop
if(first->isClosed())
{
if(!edgeSet.isEmpty())
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("more than one edge and one of them is a pure loop"));
halfedges_.clear();
return;
}
// else: good!
}
else
{
// not a pure loop, let's find the chain
while(!edgeSet.isEmpty())
{
KeyHalfedge lastAddedHalfedge = halfedges_.last(); // we know it's not a loop, otherwise couldn't be here
KeyVertex * lastVertex = lastAddedHalfedge.endVertex(); // hence this is a valid vertex
// find next
KeyHalfedge nextHalfedge;
auto it = edgeSet.begin();
auto itEnd = edgeSet.end();
for(;it!=itEnd;++it)
{
if((*it)->startVertex() == lastVertex)
{
nextHalfedge = KeyHalfedge(*it, true);
break;
}
else if((*it)->endVertex() == lastVertex)
{
nextHalfedge = KeyHalfedge(*it, false);
break;
}
}
// if found: great, insert it!
if(nextHalfedge.isValid())
{
halfedges_ << nextHalfedge;
edgeSet.erase(it);
}
else
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: no valid next edge found"));
halfedges_.clear();
return;
}
}
// So far, we've inserted all N edges, and every edge i in [0,N-2]
// satisfies edges_[i]->endVertex() == edges_[i+1]->startVertex()
// Check that it's looping
if(halfedges_.last().endVertex() != halfedges_.first().startVertex())
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: last edge not compatible with first one"));
halfedges_.clear();
return;
}
// Check that it's simple
KeyVertexSet vertices;
for(KeyHalfedge he: qAsConst(halfedges_))
{
KeyVertex * vertex = he.startVertex();
if(vertices.contains(vertex))
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: not simple"));
halfedges_.clear();
return;
}
else
{
vertices << vertex;
}
}
// Done :-) If you're here you have a valid simple loop
}
}
bool ProperCycle::isValid() const
{
return !halfedges_.isEmpty();
}
Time ProperCycle::time() const
{
return halfedges_[0].time();
}
int ProperCycle::size() const
{
return halfedges_.size();
}
KeyHalfedge ProperCycle::operator[](int i) const
{
return halfedges_[i];
}
void ProperCycle::remapPointers(VAC * newVAC)
{
for(int i=0; i<halfedges_.size(); ++i)
halfedges_[i].remapPointers(newVAC);
}
void ProperCycle::convertTempIdsToPointers(VAC * vac)
{
for(int i=0; i<halfedges_.size(); ++i)
halfedges_[i].convertTempIdsToPointers(vac);
}
// Replace pointed edges
void ProperCycle::replaceEdges(KeyEdge * oldEdge, const KeyEdgeList & newEdges)
{
QList<KeyHalfedge> newHalfedges;
for(KeyHalfedge he: qAsConst(halfedges_))
{
if(he.edge == oldEdge)
{
// Replace halfedge
if(he.side)
{
for(int i=0; i<newEdges.size(); ++i)
newHalfedges << KeyHalfedge(newEdges[i], he.side);
}
else
{
for(int i=newEdges.size()-1; i>=0; --i)
newHalfedges << KeyHalfedge(newEdges[i], he.side);
}
}
else
{
// Keep halfedge as is
newHalfedges << he;
}
}
halfedges_ = newHalfedges;
}
} // end namespace VectorAnimationComplex
QTextStream & operator<<(QTextStream & out, const VectorAnimationComplex::ProperCycle & loop)
{
out << loop.halfedges_;
return out;
}
QTextStream & operator>>(QTextStream & in, VectorAnimationComplex::ProperCycle & loop)
{
in >> loop.halfedges_;
return in;
}
| 6,327
| 1,890
|
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PlayerPawnTest_Male_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.UserConstructionScript
// ()
void APlayerPawnTest_Male_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.UserConstructionScript");
APlayerPawnTest_Male_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.ExecuteUbergraph_PlayerPawnTest_Male
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void APlayerPawnTest_Male_C::ExecuteUbergraph_PlayerPawnTest_Male(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.ExecuteUbergraph_PlayerPawnTest_Male");
APlayerPawnTest_Male_C_ExecuteUbergraph_PlayerPawnTest_Male_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 1,473
| 495
|
#include <cmath>
#include <string.h>
#include "tensor.h"
#include "layers.h"
#include "net.h"
#include "optimizer.h"
#include "error.h"
namespace lten {
void SGDOptimizer::setup_optimizer()
{
int i;
uint64_t numels;
for (i = 0; i < num_params_; i++)
{
numels = network_params_ptr_[i].param_->get_numels();
network_params_ptr_[i].param_data_ = new Tensor;
*network_params_ptr_[i].param_data_ = AllocateTensor(network_params_ptr_[i].param_->get_sizes(), network_params_ptr_[i].param_->get_ndims(),0); // allocate buffer for momentum/velocity
memset(network_params_ptr_[i].param_data_->get_data_ptr(), 0, sizeof(float) * numels);
}
}
void SGDOptimizer::step()
{
float* weight_ptr;
float* weight_grad_ptr;
float* velocity_ptr;
int i;
uint64_t j;
uint64_t numels;
device device_type;
if (!num_params_)
{
LTEN_ERR("No parameters have been added to the optimizer");
}
device_type = network_params_ptr_[0].param_->get_device(); // key off first param
if (device_type == CPU)
{
for (i = 0; i < num_params_; i++)
{
weight_ptr = (float*)network_params_ptr_[i].param_->get_data_ptr();
weight_grad_ptr = (float*)network_params_ptr_[i].param_->get_grad_ptr();
numels = network_params_ptr_[i].param_->get_numels();
velocity_ptr = (float*)network_params_ptr_[i].param_data_->get_data_ptr();
for (j = 0; j < numels; j++)
{
weight_grad_ptr[j] = wd_ * weight_ptr[j] + weight_grad_ptr[j];
velocity_ptr[j] = velocity_ptr[j] * mo_ + (1.0f - mo_) * weight_grad_ptr[j];
weight_ptr[j] = weight_ptr[j] - (velocity_ptr[j] * lr_);
}
}
}
else
{
if (device_type == GPU)
{
#ifdef USE_CUDA
for (i = 0; i < num_params_; i++)
{
weight_ptr = (float*)network_params_ptr_[i].param_->get_data_ptr();
weight_grad_ptr = (float*)network_params_ptr_[i].param_->get_grad_ptr();
numels = network_params_ptr_[i].param_->get_numels();
velocity_ptr = (float*)network_params_ptr_[i].param_data_->get_data_ptr();
gpu_sgd_step(weight_ptr, weight_grad_ptr, velocity_ptr, numels, mo_, wd_, lr_);
}
#else
LTEN_ERR("The USE_CUDA flag was not be set during the build (this flag must be set in order to use GPU tensors)");
#endif
}
else
{
LTEN_ERR("Invalid tensor device type");
}
}
}
void AdamOptimizer::setup_optimizer()
{
int i;
uint64_t dims[MAX_DIMS];
uint64_t numels;
for (i = 0; i < num_params_; i++)
{
numels = network_params_ptr_[i].param_->get_numels();
network_params_ptr_[i].param_data_ = new Tensor;
memcpy(dims, network_params_ptr_[i].param_->get_sizes(), sizeof(uint64_t) * network_params_ptr_[i].param_->get_ndims());
dims[0] *= 3; // make room for momentum, rmsprop histories and scratch space
*network_params_ptr_[i].param_data_ = AllocateTensor(dims, network_params_ptr_[i].param_->get_ndims(), 0); // allocate history buffer
memset(network_params_ptr_[i].param_data_->get_data_ptr(), 0, sizeof(float) * numels * 3);
}
}
void AdamOptimizer::step()
{
float* weight_ptr;
float* weight_grad_ptr;
float* v_dw;
float* s_dw;
float* scratch;
float epsilon;
uint64_t numels;
int i;
device device_type;
float bias_correction1;
float bias_correction2;
if (!num_params_)
{
LTEN_ERR("No parameters have been added to the optimizer");
}
device_type = network_params_ptr_[0].param_->get_device(); // key off first param
iteration_++;
epsilon = 1.0e-8f;
for (i = 0; i < num_params_; i++)
{
weight_grad_ptr = static_cast<float*>(network_params_ptr_[i].param_->get_grad_ptr());
if (!weight_grad_ptr)
{
continue;
}
weight_ptr = static_cast<float*>(network_params_ptr_[i].param_->get_data_ptr());
numels = network_params_ptr_[i].param_->get_numels();
v_dw = static_cast<float*>(network_params_ptr_[i].param_data_->get_data_ptr());
s_dw = v_dw + (numels);
scratch = v_dw + (2 * numels);
bias_correction1 = 1.0f - powf(beta1_, static_cast<float>(iteration_));
bias_correction2 = 1.0f - powf(beta2_, static_cast<float>(iteration_));
if (device_type == CPU)
{
cpu_axpby(numels, 1.0f - beta1_, weight_grad_ptr, beta1_, v_dw, v_dw);
cpu_mul(numels, weight_grad_ptr, weight_grad_ptr, scratch);
cpu_axpby(numels, 1.0f - beta2_, scratch, beta2_, s_dw, s_dw);
cpu_mul(numels, 1.0f / bias_correction2, s_dw, scratch);
cpu_powx(numels, scratch, 0.5f, scratch);
cpu_add(numels, epsilon, scratch, scratch);
cpu_div(numels, v_dw, scratch, scratch);
cpu_axpy(numels, -(1.0f / bias_correction1) * lr_, scratch, weight_ptr, weight_ptr);
}
else
{
if (device_type == GPU)
{
#ifdef USE_CUDA
gpu_axpby(numels, 1.0f - beta1_, weight_grad_ptr, beta1_, v_dw, v_dw);
gpu_mul(numels, weight_grad_ptr, weight_grad_ptr, scratch);
gpu_axpby(numels, 1.0f - beta2_, scratch, beta2_, s_dw, s_dw);
gpu_mul(numels, 1.0f / bias_correction2, s_dw, scratch);
gpu_powx(numels, scratch, 0.5f, scratch);
gpu_add(numels, epsilon, scratch, scratch);
gpu_div(numels, v_dw, scratch, scratch);
gpu_axpy(numels, -(1.0f / bias_correction1) * lr_, scratch, weight_ptr, weight_ptr);
#else
LTEN_ERR("The USE_CUDA flag was not be set during the build (this flag must be set in order to use GPU tensors)");
#endif
}
else
{
LTEN_ERR("Invalid tensor device type");
}
}
}
}
} // namespace btpn
| 5,441
| 2,514
|
// Copyright 2020 The IREE Authors
//
// Licensed 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 "iree/compiler/Codegen/LLVMCPU/KernelDispatch.h"
#include <numeric>
#include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtOps.h"
#include "iree/compiler/Codegen/Transforms/Transforms.h"
#include "iree/compiler/Codegen/Utils/MarkerUtils.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/Flow/IR/FlowOps.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetSelect.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Linalg/IR/LinalgInterfaces.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/MemRef/Transforms/Passes.h"
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
namespace mlir {
namespace iree_compiler {
/// NOTE: None of these flags are supported in any form long term. This are
/// temporary hooks added for development purposes. They could be
/// changed/modified at any time.
/// TODO: Find a way to plumb this through to not rely on these flags.
static llvm::cl::opt<int> clNativeVectorSizeInBytes(
"iree-codegen-llvm-vector-size-in-bytes",
llvm::cl::desc("native vector size to use on the hardware"),
llvm::cl::init(16));
static llvm::cl::opt<int> clNumberOfRuntimeThreads(
"iree-codegen-llvm-number-of-threads",
llvm::cl::desc("number of threads that are used at runtime"),
llvm::cl::init(8));
static llvm::cl::list<int> mmt4dWorkgroupTileSizes(
"iree-codegen-llvm-mmt4d-workgroup-tile-sizes",
llvm::cl::desc("linalg.mmt4d workgroup tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::list<int> mmt4dL1TileSizes(
"iree-codegen-llvm-mmt4d-l1-tile-size",
llvm::cl::desc("linalg.mmt4d L1 tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::list<int> mmt4dVectorSizes(
"iree-codegen-llvm-mmt4d-vector-size",
llvm::cl::desc("linalg.mmt4d vector tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::opt<int> defaultWorkgroupTileSize(
"iree-codegen-llvm-generic-ops-workgroup-size",
llvm::cl::desc(
"linalg.generic and linalg.indexed_generic workgroup tile size"),
llvm::cl::init(64));
static llvm::cl::opt<bool> useLinalgTransformInterp(
"iree-codegen-use-linalg-transform-interp",
llvm::cl::desc(
"experimental path to use the linalg transform dialect interpreter"),
llvm::cl::init(false));
using IREE::Codegen::DispatchLoweringPassPipeline;
/// Looks for the `native_vector_size` attribute in the hal.executable.variant
/// op.
static Optional<int64_t> getNativeVectorSizeInBytes(func::FuncOp entryPointFn) {
auto variantOp =
entryPointFn->getParentOfType<IREE::HAL::ExecutableVariantOp>();
if (!variantOp) return llvm::None;
IREE::HAL::ExecutableTargetAttr targetAttr = variantOp.target();
if (!targetAttr) return llvm::None;
auto config = targetAttr.getConfiguration();
if (!config) return llvm::None;
auto nativeVectorSizeAttr = config.getAs<IntegerAttr>("native_vector_size");
if (!nativeVectorSizeAttr) return llvm::None;
int64_t nativeVectorSizeVal = nativeVectorSizeAttr.getInt();
if (!nativeVectorSizeVal) return llvm::None;
return nativeVectorSizeVal;
}
/// For a given `shapedType` or (`byteWidth` of element type) return the number
/// of elements that correspond to the native vector size. Returns 1 as the
/// fallback.
static int64_t getVectorSize(func::FuncOp entryPointFn, unsigned byteWidth) {
if (Optional<int64_t> nativeVectorSize =
getNativeVectorSizeInBytes(entryPointFn)) {
return nativeVectorSize.getValue() / byteWidth;
}
return clNativeVectorSizeInBytes / byteWidth;
}
static int64_t getVectorSize(func::FuncOp entryPointFn, ShapedType shapedType) {
Type elementType = shapedType.getElementType();
if (!elementType.isIntOrFloat()) return 1;
unsigned byteWidth = IREE::Util::getRoundedElementByteWidth(elementType);
return getVectorSize(entryPointFn, byteWidth);
}
/// Returns minimum tiling sizes for each dimension. One dimension is possible
/// to access at different element types. It determines the tiling sizes by
/// looking into all the operands.
static SmallVector<int64_t> getMinTilingSizesForEachDim(
func::FuncOp entryPointFn, linalg::LinalgOp op) {
unsigned numLoops = op.getNumLoops();
SmallVector<int64_t> minTileSizes(numLoops, 1);
auto inputOutputOpOperands = op.getInputAndOutputOperands();
for (auto map : llvm::enumerate(op.getIndexingMaps())) {
// Check the fastest varying dimension of the operand. Set the vector size
// of the corresponding loop to the vector size.
if (map.value().getNumResults() == 0) continue;
auto fastestVaryingDimExpr =
map.value().getResults().back().dyn_cast<AffineDimExpr>();
if (!fastestVaryingDimExpr) continue;
unsigned fastestVaryingDim = fastestVaryingDimExpr.getPosition();
// If the indexing map has result it has to be a shaped type.
auto operandType =
inputOutputOpOperands[map.index()]->get().getType().cast<ShapedType>();
minTileSizes[fastestVaryingDim] =
std::max<int64_t>(minTileSizes[fastestVaryingDim],
getVectorSize(entryPointFn, operandType));
}
return minTileSizes;
}
/// Returns the type length in bytes. Looks through all the interface binding
/// ops to see the ABI types and guess-timates the type size to use. This is
/// used to convert the vector size in bytes to vector size in number of
/// elements.
static unsigned getReferenceTypeLengthInBytes(func::FuncOp entryPointFn) {
unsigned referenceTypeLengthInBytes = 4;
entryPointFn.walk([&](IREE::HAL::InterfaceBindingSubspanOp subSpanOp) {
Type type = subSpanOp.getResult().getType();
Type elementType = TypeSwitch<Type, Type>(type)
.Case<ShapedType, IREE::Flow::DispatchTensorType>(
[&](auto shapedType) -> Type {
// Ignore operands that are 0D tensors. These
// are not vector-loadable, so using these to
// get vector length would be a pessimization.
if (!shapedType.getRank()) return nullptr;
return shapedType.getElementType();
})
.Default([&](Type t) -> Type { return nullptr; });
if (!elementType || !elementType.isIntOrFloat()) return;
unsigned typeWidthInBytes =
IREE::Util::getRoundedElementByteWidth(elementType);
referenceTypeLengthInBytes =
std::min<unsigned>(referenceTypeLengthInBytes, typeWidthInBytes);
});
return referenceTypeLengthInBytes;
}
/// Returns the default tile sizes to use for the loops that are distributed at
/// Flow level.
static SmallVector<int64_t> getDefaultDistributedLoopTileSizes(
ArrayRef<int64_t> lbs, ArrayRef<int64_t> ubs,
ArrayRef<int64_t> minTileSizes, ArrayRef<int64_t> maxTileSizes,
ArrayRef<int64_t> vectorSizeHints) {
assert(lbs.size() == ubs.size() && lbs.size() == minTileSizes.size() &&
lbs.size() == maxTileSizes.size() &&
"expected all vectors to be of equal size");
size_t numDims = lbs.size();
SmallVector<int64_t> distributedTileSizes(numDims, 1);
SmallVector<int64_t> numWorkgroupsPerDim(numDims, 1);
SmallVector<int64_t> workload(numDims, 1);
for (auto i : llvm::seq<size_t>(0, numDims)) {
if (maxTileSizes[i] == 0 || ShapedType::isDynamic(lbs[i]) ||
ShapedType::isDynamic(ubs[i])) {
distributedTileSizes[i] = maxTileSizes[i];
workload[i] = ShapedType::kDynamicSize;
continue;
}
assert(lbs[i] <= ubs[i]);
workload[i] = ubs[i] - lbs[i];
int64_t candidateTileSize = 1;
int64_t targetSize = std::min(workload[i] / 2, maxTileSizes[i]);
int64_t vectorSize = vectorSizeHints[i];
if (vectorSize > 1) {
// Pick the factor of dim which is closest to the target tile size and
// is a multiplier of vector size.
for (int64_t k = vectorSize; k <= targetSize; k += vectorSize) {
if (workload[i] % k == 0 && k >= minTileSizes[i]) {
candidateTileSize = k;
}
}
}
// Fallback to power of 2 if there's no hint or can't find the ideal size.
if (vectorSize <= 1 || candidateTileSize == 1) {
candidateTileSize =
std::max<int64_t>(llvm::PowerOf2Floor(targetSize), minTileSizes[i]);
}
// Limit the workload per workgroup to the default being the max to keep the
// work per invocation reasonable.
distributedTileSizes[i] =
std::min<int64_t>(candidateTileSize, maxTileSizes[i]);
numWorkgroupsPerDim[i] =
llvm::divideCeil(workload[i], distributedTileSizes[i]);
}
// Reduce the number of workgroups in cases where we are dividing the work too
// much. Over-provision the number of workgroups to twice the number of
// threads.
int64_t numWorkgroupsLimit = 2 * clNumberOfRuntimeThreads;
int64_t numWorkgroups =
std::accumulate(numWorkgroupsPerDim.begin(), numWorkgroupsPerDim.end(),
1LL, std::multiplies<int64_t>{});
unsigned currDim = numDims;
while (numWorkgroups > numWorkgroupsLimit && currDim > 0) {
unsigned index = currDim - 1;
int64_t currSize = distributedTileSizes[index];
if (currSize >= maxTileSizes[index] ||
workload[index] == ShapedType::kDynamicSize ||
currSize >= workload[index]) {
currDim--;
continue;
}
int64_t newSize = std::min<int64_t>(currSize * 2, maxTileSizes[index]);
int64_t vectorSize = vectorSizeHints[index];
// Chech if it's the ideal size with vector size hint. And skip if the new
// size will break the ideal size.
if (vectorSize > 1 &&
(currSize % vectorSize == 0 && workload[index] % currSize == 0) &&
(newSize % vectorSize != 0 || workload[index] % newSize != 0)) {
currDim--;
continue;
}
distributedTileSizes[index] = newSize;
int64_t nwg =
llvm::divideCeil(workload[index], distributedTileSizes[index]);
if (nwg < numWorkgroupsPerDim[index]) {
numWorkgroups /= numWorkgroupsPerDim[index];
numWorkgroups *= nwg;
} else {
currDim--;
}
}
return distributedTileSizes;
}
/// Adjusts the workload per workgroup to be a multiple of vector size to ensure
/// that the op vectorizes.
static int64_t getMaxTileSize(int64_t lb, int64_t ub, int64_t maxSize,
int64_t vectorSizeVal) {
if (ub == ShapedType::kDynamicSize || lb == ShapedType::kDynamicSize) {
return maxSize;
}
int64_t dim = ub - lb;
if (dim < vectorSizeVal) return dim;
for (int64_t i = std::min(maxSize, dim); i > 0; --i) {
if (dim % i == 0 && i % vectorSizeVal == 0) {
return i;
}
}
// If it can't be a multiple of vectorSizeVal, let's choose a factor of dim
// sizes heuristically.
int64_t start = std::min(maxSize, dim);
start = std::min(start, vectorSizeVal * 2);
for (int64_t i = start; i > 0; --i) {
if (dim % i == 0) {
return i;
}
}
return 1;
}
/// Returns the tile size to use for the Flow level.
///
/// The vectorSizeHints can be empty or as many as the number of loops. When not
/// empty, each hint should be 1 or the vector size. On the dimensions where the
/// hints != 1, it will try to find the tile sizes which are multipliers of the
/// hints.
static SmallVector<int64_t> getDefaultDistributedLevelTileSizes(
ArrayRef<unsigned> partitionableLoops, ArrayRef<int64_t> lbs,
ArrayRef<int64_t> ubs, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes, ArrayRef<int64_t> vectorSizeHints = {}) {
int64_t numLoops = lbs.size();
assert(numLoops == minTileSizes.size() && maxTileSizes.size() == numLoops &&
"expected as many min/max tile sizes as number of loops");
assert(
vectorSizeHints.empty() ||
vectorSizeHints.size() == numLoops &&
"vector size hints should be empty or equal to the number of loops");
// Only set values when the loop is partitionable.
SmallVector<int64_t> adjustedMinTileSizes(numLoops, 0);
SmallVector<int64_t> adjustedMaxTileSizes(numLoops, 0);
SmallVector<int64_t> adjustedVectorSizeHints(numLoops, 1);
for (auto i : partitionableLoops) {
adjustedMinTileSizes[i] = minTileSizes[i];
adjustedMaxTileSizes[i] = maxTileSizes[i];
if (!vectorSizeHints.empty()) {
adjustedVectorSizeHints[i] = vectorSizeHints[i];
}
}
SmallVector<int64_t> distributedTileSizes =
getDefaultDistributedLoopTileSizes(lbs, ubs, adjustedMinTileSizes,
adjustedMaxTileSizes,
adjustedVectorSizeHints);
// Final fix up of the tile sizes to make sure that they divide the problem
// size to make it vectorizable.
for (auto i : llvm::seq<unsigned>(0, distributedTileSizes.size())) {
if (!distributedTileSizes[i]) continue;
distributedTileSizes[i] = getMaxTileSize(
lbs[i], ubs[i], distributedTileSizes[i], minTileSizes[i]);
}
return distributedTileSizes;
}
static SmallVector<int64_t> getDefaultDistributedLevelTileSizes(
linalg::LinalgOp linalgOp, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes, ArrayRef<int64_t> vectorSizeHints = {}) {
OpBuilder builder(linalgOp.getContext());
builder.setInsertionPoint(linalgOp);
SmallVector<int64_t> lbs(linalgOp.getNumLoops(), 0);
SmallVector<int64_t> ubs = linalgOp.getStaticLoopRanges();
auto loops =
cast<IREE::Flow::PartitionableLoopsInterface>(linalgOp.getOperation())
.getPartitionableLoops(kNumMaxParallelDims);
return getDefaultDistributedLevelTileSizes(loops, lbs, ubs, minTileSizes,
maxTileSizes, vectorSizeHints);
}
/// Splits the tile sizes in `parallelSizes` into `reductionSizes` for the
/// reduction loops.
static void splitParallelAndReductionTiles(
linalg::LinalgOp op, SmallVectorImpl<int64_t> ¶llelSizes,
SmallVectorImpl<int64_t> &reductionSizes) {
reductionSizes.assign(parallelSizes.begin(), parallelSizes.end());
for (auto iteratorType : llvm::enumerate(op.iterator_types())) {
if (iteratorType.value().cast<StringAttr>().getValue() ==
getParallelIteratorTypeName()) {
reductionSizes[iteratorType.index()] = 0;
} else {
parallelSizes[iteratorType.index()] = 0;
}
}
}
static void setAlwaysVectorizeSizes(linalg::LinalgOp op,
SmallVectorImpl<int64_t> ¶llelSizes,
SmallVectorImpl<int64_t> &reductionSizes) {
SmallVector<int64_t, 4> staticLoopRanges = op.getStaticLoopRanges();
for (auto en :
llvm::enumerate(llvm::zip(staticLoopRanges, op.iterator_types()))) {
auto size = std::get<0>(en.value());
if (!ShapedType::isDynamic(size)) continue;
auto iterType = std::get<1>(en.value()).cast<StringAttr>().getValue();
if (iterType == getParallelIteratorTypeName()) {
parallelSizes[en.index()] = 1;
} else {
reductionSizes[en.index()] = 1;
}
}
}
/// Sets the default configuration to use for an operation that implements the
/// `PartitionableLoopsInterface`, given the `lbs` and `ubs` of all the loops.
static LogicalResult setDefaultRootConfig(
func::FuncOp entryPointFn,
IREE::Flow::PartitionableLoopsInterface partitionableLoopsInterfaceOp,
ArrayRef<int64_t> lbs, ArrayRef<int64_t> ubs, bool hasTensorSemantics) {
if (getLoweringConfig(partitionableLoopsInterfaceOp)) return success();
SmallVector<unsigned> partitionableLoops =
partitionableLoopsInterfaceOp.getPartitionableLoops(kNumMaxParallelDims);
SmallVector<int64_t> minTileSizes(lbs.size(), 1);
SmallVector<int64_t> maxTileSizes(lbs.size(), 1);
if (!partitionableLoops.empty()) {
// TODO: Here the min tile size is just looking at the type of the data in
// the entry point function, and using a vector size that depends on just
// that. For `LinalgOp`s we can use the indexing map, find the loops that
// are fastest varying and set those to have a min tile size of vector
// length. A version of this is done for generic ops. Generalize that and
// use it for `LinalgOp`s.
unsigned typeWidthInBytes = getReferenceTypeLengthInBytes(entryPointFn);
minTileSizes[partitionableLoops.back()] =
getVectorSize(entryPointFn, typeWidthInBytes);
for (auto partitionableLoopId : partitionableLoops) {
maxTileSizes[partitionableLoopId] = defaultWorkgroupTileSize;
}
}
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
partitionableLoops, lbs, ubs, minTileSizes, maxTileSizes);
TileSizesListType tileSizes;
tileSizes.emplace_back(std::move(flowTileSizes));
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, partitionableLoopsInterfaceOp, tileSizes,
hasTensorSemantics ? DispatchLoweringPassPipeline::CPUDefault
: DispatchLoweringPassPipeline::CPUBufferOpsDefault);
}
static LogicalResult setSandboxRootConfig(func::FuncOp entryPointFn,
linalg::ContractionOpInterface op,
ArrayRef<int64_t> flowTileSizes,
ArrayRef<int64_t> target2ndTileSizes,
int vectorSize) {
assert(target2ndTileSizes.size() == 3 &&
"the current configuration is driven by matmul which has exactly "
"three loops");
// The tiling for parallel dims and reduction dims should be separated.
SmallVector<int64_t> parallelTileSizes;
auto linalgOp = cast<linalg::LinalgOp>(op.getOperation());
int64_t nLoops = linalgOp.getNumLoops();
if (nLoops >= 3) {
parallelTileSizes.append(nLoops - 3, 1);
parallelTileSizes.push_back(getMaxTileSize(
0, flowTileSizes[nLoops - 3], target2ndTileSizes[0], vectorSize));
}
if (nLoops >= 2) {
parallelTileSizes.push_back(getMaxTileSize(
0, flowTileSizes[nLoops - 2], target2ndTileSizes[1], vectorSize));
}
parallelTileSizes.push_back(0);
auto lhsShapedType = op.lhs().getType().cast<ShapedType>();
int64_t K = lhsShapedType.getShape().back();
SmallVector<int64_t> reductionTileSizes;
reductionTileSizes.append(nLoops - 1, 0);
reductionTileSizes.push_back(
getMaxTileSize(0, K, target2ndTileSizes[2], vectorSize));
setAlwaysVectorizeSizes(linalgOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.emplace_back(flowTileSizes.begin(), flowTileSizes.end());
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, op, tileSizes,
DispatchLoweringPassPipeline::CPUDoubleTilingExpert);
}
static LogicalResult setARMRootConfig(func::FuncOp entryPointFn,
linalg::ContractionOpInterface op,
ArrayRef<int64_t> flowTileSizes,
int vectorSize) {
// Hardcoded tile sizes, where v is the native vector size.
// L1 tile sizes are {1, ..., 5v, v, 16v}.
// Vector tile sizes are {1, ..., v, v, v}
SmallVector<int64_t> l1TileSizes, vectorTileSizes;
int64_t nLoops = cast<linalg::LinalgOp>(op.getOperation()).getNumLoops();
if (nLoops >= 3) {
l1TileSizes.append(nLoops - 3, 1);
l1TileSizes.push_back(getMaxTileSize(0, flowTileSizes[nLoops - 3],
5 * vectorSize, vectorSize));
vectorTileSizes.append(nLoops - 3, 1);
vectorTileSizes.push_back(vectorSize);
}
if (nLoops >= 2) {
l1TileSizes.push_back(
getMaxTileSize(0, flowTileSizes[nLoops - 2], vectorSize, vectorSize));
vectorTileSizes.push_back(vectorSize);
}
// L1/vector tile size for k dimensions.
auto lhsShapedType = op.lhs().getType().cast<ShapedType>();
int64_t K = lhsShapedType.getShape().back();
l1TileSizes.push_back(getMaxTileSize(0, K, 16 * vectorSize, vectorSize));
vectorTileSizes.push_back(vectorSize);
TileSizesListType tileSizes;
tileSizes.emplace_back(flowTileSizes.begin(), flowTileSizes.end());
tileSizes.push_back(l1TileSizes);
tileSizes.push_back(vectorTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, op, tileSizes,
DispatchLoweringPassPipeline::CPUTileFuseAndVectorize);
}
/// Sets the lowering configuration for dispatch region with root op that
/// implements the contraction operation interface.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::ContractionOpInterface contractionOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
auto linalgOp = cast<linalg::LinalgOp>(contractionOp.getOperation());
unsigned numLoops = linalgOp.getNumLoops();
{
SmallVector<unsigned> dims;
linalgOp.getReductionDims(dims);
if (dims.size() != 1 || dims[0] != numLoops - 1) {
return contractionOp.emitOpError(
"expected to have exactly one reduction dim, and it is the innermost "
"dim");
}
}
// Consider all element types and use the smallest vector size. The tiling
// sizes are chosen based on the vector size.
auto lhsShapedType = contractionOp.lhs().getType().cast<ShapedType>();
auto rhsShapedType = contractionOp.rhs().getType().cast<ShapedType>();
auto resShapedType =
linalgOp.getOutputOperand(0)->get().getType().cast<ShapedType>();
int64_t vectorSize = getVectorSize(entryPointFn, lhsShapedType);
vectorSize = std::min(vectorSize, getVectorSize(entryPointFn, rhsShapedType));
vectorSize = std::min(vectorSize, getVectorSize(entryPointFn, resShapedType));
// Use the default distribution for the matmul loops.
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, linalgOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (numLoops > 3) {
minTileSizes[0] = 1;
maxTileSizes[0] = 1;
}
SmallVector<int64_t> flowTileSizes =
getDefaultDistributedLevelTileSizes(linalgOp, minTileSizes, maxTileSizes);
// TODO(dcaballe): Find better configurations for RISC-V backends.
if (isX86(entryPointFn) || isRISCV(entryPointFn)) {
SmallVector<int64_t> tileSizes = {8, 32, 16};
return setSandboxRootConfig(entryPointFn, contractionOp, flowTileSizes,
tileSizes, vectorSize);
}
// Fall back to ARM configurations.
bool isQuantized =
lhsShapedType.getElementType() != resShapedType.getElementType();
if (isQuantized) {
SmallVector<int64_t> tileSizes = {4, 16, 4};
return setSandboxRootConfig(entryPointFn, contractionOp, flowTileSizes,
tileSizes, vectorSize);
} else {
return setARMRootConfig(entryPointFn, contractionOp, flowTileSizes,
vectorSize);
}
}
/// Sets the lowering configuration for dispatch region for linalg.mmt4d root
/// op
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::Mmt4DOp mmt4dOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// TODO(ataei): These are hand tuned for some performance benchmarks for
// now, we want to adapt the same strategy as matmul that dynamically sets
// tile size.
auto getWorkgroupTileSizes = [&]() -> SmallVector<int64_t> {
if (!mmt4dWorkgroupTileSizes.empty()) {
return SmallVector<int64_t>(mmt4dWorkgroupTileSizes.begin(),
mmt4dWorkgroupTileSizes.end());
}
return {48, 32};
};
auto getL1TileSizes = [&]() -> SmallVector<int64_t> {
auto lhsShape = mmt4dOp.inputs()[0].getType().cast<ShapedType>().getShape();
auto rhsShape = mmt4dOp.inputs()[1].getType().cast<ShapedType>().getShape();
int M0 = lhsShape[2];
int N0 = rhsShape[2];
int K0 = lhsShape[3];
if (!mmt4dL1TileSizes.empty()) {
return SmallVector<int64_t>(mmt4dL1TileSizes.begin(),
mmt4dL1TileSizes.end());
}
return {1, 1, 1, M0, N0, K0};
};
auto getVectorSizes = [&]() -> SmallVector<int64_t> {
auto lhsShape = mmt4dOp.inputs()[0].getType().cast<ShapedType>().getShape();
auto rhsShape = mmt4dOp.inputs()[1].getType().cast<ShapedType>().getShape();
int M0 = lhsShape[2];
int N0 = rhsShape[2];
int K0 = lhsShape[3];
if (!mmt4dVectorSizes.empty()) {
return SmallVector<int64_t>(mmt4dVectorSizes.begin(),
mmt4dVectorSizes.end());
}
return {1, 1, 1, M0, N0, K0};
};
SmallVector<int64_t> nativeVectorSize = getVectorSizes();
TileSizesListType tileSizes = {getWorkgroupTileSizes(), getL1TileSizes(),
nativeVectorSize};
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, mmt4dOp, tileSizes,
DispatchLoweringPassPipeline::CPUTileFuseAndVectorize);
}
/// Sets the lowering configuration for dispatch region for linalg_ext.fft
/// root op.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, IREE::LinalgExt::FftOp fftOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
unsigned numLoops = fftOp.getLoopIteratorTypes().size();
auto partitionedLoops = fftOp.getPartitionableLoops(kNumMaxParallelDims);
SmallVector<int64_t> workgroupTileSizes(numLoops, defaultWorkgroupTileSize);
llvm::DenseSet<unsigned> partitionedLoopsSet(partitionedLoops.begin(),
partitionedLoops.end());
for (auto dim : llvm::seq<int64_t>(0, workgroupTileSizes.size())) {
if (!partitionedLoopsSet.count(dim)) {
workgroupTileSizes[dim] = 0;
}
}
auto rank = fftOp.getOperandRank();
if (workgroupTileSizes.size() >= rank && workgroupTileSizes[rank - 1] != 0) {
APInt value;
if (matchPattern(fftOp.getStage(), m_ConstantInt(&value))) {
workgroupTileSizes[rank - 1] = 1ll << value.getSExtValue();
workgroupTileSizes[rank - 1] =
std::max(workgroupTileSizes[rank - 1],
static_cast<int64_t>(defaultWorkgroupTileSize));
} else {
return fftOp.emitOpError("non-constant stage might not work for fft op");
}
}
TileSizesListType tileSizes = {workgroupTileSizes};
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, fftOp, tileSizes, DispatchLoweringPassPipeline::CPUDefault);
}
static void setX86WorkgroupTileSizes(
linalg::GenericOp genericOp, unsigned numLoops,
ArrayRef<int64_t> flowTileSizes, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes,
SmallVectorImpl<int64_t> &workgroupTileSizes) {
workgroupTileSizes.append(numLoops, 0);
SmallVector<int64_t, 4> staticLoopRanges = genericOp.getStaticLoopRanges();
for (auto loopNum : llvm::seq<unsigned>(0, numLoops)) {
if (flowTileSizes[loopNum]) {
workgroupTileSizes[loopNum] =
getMaxTileSize(0, flowTileSizes[loopNum], minTileSizes[loopNum],
minTileSizes[loopNum]);
} else {
// If the flow level tile size is zero, and static loop range is 0 as
// well, set the tile sizes here to zero as well.
workgroupTileSizes[loopNum] =
staticLoopRanges[loopNum] == 1 ? 0 : minTileSizes[loopNum];
}
}
}
/// Returns true if the operation is a GenericOp implementing a supported
/// transposition.
static bool isSupportedTransposeOp(linalg::GenericOp genericOp) {
// Check that the op has at least 2 dimensions.
if (genericOp.getNumLoops() < 2) {
return false;
}
// Check that the op has only one input and one output.
// TODO(diegocaballero): Generalize to multiple inputs.
if ((genericOp.getNumInputs() != 1) || (genericOp.getNumOutputs() != 1)) {
return false;
}
// Check that all the iterators are parallel.
if (genericOp.getNumParallelLoops() != genericOp.getNumLoops()) {
return false;
}
// Check that the two indexing maps are a permutation of each other.
auto indexing_maps = genericOp.getIndexingMaps();
return !indexing_maps[0].isEmpty() && !indexing_maps[1].isEmpty() &&
((indexing_maps[0].isIdentity() && !indexing_maps[1].isIdentity() &&
indexing_maps[1].isPermutation()) ||
(!indexing_maps[0].isIdentity() && indexing_maps[0].isPermutation() &&
indexing_maps[1].isIdentity()));
}
/// Sets the default lowering configuration for a generic op to use
/// CPUDoubleTilingExpert pipeline.
static LogicalResult setDefaultGenericOpRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(genericOp)) {
return success();
}
// If there are no loops, there is nothing to do.
unsigned numLoops = genericOp.getNumLoops();
if (numLoops == 0) return success();
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, genericOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (llvm::all_of(minTileSizes, [](int64_t vs) { return vs == 1; })) {
// Nothing to vectorize just lower to loops.
return success();
}
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
genericOp, minTileSizes, maxTileSizes);
// Set the next level tile sizes.
SmallVector<int64_t> parallelTileSizes;
SmallVector<int64_t> reductionTileSizes;
setX86WorkgroupTileSizes(genericOp, numLoops, flowTileSizes, minTileSizes,
maxTileSizes, parallelTileSizes);
splitParallelAndReductionTiles(genericOp, parallelTileSizes,
reductionTileSizes);
setAlwaysVectorizeSizes(genericOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
// For non-tensor based ops use the Buffer ops pipeline.
auto passPipeline =
genericOp.hasTensorSemantics()
? DispatchLoweringPassPipeline::CPUDoubleTilingExpert
: DispatchLoweringPassPipeline::CPUBufferOpsTileAndVectorize;
return setOpConfigAndEntryPointFnTranslation(entryPointFn, genericOp,
tileSizes, passPipeline);
}
/// Sets the lowering configuration for a generic op implementing a
/// transposition to use CPUDoubleTilingExpert pipeline.
static LogicalResult setTransposeLikeOpRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(genericOp)) {
return success();
}
if (!hasAVX2Features(genericOp) || !isSupportedTransposeOp(genericOp)) {
return success();
}
unsigned numLoops = genericOp.getNumLoops();
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, genericOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (llvm::all_of(minTileSizes, [](int64_t vs) { return vs == 1; })) {
// Nothing to vectorize just lower to loops.
return success();
}
if (llvm::count_if(minTileSizes,
[](int64_t tileSize) { return tileSize > 1; }) != 2) {
// Transpose patterns are not applicable if vectorizing more or less than
// two dims.
return success();
}
// Make sure that the original tile sizes are multiple of the tile sizes
// to be used for the transpose op (i.e., 8x8).
// TODO(diegocaballero): Enable 4x8 tile sizes if we find it useful.
if (llvm::any_of(minTileSizes, [](int64_t tileSize) {
return tileSize > 1 && (tileSize % 8) != 0;
})) {
return success();
}
// Replace dims to be vectorized with the new 8x8 tile sizes.
std::replace_if(
minTileSizes.begin(), minTileSizes.end(),
[](int64_t tileSize) { return tileSize > 1; }, 8);
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
genericOp, minTileSizes, maxTileSizes);
// Set the next level tile sizes.
SmallVector<int64_t> parallelTileSizes;
setX86WorkgroupTileSizes(genericOp, numLoops, flowTileSizes, minTileSizes,
maxTileSizes, parallelTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(/*reduction tile sizes=*/{});
// For non-tensor based ops use the Buffer ops pipeline.
auto passPipeline =
genericOp.hasTensorSemantics()
? DispatchLoweringPassPipeline::CPUDoubleTilingExpert
: DispatchLoweringPassPipeline::CPUBufferOpsTileAndVectorize;
return setOpConfigAndEntryPointFnTranslation(entryPointFn, genericOp,
tileSizes, passPipeline);
}
/// Sets the lowering configuration for a generic op to use
/// CPUDoubleTilingExpert pipeline.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (failed(
setTransposeLikeOpRootConfig(entryPointFn, genericOp, tiledLoops)) ||
failed(
setDefaultGenericOpRootConfig(entryPointFn, genericOp, tiledLoops))) {
return failure();
}
return success();
}
/// Sets the lowering configuration for linalg.conv_2d_nhwc_hwcf and
/// linalg.depthwise_conv_2d_nhwc_hwc operations.
static LogicalResult setConvRootConfig(
func::FuncOp entryPointFn, linalg::LinalgOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops,
ArrayRef<int64_t> targetTileSizes, int64_t vectorSize) {
if (!isa<linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp>(
convOp.getOperation())) {
return failure();
}
// Use the default distribution for the conv loops.
unsigned numLoops = convOp.getNumLoops();
SmallVector<int64_t> minTileSizes(numLoops, 1);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
SmallVector<int64_t> vectorSizeHints(numLoops, 1);
// Give the vector size hint on OC.
vectorSizeHints[3] = vectorSize;
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
convOp, minTileSizes, maxTileSizes, vectorSizeHints);
// Shapes of N, OH, OW, OC, KH, KW, (IC)
SmallVector<int64_t, 4> shapes = convOp.getStaticLoopRanges();
SmallVector<int64_t> parallelTileSizes(targetTileSizes.begin(),
targetTileSizes.end());
for (auto i : llvm::seq<unsigned>(0, parallelTileSizes.size())) {
auto tileSize = flowTileSizes[i] ? flowTileSizes[i] : shapes[i];
// If the tile size is intended to be 1, do not adjust it to `vectorSize`.
// The ops will be decomposed to lower-rank named ops.
if (parallelTileSizes[i] != 1) {
parallelTileSizes[i] =
getMaxTileSize(0, tileSize, parallelTileSizes[i], vectorSize);
}
}
SmallVector<int64_t> reductionTileSizes;
splitParallelAndReductionTiles(convOp, parallelTileSizes, reductionTileSizes);
setAlwaysVectorizeSizes(convOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, convOp, tileSizes,
DispatchLoweringPassPipeline::CPUConvTileAndDecomposeExpert);
}
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::Conv2DNhwcHwcfOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
int64_t vectorSize =
getVectorSize(entryPointFn, convOp.getResult(0).getType());
SmallVector<int64_t> targetTileSizes = {1, 1, 8, vectorSize * 2, 1, 1, 8};
return setConvRootConfig(entryPointFn, convOp, tiledLoops, targetTileSizes,
vectorSize);
}
/// Sets the lowering configuration for linalg.depthwise_conv_2d_nhwc_hwc
/// operations.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::DepthwiseConv2DNhwcHwcOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
int64_t vectorSize =
getVectorSize(entryPointFn, convOp.getResult(0).getType());
SmallVector<int64_t> targetTileSizes = {1, 1, 8, vectorSize * 2, 1, 3};
return setConvRootConfig(entryPointFn, convOp, tiledLoops, targetTileSizes,
vectorSize);
}
/// Set default configuration for Linalg ops.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::LinalgOp linalgOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(linalgOp)) return success();
auto partitionableLoopOp =
cast<IREE::Flow::PartitionableLoopsInterface>(linalgOp.getOperation());
SmallVector<int64_t> lbs(linalgOp.getNumLoops(), 0);
SmallVector<int64_t> ubs = linalgOp.getStaticLoopRanges();
return setDefaultRootConfig(entryPointFn, partitionableLoopOp, lbs, ubs,
linalgOp.hasTensorSemantics());
}
/// Set the default configuration for operations that implement the
/// `TiledOpInterface`.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn,
IREE::LinalgExt::TiledOpInterface tiledOpInterfaceOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(tiledOpInterfaceOp)) return success();
auto partitionableLoopOp = cast<IREE::Flow::PartitionableLoopsInterface>(
tiledOpInterfaceOp.getOperation());
// TODO(hanchung): Implement getStaticLoopRanges method for TiledOpInterface.
OpBuilder builder(tiledOpInterfaceOp.getContext());
builder.setInsertionPoint(tiledOpInterfaceOp);
SmallVector<Range> iterationDomain =
tiledOpInterfaceOp.getIterationDomain(builder);
auto getStaticValue = [](Value v) -> int64_t {
IntegerAttr attr;
if (!matchPattern(v, m_Constant(&attr))) return ShapedType::kDynamicSize;
return attr.getInt();
};
auto lbs = llvm::to_vector(llvm::map_range(
iterationDomain, [&](Range r) { return getStaticValue(r.offset); }));
auto ubs = llvm::to_vector(llvm::map_range(
iterationDomain, [&](Range r) { return getStaticValue(r.size); }));
return setDefaultRootConfig(entryPointFn, partitionableLoopOp, lbs, ubs,
/*hasTensorSemantics=*/true);
}
/// Redirects to methods that set the configuration based on operation type.
static LogicalResult setRootConfigImpl(
func::FuncOp entryPointFn, Operation *op,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// Do not overwrite default configuration.
if (getLoweringConfig(op)) return success();
// Redirect to individual operations.
auto setRootConfigFn = [&](Operation *op) -> LogicalResult {
return TypeSwitch<Operation *, LogicalResult>(op)
.Case<IREE::LinalgExt::FftOp, linalg::GenericOp, linalg::Mmt4DOp,
linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Case<linalg::ContractionOpInterface>([&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Case<linalg::LinalgOp, IREE::LinalgExt::TiledOpInterface>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Default([&](Operation *op) { return success(); });
};
return setRootConfigFn(op);
}
/// Redirects to methods that set the configuration based on operation type for
/// VMVX backend.
static LogicalResult setVMVXRootConfigImpl(
func::FuncOp entryPointFn, Operation *op,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(op)) return success();
// Redirect to individual operations.
auto setRootConfigFn = [&](Operation *op) -> LogicalResult {
return TypeSwitch<Operation *, LogicalResult>(op)
.Case<linalg::LinalgOp, IREE::LinalgExt::TiledOpInterface>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Default([&](Operation *op) { return success(); });
};
return setRootConfigFn(op);
}
/// Find the root operation for the dispatch region.
static FailureOr<Operation *> getRootOperation(
ArrayRef<Operation *> computeOps) {
Operation *rootOperation = nullptr;
auto updateRootOperation = [&](Operation *op) -> LogicalResult {
if (rootOperation) {
return op->emitOpError(
"unhandled multiple root operations in dispatch region");
}
rootOperation = op;
return success();
};
for (auto op : computeOps) {
if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op)) {
// Do not not treat linalg ops that are all parallel as root operations in
// this sweep.
if (linalgOp.getNumLoops() == linalgOp.getNumParallelLoops()) continue;
// All other linalg ops are root ops.
if (failed(updateRootOperation(op))) return failure();
continue;
}
if (auto tiledOpInterfaceOp =
dyn_cast<IREE::LinalgExt::TiledOpInterface>(op)) {
// TODO(ravishankarm): For now
// `tensor.extract_slice`/`tensor.insert_slice` implement the
// `tiledInterfaceOp`. With tile + distribute moved out of Flow
// dialect, this doesnt work anymore. Remove this when the external
// model implementation of
// `tensor.extract_slice`/`tensor.insert_slice` are dropped.
if (isa<tensor::ExtractSliceOp, tensor::InsertSliceOp>(op)) continue;
// All other operations that implement this interface are root ops.
if (failed(updateRootOperation(op))) return failure();
continue;
}
}
if (rootOperation) return rootOperation;
// If no root operation is found yet. Look for linalg generic ops.
for (auto op : llvm::reverse(computeOps)) {
if (isa<linalg::LinalgOp>(op)) {
if (failed(updateRootOperation(op))) return failure();
}
}
return rootOperation;
}
/// Finds the root operation in the given list of Linalg operations and sets
/// its configuration. Returns error for multiple root operations.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, ArrayRef<Operation *> computeOps,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
FailureOr<Operation *> rootOp = getRootOperation(computeOps);
if (failed(rootOp)) {
return failure();
}
Operation *rootOperation = rootOp.getValue();
if (rootOperation) {
if (isVMVXBackend(entryPointFn)) {
if (failed(
setVMVXRootConfigImpl(entryPointFn, rootOperation, tiledLoops))) {
return failure();
}
} else {
if (failed(setRootConfigImpl(entryPointFn, rootOperation, tiledLoops))) {
return failure();
}
}
}
if (!getTranslationInfo(entryPointFn)) {
// Fall back, just set the translation to CPUDefault.
setTranslationInfo(entryPointFn, DispatchLoweringPassPipeline::CPUDefault,
/*workloadPerWorkgroup=*/ArrayRef<int64_t>{},
/*workgroupSize=*/ArrayRef<int64_t>{});
}
return success();
}
/// Sets the translation information to use for a dispatch region.
static LogicalResult setTranslationInfoAndRootConfig(
func::FuncOp entryPointFn, ArrayRef<Operation *> computeOps,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// First check if the operations have a preset pipeline.
for (auto computeOp : computeOps) {
if (IREE::Codegen::CompilationInfoAttr compilationInfo =
getCompilationInfo(computeOp)) {
// If the function already has a translation, error out.
if (auto translationInfo = getTranslationInfo(entryPointFn)) {
return computeOp->emitOpError(
"multiple ops within dispatch trying to set the translation "
"info");
}
SmallVector<int64_t> workgroupSize =
compilationInfo.getWorkgroupSizeVals();
setTranslationInfo(entryPointFn, compilationInfo.getTranslationInfo(),
workgroupSize);
setLoweringConfig(computeOp, compilationInfo.getLoweringConfig());
eraseCompilationInfo(computeOp);
}
}
// Next set the configuration of the operations.
return setRootConfig(entryPointFn, computeOps, tiledLoops);
}
LogicalResult initCPULaunchConfig(ModuleOp moduleOp) {
llvm::StringMap<IREE::HAL::ExecutableEntryPointOp> entryPointOps =
getAllEntryPoints(moduleOp);
for (auto funcOp : moduleOp.getOps<func::FuncOp>()) {
auto entryPointOp = entryPointOps.lookup(funcOp.getName());
if (!entryPointOp) continue;
if (getTranslationInfo(entryPointOp)) continue;
// If using sandbox passes, currently set the workload_per_wg to be
// empty for single-threaded execution.
if (useLinalgTransformInterp) {
auto translationInfo = IREE::Codegen::TranslationInfoAttr::get(
moduleOp.getContext(), IREE::Codegen::DispatchLoweringPassPipeline::
LinalgTransformInterpCodegen);
setTranslationInfo(funcOp, translationInfo);
continue;
}
SmallVector<Operation *> computeOps;
SmallVector<LoopTilingAndDistributionInfo> tiledLoops;
// If there are no linalg ops, not using Linalg based lowering.
if (failed(getComputeOps(funcOp, computeOps, tiledLoops))) {
return failure();
}
if (failed(
setTranslationInfoAndRootConfig(funcOp, computeOps, tiledLoops))) {
return failure();
}
}
// The root confguration setting introduces `tensor.dim` operations. Resolve
// those away.
RewritePatternSet patterns(moduleOp.getContext());
memref::populateResolveRankedShapeTypeResultDimsPatterns(patterns);
return applyPatternsAndFoldGreedily(moduleOp, std::move(patterns));
}
} // namespace iree_compiler
} // namespace mlir
| 46,376
| 15,397
|
#include "bwtransform.h"
/*
* Author: Daniil [Mathtin] Shigapov
* Copyright (c) 2017 Mathtin <wdaniil@mail.ru>
* This file is released under the MIT license.
*/
size_t sa[L_PAGE];
size_t tmp[L_PAGE];
size_t tmp2[L_PAGE];
size_t count[L_PAGE];
size_t *cl, *workTmp;
#define REP(i, n) for (size_t i = 0; i < n; ++i)
#define REP1(i, n) for (size_t i = 1; i < n; ++i)
#define REVREP(i, n) for (size_t i = n; i + 1; --i)
#define NOT_EQUAL_CL(i, step, sz) \
cl[sa[i]] != cl[sa[i - 1]] || \
cl[(sa[i] + step) % sz] != cl[(sa[i - 1] + step) % sz]
static void SortSA(const size_t & step, const size_t & clcount,
const size_t & sz) {
REP(i, sz) {
workTmp[i] = (sa[i] + sz - step) % sz;
}
memset(count, 0, clcount * sizeof(size_t));
REP(i, sz) {
++count[cl[workTmp[i]]];
}
REP1(i, clcount) {
count[i] += count[i - 1];
}
REVREP(i, sz - 1) {
sa[--count[cl[workTmp[i]]]] = workTmp[i];
}
}
static void CalcCl(const size_t & step, size_t & clcount, const size_t & sz) {
workTmp[sa[0]] = 0;
clcount = 0;
REP1(i, sz) {
if (NOT_EQUAL_CL(i, step, sz)) {
++clcount;
}
workTmp[sa[i]] = clcount;
}
++clcount;
std::swap(cl, workTmp);
}
static void buildSA(const byte * s, const size_t & sz) {
cl = tmp, workTmp = tmp2;
memset(count, 0, 0x100 * sizeof(size_t));
REP(i, sz) {
++count[s[i]];
}
REP1(i, 0x100) {
count[i] += count[i - 1];
}
REP(i, sz) {
sa[--count[s[i]]] = i;
}
cl[sa[0]] = 0;
size_t clcount = 0;
REP1(i, sz) {
if (s[sa[i]] != s[sa[i - 1]]) {
++clcount;
}
cl[sa[i]] = clcount;
}
++clcount;
for (size_t h = 0; (1u << h) < sz; ++h) {
SortSA(1 << h, clcount, sz);
CalcCl(1 << h, clcount, sz);
}
}
static uint16_t BWTBuffer(byte * input, byte * output, size_t sz) {
if (sz == 0) {
return 0;
}
uint16_t opos = 0;
buildSA(input, sz);
REP(i, sz) {
output[i] = input[(sa[i] + sz - 1) % sz];
if (sa[i] == 0) {
opos = i;
}
}
return opos;
}
static void BWRBuffer(byte * input, byte * output, size_t sz, size_t j) {
memset(count, 0, 0x100 * sizeof(size_t));
REP(i, sz) {
++count[input[i]];
}
size_t sum = 0;
REP(i, 0x100) {
sum += count[i];
count[i] = sum - count[i];
}
REP(i, sz) {
tmp[count[input[i]]++] = i;
}
j = tmp[j];
REP(i, sz) {
output[i] = input[j];
j = tmp[j];
}
}
static byte PageToFlag(size_t page) {
if (page == L_PAGE) {
return FLAG_BEST;
} else if (page == S_PAGE) {
return FLAG_FAST;
}
return 0;
}
BWTransform::BWTransform(TMaFile & buffer, bool write)
: file(buffer)
, offsetPages(-1)
, grow(0)
, gpos(0)
, w(write)
, pageSet(false) {
bwtpage = file.Page() + sizeof(uint16_t);
bwtsize = (file.size() / file.Page()) * bwtpage + 1;
if (file.size() % file.Page()) {
bwtsize += file.size() % file.Page() + sizeof(uint16_t);
}
gpos = (bwtsize - 1) % bwtpage;
if (w) {
LoadPage(0);
}
}
BWTransform::~BWTransform() {
if (w && offsetPages != (size_t)-1) {
SwapOff();
}
}
void BWTransform::LoadPage(size_t p) {
if (p == offsetPages) {
return;
} else if (w && offsetPages != (size_t)-1) {
SwapOff();
}
file.LoadPage(p);
offsetPages = p;
if (w) {
return;
}
uint16_t opos = BWTBuffer(file.data(), buff + 3, file.PageSize());
buff[0] = PageToFlag(file.Page());
buff[1] = opos;
buff[2] = opos >> 8;
}
void BWTransform::SwapOff() {
if (grow > 2) {
resize(bwtsize + grow);
grow = 0;
}
BWRBuffer(buff + 3, file.data(), file.PageSize(),
buff[1] | ((buff[2]) << 8));
}
void BWTransformSTDIN::LoadPage(size_t p) {
bwtsize = file.size();
if (bwtsize == 0) {
return;
}
offsetPages = p;
byte * filepage = file.data();
size_t i;
for (i = 0; i < file.size() && i < file.Page(); ++i) {
filepage[i] = file[i];
}
grow = i + sizeof(uint16_t);
if (p == 0) {
++grow;
}
uint16_t opos = BWTBuffer(filepage, buff + 3, i);
buff[0] = PageToFlag(file.Page());
buff[1] = opos;
buff[2] = opos >> 8;
}
void BWTransformSTDOUT::LoadPage(size_t p) {
if (p == offsetPages) {
return;
} else if (offsetPages != (size_t)-1) {
SwapOff();
}
offsetPages = p;
}
void BWTransformSTDOUT::SwapOff() {
if (gpos < 2) {
return;
}
size_t off = gpos - 2;
gpos = 0;
byte * offBuff = file.data();
BWRBuffer(buff + 3, offBuff, off, buff[1] | ((buff[2]) << 8));
for (size_t i = 0; i < off; ++i) {
file[i] = offBuff[i];
}
}
| 5,015
| 2,162
|
#include "array_list.hpp" // подключаем заголовочный файл с объявлениями
#include <algorithm> // copy, fill
#include <cassert> // assert
#include <stdexcept> // out_of_range, invalid_argument
#include "private/internal.hpp" // вспомогательные функции
namespace itis {
ArrayList::ArrayList(int capacity) : capacity_{capacity} {
if (capacity <= 0) {
throw std::invalid_argument("ArrayList::capacity must be positive");
}
// Tip 1: используйте std::fill для заполнения выделенных ячеек массива значением Element::UNINITIALIZED
// здесь должен быть ваш код ...
data_ = new Element[capacity_]{};
std::fill(data_, data_ + capacity_, Element::UNINITIALIZED);
}
ArrayList::~ArrayList() {
// Tip 1: высвободите выделенную память
// Tip 2: не забудьте про логическую целостность объекта (инвариантность)
if (data_ != nullptr) {
delete[] data_;
data_ = nullptr;
}
size_ = 0;
capacity_ = 0;
}
void ArrayList::Add(Element e) {
// Tip 1: используйте метод resize(new_capacity) для расширения емкости массива
// здесь должен быть ваш код ...
if (size_ == capacity_)
resize(capacity_+kCapacityGrowthCoefficient);
assert(size_ < capacity_); // я здесь, чтобы не дать тебе сойти с правильного пути
// напишите свой код после расширения емкости массива здесь ...
data_[size_++] = e;
}
void ArrayList::Insert(int index, Element e) {
if (index != 0 && index != size_) {
// index = 0 и index == size это особые случаи, при которых всегда можно выполнить операцию вставки
internal::check_out_of_range(index, 0, size_);
}
// Tip 1: используйте метод resize(new_capacity) для расширения емкости массива
// напишите свой код здесь ...
if (size_ >= capacity_)
resize(capacity_+kCapacityGrowthCoefficient);
assert(size_ < capacity_); // я ни в коем случае не дам вам совершить ошибку всей вашей жизни
// Tip 2: для свдига элементов вправо можете использовать std::copy
// напишите свой код после расширения емкости массива здесь ...
std::copy(data_ + index, data_ + size_, data_ + index + 1);
data_[index] = e;
size_ += 1;
}
void ArrayList::Set(int index, Element value) {
internal::check_out_of_range(index, 0, size_);
// напишите свой код здесь ...
data_[index] = value;
}
Element ArrayList::Remove(int index) {
internal::check_out_of_range(index, 0, size_);
// Tip 1: можете использовать std::copy для сдвига элементов влево
// Tip 2: не забудьте задать значение Element::UNINITIALIZED освободившейся ячейке
// напишите свой код здесь ...
Element element = data_[index];
std::copy(data_ + index + 1, data_+size_, data_+index );
data_[size_ - 1] = Element::UNINITIALIZED;
size_--;
return element;
}
void ArrayList::Clear() {
// Tip 1: можете использовать std::fill для заполнения ячеек массива значением Element::UNINITIALIZED
// напишите свой код здесь ...
std::fill(data_, data_+capacity_, Element::UNINITIALIZED);
size_ = 0;
}
Element ArrayList::Get(int index) const {
internal::check_out_of_range(index, 0, size_);
// напишите свой код здесь ...
return data_[index];
}
int ArrayList::IndexOf(Element e) const {
// напишите свой код здесь ...
for (int i = 0; i < size_; ++i) {
if (data_[i] == e){
return i;
}
}
return -1;
}
// === РЕАЛИЗОВАНО ===
bool ArrayList::Contains(Element e) const {
// здесь был Рамиль
return IndexOf(e) != kNotFoundElementIndex;
}
// это делегирующий конструктор если что
ArrayList::ArrayList() : ArrayList(kInitCapacity) {}
int ArrayList::GetSize() const {
return size_;
}
int ArrayList::GetCapacity() const {
return capacity_;
}
bool ArrayList::IsEmpty() const {
return size_ == 0;
}
// Легенда: давным давно на планете под названием Земля жил да был Аватар...
// Аватар мог управлять четырьмя стихиями, но никак не мог совладать с C++ (фейспалм).
// Помогите найти непростительную ошибку Аватара,
// которая привела к гибели десятков тысяч котиков (плак-плак, шмыгание носом, втягивание соплей).
// P.S. кол-во ошибок может быть более одной, порядку операций можно верить
void ArrayList::resize(int new_capacity) {
assert(new_capacity > capacity_); // не ошибается тот, кто ничего не делает ...
// 1. выделяем новый участок памяти
auto new_data = new Element[new_capacity];
// 2. копируем данные на новый участок
std::copy(data_, data_ + size_, new_data);
// 3. заполняем "свободные" ячейки памяти значением Element::UNINITIALIZED
std::fill(new_data + size_, new_data + new_capacity, Element::UNINITIALIZED);
// 4. высвобождаем старый участок памяти меньшего размера
delete[] data_;
// 5. пересылаем указатель на новый участок памяти
data_ = new_data;
// 6. не забываем посолить ... кхм... обновить емкость массива
capacity_ = new_capacity;
}
// === ЗОНА 51: необходимо для тестирования ===
ArrayList::ArrayList(Element *data, int size, int capacity) : size_{size}, capacity_{capacity} {
assert(capacity > 0 && size >= 0 && size <= capacity);
data_ = new Element[capacity];
std::fill(data_, data_ + capacity, Element::UNINITIALIZED);
if (data != nullptr) {
std::copy(data, data + size, data_);
}
}
std::ostream &operator<<(std::ostream &os, const ArrayList &list) {
if (list.data_ != nullptr) {
os << "{ ";
for (int index = 0; index < list.capacity_ - 1; index++) {
os << internal::elem_to_str(list.data_[index]) << ", ";
}
os << internal::elem_to_str(list.data_[list.capacity_ - 1]) << " }";
} else {
os << "{ nullptr }";
}
return os;
}
bool operator==(const ArrayList &list, const std::vector<Element> &elements) {
if (list.data_ == nullptr) return false;
if (list.capacity_ != static_cast<int>(elements.size())) return false;
for (int index = 0; index < list.capacity_; index++) {
if (list.data_[index] != elements.at(index)) return false;
}
return true;
}
} // namespace itis
| 5,990
| 2,198
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef TESTVIEWSUBVIEW_HPP_
#define TESTVIEWSUBVIEW_HPP_
#include <gtest/gtest.h>
#include <Kokkos_Core.hpp>
#include <stdexcept>
#include <sstream>
#include <iostream>
namespace TestViewSubview {
template< class Layout, class Space >
struct getView {
static
Kokkos::View< double**, Layout, Space > get( int n, int m ) {
return Kokkos::View< double**, Layout, Space >( "G", n, m );
}
};
template< class Space >
struct getView< Kokkos::LayoutStride, Space > {
static
Kokkos::View< double**, Kokkos::LayoutStride, Space > get( int n, int m ) {
const int rank = 2;
const int order[] = { 0, 1 };
const unsigned dim[] = { unsigned( n ), unsigned( m ) };
Kokkos::LayoutStride stride = Kokkos::LayoutStride::order_dimensions( rank, order, dim );
return Kokkos::View< double**, Kokkos::LayoutStride, Space >( "G", stride );
}
};
template< class ViewType, class Space >
struct fill_1D {
typedef typename Space::execution_space execution_space;
typedef typename ViewType::size_type size_type;
ViewType a;
double val;
fill_1D( ViewType a_, double val_ ) : a( a_ ), val( val_ ) {}
KOKKOS_INLINE_FUNCTION
void operator()( const int i ) const { a( i ) = val; }
};
template< class ViewType, class Space >
struct fill_2D {
typedef typename Space::execution_space execution_space;
typedef typename ViewType::size_type size_type;
ViewType a;
double val;
fill_2D( ViewType a_, double val_ ) : a( a_ ), val( val_ ) {}
KOKKOS_INLINE_FUNCTION
void operator()( const int i ) const
{
for ( int j = 0; j < static_cast< int >( a.dimension_1() ); j++ ) {
a( i, j ) = val;
}
}
};
template< class Layout, class Space >
void test_auto_1d ()
{
typedef Kokkos::View< double**, Layout, Space > mv_type;
typedef typename mv_type::size_type size_type;
const double ZERO = 0.0;
const double ONE = 1.0;
const double TWO = 2.0;
const size_type numRows = 10;
const size_type numCols = 3;
mv_type X = getView< Layout, Space >::get( numRows, numCols );
typename mv_type::HostMirror X_h = Kokkos::create_mirror_view( X );
fill_2D< mv_type, Space > f1( X, ONE );
Kokkos::parallel_for( X.dimension_0(), f1 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type j = 0; j < numCols; ++j ) {
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == ONE );
}
}
fill_2D< mv_type, Space > f2( X, 0.0 );
Kokkos::parallel_for( X.dimension_0(), f2 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type j = 0; j < numCols; ++j ) {
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == ZERO );
}
}
fill_2D< mv_type, Space > f3( X, TWO );
Kokkos::parallel_for( X.dimension_0(), f3 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type j = 0; j < numCols; ++j ) {
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == TWO );
}
}
for ( size_type j = 0; j < numCols; ++j ) {
auto X_j = Kokkos::subview( X, Kokkos::ALL, j );
fill_1D< decltype( X_j ), Space > f4( X_j, ZERO );
Kokkos::parallel_for( X_j.dimension_0(), f4 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == ZERO );
}
for ( size_type jj = 0; jj < numCols; ++jj ) {
auto X_jj = Kokkos::subview ( X, Kokkos::ALL, jj );
fill_1D< decltype( X_jj ), Space > f5( X_jj, ONE );
Kokkos::parallel_for( X_jj.dimension_0(), f5 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, jj ) == ONE );
}
}
}
}
template< class LD, class LS, class Space >
void test_1d_strided_assignment_impl( bool a, bool b, bool c, bool d, int n, int m ) {
Kokkos::View< double**, LS, Space > l2d( "l2d", n, m );
int col = n > 2 ? 2 : 0;
int row = m > 2 ? 2 : 0;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
if ( a ) {
Kokkos::View< double*, LD, Space > l1da = Kokkos::subview( l2d, Kokkos::ALL, row );
ASSERT_TRUE( & l1da( 0 ) == & l2d( 0, row ) );
if ( n > 1 ) {
ASSERT_TRUE( & l1da( 1 ) == & l2d( 1, row ) );
}
}
if ( b && n > 13 ) {
Kokkos::View< double*, LD, Space > l1db = Kokkos::subview( l2d, std::pair< unsigned, unsigned >( 2, 13 ), row );
ASSERT_TRUE( & l1db( 0 ) == & l2d( 2, row ) );
ASSERT_TRUE( & l1db( 1 ) == & l2d( 3, row ) );
}
if ( c ) {
Kokkos::View< double*, LD, Space > l1dc = Kokkos::subview( l2d, col, Kokkos::ALL );
ASSERT_TRUE( & l1dc( 0 ) == & l2d( col, 0 ) );
if( m > 1 ) {
ASSERT_TRUE( & l1dc( 1 ) == & l2d( col, 1 ) );
}
}
if ( d && m > 13 ) {
Kokkos::View< double*, LD, Space > l1dd = Kokkos::subview( l2d, col, std::pair< unsigned, unsigned >( 2, 13 ) );
ASSERT_TRUE( & l1dd( 0 ) == & l2d( col, 2 ) );
ASSERT_TRUE( & l1dd( 1 ) == & l2d( col, 3 ) );
}
}
}
template< class Space >
void test_1d_strided_assignment() {
test_1d_strided_assignment_impl< Kokkos::LayoutStride, Kokkos::LayoutLeft, Space >( true, true, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutStride, Kokkos::LayoutRight, Space >( true, true, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutRight, Space >( false, false, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutRight, Space >( false, false, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 1 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutLeft, Space >( true, true, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutLeft, Space >( true, true, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 1 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutRight, Space >( true, true, true, true, 17, 1 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutRight, Space >( false, false, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutRight, Space >( false, false, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutRight, Space >( true, true, true, true, 17, 1 );
}
template< class Space >
void test_left_0()
{
typedef Kokkos::View< int [2][3][4][5][2][3][4][5], Kokkos::LayoutLeft, Space > view_static_8_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_static_8_type x_static_8( "x_static_left_8" );
ASSERT_TRUE( x_static_8.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( x_static_8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & x_static_8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 =
Kokkos::subview( x_static_8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3, 0, 1, 2, 3 );
ASSERT_TRUE( x1.is_contiguous() );
ASSERT_TRUE( & x1( 0 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x1( 1 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( x_static_8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! x2.is_contiguous() );
ASSERT_TRUE( & x2( 0, 0 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x_static_8( 0, 1, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x_static_8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x_static_8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! sx2.is_contiguous() );
ASSERT_TRUE( & sx2( 0, 0 ) == & x_static_8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x_static_8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x_static_8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x_static_8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( ! sx4.is_contiguous() );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x_static_8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_left_1()
{
typedef Kokkos::View< int ****[2][3][4][5], Kokkos::LayoutLeft, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_type x8( "x_left_8", 2, 3, 4, 5 );
ASSERT_TRUE( x8.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( x8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & x8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 =
Kokkos::subview( x8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3, 0, 1, 2, 3 );
ASSERT_TRUE( x1.is_contiguous() );
ASSERT_TRUE( & x1( 0 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x1( 1 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( x8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! x2.is_contiguous() );
ASSERT_TRUE( & x2( 0, 0 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x8( 0, 1, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! sx2.is_contiguous() );
ASSERT_TRUE( & sx2( 0, 0 ) == & x8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( ! sx4.is_contiguous() );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_left_2()
{
typedef Kokkos::View< int ****, Kokkos::LayoutLeft, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility<Kokkos::HostSpace, typename Space::memory_space>::accessible ) {
view_type x4( "x4", 2, 3, 4, 5 );
ASSERT_TRUE( x4.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( x4, 0, 0, 0, 0 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & x4( 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 =
Kokkos::subview( x4, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( x1.is_contiguous() );
ASSERT_TRUE( & x1( 0 ) == & x4( 0, 1, 2, 3 ) );
ASSERT_TRUE( & x1( 1 ) == & x4( 1, 1, 2, 3 ) );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( x4, Kokkos::pair< int, int >( 0, 2 ), 1
, Kokkos::pair< int, int >( 1, 3 ), 2 );
ASSERT_TRUE( ! x2.is_contiguous() );
ASSERT_TRUE( & x2( 0, 0 ) == & x4( 0, 1, 1, 2 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x4( 1, 1, 1, 2 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x4( 0, 1, 2, 2 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x4( 1, 1, 2, 2 ) );
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x4, 1, Kokkos::pair< int, int >( 0, 2 )
, 2, Kokkos::pair< int, int >( 1, 4 ) );
ASSERT_TRUE( ! sx2.is_contiguous() );
ASSERT_TRUE( & sx2( 0, 0 ) == & x4( 1, 0, 2, 1 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x4( 1, 1, 2, 1 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x4( 1, 0, 2, 2 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x4( 1, 1, 2, 2 ) );
ASSERT_TRUE( & sx2( 0, 2 ) == & x4( 1, 0, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 2 ) == & x4( 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x4, Kokkos::pair< int, int >( 1, 2 ) /* of [2] */
, Kokkos::pair< int, int >( 1, 3 ) /* of [3] */
, Kokkos::pair< int, int >( 0, 4 ) /* of [4] */
, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( ! sx4.is_contiguous() );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x4( 1 + i0, 1 + i1, 0 + i2, 2 + i3 ) );
}
}
}
template< class Space >
void test_left_3()
{
typedef Kokkos::View< int **, Kokkos::LayoutLeft, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_type xm( "x4", 10, 5 );
ASSERT_TRUE( xm.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( xm, 5, 3 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & xm( 5, 3 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 = Kokkos::subview( xm, Kokkos::ALL, 3 );
ASSERT_TRUE( x1.is_contiguous() );
for ( int i = 0; i < int( xm.dimension_0() ); ++i ) {
ASSERT_TRUE( & x1( i ) == & xm( i, 3 ) );
}
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( xm, Kokkos::pair< int, int >( 1, 9 ), Kokkos::ALL );
ASSERT_TRUE( ! x2.is_contiguous() );
for ( int j = 0; j < int( x2.dimension_1() ); ++j )
for ( int i = 0; i < int( x2.dimension_0() ); ++i )
{
ASSERT_TRUE( & x2( i, j ) == & xm( 1 + i, j ) );
}
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2c =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 2, 4 ) );
ASSERT_TRUE( x2c.is_contiguous() );
for ( int j = 0; j < int( x2c.dimension_1() ); ++j )
for ( int i = 0; i < int( x2c.dimension_0() ); ++i )
{
ASSERT_TRUE( & x2c( i, j ) == & xm( i, 2 + j ) );
}
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2_n1 =
Kokkos::subview( xm, std::pair< int, int >( 1, 1 ), Kokkos::ALL );
ASSERT_TRUE( x2_n1.dimension_0() == 0 );
ASSERT_TRUE( x2_n1.dimension_1() == xm.dimension_1() );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2_n2 =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 1, 1 ) );
ASSERT_TRUE( x2_n2.dimension_0() == xm.dimension_0() );
ASSERT_TRUE( x2_n2.dimension_1() == 0 );
}
}
//----------------------------------------------------------------------------
template< class Space >
void test_right_0()
{
typedef Kokkos::View< int [2][3][4][5][2][3][4][5], Kokkos::LayoutRight, Space > view_static_8_type;
if ( Kokkos::Impl::SpaceAccessibility<Kokkos::HostSpace, typename Space::memory_space>::accessible ) {
view_static_8_type x_static_8( "x_static_right_8" );
Kokkos::View< int, Kokkos::LayoutRight, Space > x0 = Kokkos::subview( x_static_8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( & x0() == & x_static_8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutRight, Space > x1 =
Kokkos::subview( x_static_8, 0, 1, 2, 3, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( x1.dimension_0() == 2 );
ASSERT_TRUE( & x1( 0 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x1( 1 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 2 ) );
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2 =
Kokkos::subview( x_static_8, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 )
, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( x2.dimension_0() == 2 );
ASSERT_TRUE( x2.dimension_1() == 2 );
ASSERT_TRUE( & x2( 0, 0 ) == & x_static_8( 0, 1, 2, 1, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x_static_8( 0, 1, 2, 2, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x_static_8( 0, 1, 2, 1, 0, 1, 2, 2 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x_static_8( 0, 1, 2, 2, 0, 1, 2, 2 ) );
// Kokkos::View< int**, Kokkos::LayoutRight, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x_static_8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( sx2.dimension_0() == 2 );
ASSERT_TRUE( sx2.dimension_1() == 2 );
ASSERT_TRUE( & sx2( 0, 0 ) == & x_static_8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x_static_8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x_static_8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x_static_8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( sx4.dimension_0() == 2 );
ASSERT_TRUE( sx4.dimension_1() == 2 );
ASSERT_TRUE( sx4.dimension_2() == 2 );
ASSERT_TRUE( sx4.dimension_3() == 2 );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x_static_8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_right_1()
{
typedef Kokkos::View< int ****[2][3][4][5], Kokkos::LayoutRight, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility<Kokkos::HostSpace, typename Space::memory_space>::accessible ) {
view_type x8( "x_right_8", 2, 3, 4, 5 );
Kokkos::View< int, Kokkos::LayoutRight, Space > x0 = Kokkos::subview( x8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( & x0() == & x8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutRight, Space > x1 =
Kokkos::subview( x8, 0, 1, 2, 3, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( & x1( 0 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x1( 1 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 2 ) );
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2 =
Kokkos::subview( x8, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 )
, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( & x2( 0, 0 ) == & x8( 0, 1, 2, 1, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x8( 0, 1, 2, 2, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x8( 0, 1, 2, 1, 0, 1, 2, 2 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x8( 0, 1, 2, 2, 0, 1, 2, 2 ) );
// Kokkos::View< int**, Kokkos::LayoutRight, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( & sx2( 0, 0 ) == & x8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_right_3()
{
typedef Kokkos::View< int **, Kokkos::LayoutRight, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_type xm( "x4", 10, 5 );
ASSERT_TRUE( xm.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutRight, Space > x0 = Kokkos::subview( xm, 5, 3 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & xm( 5, 3 ) );
Kokkos::View< int*, Kokkos::LayoutRight, Space > x1 = Kokkos::subview( xm, 3, Kokkos::ALL );
ASSERT_TRUE( x1.is_contiguous() );
for ( int i = 0; i < int( xm.dimension_1() ); ++i ) {
ASSERT_TRUE( & x1( i ) == & xm( 3, i ) );
}
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2c =
Kokkos::subview( xm, Kokkos::pair< int, int >( 1, 9 ), Kokkos::ALL );
ASSERT_TRUE( x2c.is_contiguous() );
for ( int j = 0; j < int( x2c.dimension_1() ); ++j )
for ( int i = 0; i < int( x2c.dimension_0() ); ++i ) {
ASSERT_TRUE( & x2c( i, j ) == & xm( 1 + i, j ) );
}
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2 =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 2, 4 ) );
ASSERT_TRUE( ! x2.is_contiguous() );
for ( int j = 0; j < int( x2.dimension_1() ); ++j )
for ( int i = 0; i < int( x2.dimension_0() ); ++i )
{
ASSERT_TRUE( & x2( i, j ) == & xm( i, 2 + j ) );
}
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2_n1 =
Kokkos::subview( xm, std::pair< int, int >( 1, 1 ), Kokkos::ALL );
ASSERT_TRUE( x2_n1.dimension_0() == 0 );
ASSERT_TRUE( x2_n1.dimension_1() == xm.dimension_1() );
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2_n2 =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 1, 1 ) );
ASSERT_TRUE( x2_n2.dimension_0() == xm.dimension_0() );
ASSERT_TRUE( x2_n2.dimension_1() == 0 );
}
}
namespace Impl {
constexpr int N0 = 113;
constexpr int N1 = 11;
constexpr int N2 = 17;
constexpr int N3 = 5;
constexpr int N4 = 7;
template< class SubView, class View >
void test_Check1D( SubView a, View b, std::pair< int, int > range ) {
int errors = 0;
for ( int i = 0; i < range.second - range.first; i++ ) {
if ( a( i ) != b( i + range.first ) ) errors++;
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check1D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template< class SubView, class View >
void test_Check1D2D( SubView a, View b, int i0, std::pair< int, int > range ) {
int errors = 0;
for ( int i1 = 0; i1 < range.second - range.first; i1++ ) {
if ( a( i1 ) != b( i0, i1 + range.first ) ) errors++;
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check1D2D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template< class SubView, class View >
void test_Check2D3D( SubView a, View b, int i0, std::pair< int, int > range1
, std::pair< int, int > range2 )
{
int errors = 0;
for ( int i1 = 0; i1 < range1.second - range1.first; i1++ ) {
for ( int i2 = 0; i2 < range2.second - range2.first; i2++ ) {
if ( a( i1, i2 ) != b( i0, i1 + range1.first, i2 + range2.first ) ) errors++;
}
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check2D3D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template<class SubView, class View>
void test_Check3D5D( SubView a, View b, int i0, int i1, std::pair< int, int > range2
, std::pair< int, int > range3, std::pair< int, int > range4 )
{
int errors = 0;
for ( int i2 = 0; i2 < range2.second - range2.first; i2++ ) {
for ( int i3 = 0; i3 < range3.second - range3.first; i3++ ) {
for ( int i4 = 0; i4 < range4.second - range4.first; i4++ ) {
if ( a( i2, i3, i4 ) != b( i0, i1, i2 + range2.first, i3 + range3.first, i4 + range4.first ) ) {
errors++;
}
}
}
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check3D5D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template< class Space, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_1d_assign_impl() {
{ // Breaks.
Kokkos::View< int*, LayoutOrg, Space > a_org( "A", N0 );
Kokkos::View< int*, LayoutOrg, Space, MemTraits > a( a_org );
Kokkos::fence();
for ( int i = 0; i < N0; i++ ) a_org( i ) = i;
Kokkos::View< int[N0], Layout, Space, MemTraits > a1( a );
Kokkos::fence();
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
Kokkos::View< int[N0], LayoutSub, Space, MemTraits > a2( a1 );
Kokkos::fence();
test_Check1D( a2, a, std::pair< int, int >( 0, N0 ) );
a1 = a;
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
// Runtime Fail expected.
//Kokkos::View< int[N1] > afail1( a );
// Compile Time Fail expected.
//Kokkos::View< int[N1] > afail2( a1 );
}
{ // Works.
Kokkos::View< int[N0], LayoutOrg, Space, MemTraits > a( "A" );
Kokkos::View< int*, Layout, Space, MemTraits > a1( a );
Kokkos::fence();
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
a1 = a;
Kokkos::fence();
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
}
}
template< class Space, class Type, class TypeSub, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_2d_subview_3d_impl_type() {
Kokkos::View< int***, LayoutOrg, Space > a_org( "A", N0, N1, N2 );
Kokkos::View< Type, Layout, Space, MemTraits > a( a_org );
for ( int i0 = 0; i0 < N0; i0++ )
for ( int i1 = 0; i1 < N1; i1++ )
for ( int i2 = 0; i2 < N2; i2++ )
{
a_org( i0, i1, i2 ) = i0 * 1000000 + i1 * 1000 + i2;
}
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a1;
a1 = Kokkos::subview( a, 3, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check2D3D( a1, a, 3, std::pair< int, int >( 0, N1 ), std::pair< int, int >( 0, N2 ) );
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a2( a, 3, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check2D3D( a2, a, 3, std::pair< int, int >( 0, N1 ), std::pair< int, int >( 0, N2 ) );
}
template< class Space, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_2d_subview_3d_impl_layout() {
test_2d_subview_3d_impl_type< Space, int[N0][N1][N2], int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int[N0][N1][N2], int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int[N0][N1][N2], int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int* [N1][N2], int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int* [N1][N2], int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int* [N1][N2], int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int** [N2], int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int** [N2], int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int** [N2], int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int*** , int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int*** , int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int*** , int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int[N0][N1][N2], const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int[N0][N1][N2], const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int[N0][N1][N2], const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int* [N1][N2], const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int* [N1][N2], const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int* [N1][N2], const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int** [N2], const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int** [N2], const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int** [N2], const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int*** , const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int*** , const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int*** , const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
}
template< class Space, class Type, class TypeSub, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_3d_subview_5d_impl_type() {
Kokkos::View< int*****, LayoutOrg, Space > a_org( "A", N0, N1, N2, N3, N4 );
Kokkos::View< Type, Layout, Space, MemTraits > a( a_org );
for ( int i0 = 0; i0 < N0; i0++ )
for ( int i1 = 0; i1 < N1; i1++ )
for ( int i2 = 0; i2 < N2; i2++ )
for ( int i3 = 0; i3 < N3; i3++ )
for ( int i4 = 0; i4 < N4; i4++ )
{
a_org( i0, i1, i2, i3, i4 ) = i0 * 1000000 + i1 * 10000 + i2 * 100 + i3 * 10 + i4;
}
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a1;
a1 = Kokkos::subview( a, 3, 5, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check3D5D( a1, a, 3, 5, std::pair< int, int >( 0, N2 ), std::pair< int, int >( 0, N3 ), std::pair< int, int >( 0, N4 ) );
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a2( a, 3, 5, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check3D5D( a2, a, 3, 5, std::pair< int, int >( 0, N2 ), std::pair< int, int >( 0, N3 ), std::pair< int, int >( 0, N4 ) );
}
template< class Space, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_3d_subview_5d_impl_layout() {
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
}
inline
void test_subview_legal_args_right() {
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
}
inline
void test_subview_legal_args_left() {
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
}
} // namespace Impl
template< class Space, class MemTraits = void >
void test_1d_assign() {
Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutLeft, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutStride, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutRight, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutStride, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutStride, Kokkos::LayoutLeft >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutStride, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutLeft, MemTraits >();
}
template< class Space, class MemTraits = void >
void test_2d_subview_3d() {
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutRight, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutRight, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutLeft, MemTraits >();
}
template< class Space, class MemTraits = void >
void test_3d_subview_5d_right() {
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutRight, MemTraits >();
}
template< class Space, class MemTraits = void >
void test_3d_subview_5d_left() {
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutLeft, MemTraits >();
}
namespace Impl {
template< class Layout, class Space >
struct FillView_3D {
Kokkos::View< int***, Layout, Space > a;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const
{
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % a.dimension_0()
: ii / ( a.dimension_1() * a.dimension_2() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / a.dimension_0() ) % a.dimension_1()
: ( ii / a.dimension_2() ) % a.dimension_1();
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( a.dimension_0() * a.dimension_1() )
: ii % a.dimension_2();
a( i, j, k ) = 1000000 * i + 1000 * j + k;
}
};
template< class Layout, class Space >
struct FillView_4D {
Kokkos::View< int****, Layout, Space > a;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const {
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % a.dimension_0()
: ii / ( a.dimension_1() * a.dimension_2() * a.dimension_3() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / a.dimension_0() ) % a.dimension_1()
: ( ii / ( a.dimension_2() * a.dimension_3() ) % a.dimension_1() );
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ( ii / ( a.dimension_0() * a.dimension_1() ) ) % a.dimension_2()
: ( ii / a.dimension_3() ) % a.dimension_2();
const int l = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( a.dimension_0() * a.dimension_1() * a.dimension_2() )
: ii % a.dimension_3();
a( i, j, k, l ) = 1000000 * i + 10000 * j + 100 * k + l;
}
};
template< class Layout, class Space, class MemTraits >
struct CheckSubviewCorrectness_3D_3D {
Kokkos::View< const int***, Layout, Space, MemTraits > a;
Kokkos::View< const int***, Layout, Space, MemTraits > b;
int offset_0, offset_2;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const
{
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % b.dimension_0()
: ii / ( b.dimension_1() * b.dimension_2() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / b.dimension_0() ) % b.dimension_1()
: ( ii / b.dimension_2() ) % b.dimension_1();
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( b.dimension_0() * b.dimension_1() )
: ii % b.dimension_2();
if ( a( i + offset_0, j, k + offset_2 ) != b( i, j, k ) ) {
Kokkos::abort( "Error: check_subview_correctness 3D-3D (LayoutLeft -> LayoutLeft or LayoutRight -> LayoutRight)" );
}
}
};
template< class Layout, class Space, class MemTraits >
struct CheckSubviewCorrectness_3D_4D {
Kokkos::View< const int****, Layout, Space, MemTraits > a;
Kokkos::View< const int***, Layout, Space, MemTraits > b;
int offset_0, offset_2, index;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const {
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % b.dimension_0()
: ii / ( b.dimension_1() * b.dimension_2() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / b.dimension_0() ) % b.dimension_1()
: ( ii / b.dimension_2() ) % b.dimension_1();
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( b.dimension_0() * b.dimension_1() )
: ii % b.dimension_2();
int i0, i1, i2, i3;
if ( std::is_same< Layout, Kokkos::LayoutLeft >::value ) {
i0 = i + offset_0;
i1 = j;
i2 = k + offset_2;
i3 = index;
}
else {
i0 = index;
i1 = i + offset_0;
i2 = j;
i3 = k + offset_2;
}
if ( a( i0, i1, i2, i3 ) != b( i, j, k ) ) {
Kokkos::abort( "Error: check_subview_correctness 3D-4D (LayoutLeft -> LayoutLeft or LayoutRight -> LayoutRight)" );
}
}
};
} // namespace Impl
template< class Space, class MemTraits = void >
void test_layoutleft_to_layoutleft() {
Impl::test_subview_legal_args_left();
{
Kokkos::View< int***, Kokkos::LayoutLeft, Space > a( "A", 100, 4, 3 );
Kokkos::View< int***, Kokkos::LayoutLeft, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::ALL );
Impl::FillView_3D< Kokkos::LayoutLeft, Space > fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) ), fill );
Impl::CheckSubviewCorrectness_3D_3D< Kokkos::LayoutLeft, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 0;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
{
Kokkos::View< int***, Kokkos::LayoutLeft, Space > a( "A", 100, 4, 5 );
Kokkos::View< int***, Kokkos::LayoutLeft, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::pair< int, int >( 1, 3 ) );
Impl::FillView_3D<Kokkos::LayoutLeft, Space> fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) ), fill );
Impl::CheckSubviewCorrectness_3D_3D< Kokkos::LayoutLeft, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 1;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
{
Kokkos::View< int****, Kokkos::LayoutLeft, Space > a( "A", 100, 4, 5, 3 );
Kokkos::View< int***, Kokkos::LayoutLeft, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::pair< int, int >( 1, 3 ), 1 );
Impl::FillView_4D< Kokkos::LayoutLeft, Space > fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) * a.extent( 3 ) ), fill );
Impl::CheckSubviewCorrectness_3D_4D< Kokkos::LayoutLeft, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 1;
check.index = 1;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
}
template< class Space, class MemTraits = void >
void test_layoutright_to_layoutright() {
Impl::test_subview_legal_args_right();
{
Kokkos::View< int***, Kokkos::LayoutRight, Space > a( "A", 100, 4, 3 );
Kokkos::View< int***, Kokkos::LayoutRight, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::ALL );
Impl::FillView_3D<Kokkos::LayoutRight, Space> fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) ), fill );
Impl::CheckSubviewCorrectness_3D_3D< Kokkos::LayoutRight, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 0;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
{
Kokkos::View< int****, Kokkos::LayoutRight, Space > a( "A", 3, 4, 5, 100 );
Kokkos::View< int***, Kokkos::LayoutRight, Space > b( a, 1, Kokkos::pair< int, int >( 1, 3 ), Kokkos::ALL, Kokkos::ALL );
Impl::FillView_4D< Kokkos::LayoutRight, Space > fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) * a.extent( 3 ) ), fill );
Impl::CheckSubviewCorrectness_3D_4D< Kokkos::LayoutRight, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 1;
check.offset_2 = 0;
check.index = 1;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
}
} // namespace TestViewSubview
#endif
| 74,686
| 33,793
|
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot_spectrogram.h"
#include "qwt_painter.h"
#include "qwt_interval.h"
#include "qwt_scale_map.h"
#include "qwt_color_map.h"
#include <qimage.h>
#include <qpen.h>
#include <qpainter.h>
#include <qmath.h>
#include <qalgorithms.h>
#if QT_VERSION >= 0x040400
#include <qthread.h>
#include <qfuture.h>
#include <qtconcurrentrun.h>
#endif
#define DEBUG_RENDER 0
#if DEBUG_RENDER
#include <QElapsedTimer>
#endif
class QwtPlotSpectrogram::PrivateData
{
public:
PrivateData():
data( NULL )
{
colorMap = new QwtLinearColorMap();
displayMode = ImageMode;
conrecFlags = QwtRasterData::IgnoreAllVerticesOnLevel;
#if 0
conrecFlags |= QwtRasterData::IgnoreOutOfRange;
#endif
}
~PrivateData()
{
delete data;
delete colorMap;
}
QwtRasterData *data;
QwtColorMap *colorMap;
DisplayModes displayMode;
QList<double> contourLevels;
QPen defaultContourPen;
QwtRasterData::ConrecFlags conrecFlags;
};
/*!
Sets the following item attributes:
- QwtPlotItem::AutoScale: true
- QwtPlotItem::Legend: false
The z value is initialized by 8.0.
\param title Title
\sa QwtPlotItem::setItemAttribute(), QwtPlotItem::setZ()
*/
QwtPlotSpectrogram::QwtPlotSpectrogram( const QString &title ):
QwtPlotRasterItem( title )
{
d_data = new PrivateData();
setItemAttribute( QwtPlotItem::AutoScale, true );
setItemAttribute( QwtPlotItem::Legend, false );
setZ( 8.0 );
}
//! Destructor
QwtPlotSpectrogram::~QwtPlotSpectrogram()
{
delete d_data;
}
//! \return QwtPlotItem::Rtti_PlotSpectrogram
int QwtPlotSpectrogram::rtti() const
{
return QwtPlotItem::Rtti_PlotSpectrogram;
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\param on On/Off
The default setting enables ImageMode.
\sa DisplayMode, displayMode()
*/
void QwtPlotSpectrogram::setDisplayMode( DisplayMode mode, bool on )
{
if ( on != bool( mode & d_data->displayMode ) )
{
if ( on )
d_data->displayMode |= mode;
else
d_data->displayMode &= ~mode;
}
legendChanged();
itemChanged();
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\return true if mode is enabled
*/
bool QwtPlotSpectrogram::testDisplayMode( DisplayMode mode ) const
{
return ( d_data->displayMode & mode );
}
/*!
Change the color map
Often it is useful to display the mapping between intensities and
colors as an additional plot axis, showing a color bar.
\param colorMap Color Map
\sa colorMap(), QwtScaleWidget::setColorBarEnabled(),
QwtScaleWidget::setColorMap()
*/
void QwtPlotSpectrogram::setColorMap( QwtColorMap *colorMap )
{
if ( d_data->colorMap != colorMap )
{
delete d_data->colorMap;
d_data->colorMap = colorMap;
}
invalidateCache();
legendChanged();
itemChanged();
}
/*!
\return Color Map used for mapping the intensity values to colors
\sa setColorMap()
*/
const QwtColorMap *QwtPlotSpectrogram::colorMap() const
{
return d_data->colorMap;
}
/*!
Build and assign the default pen for the contour lines
In Qt5 the default pen width is 1.0 ( 0.0 in Qt4 ) what makes it
non cosmetic ( see QPen::isCosmetic() ). This method has been introduced
to hide this incompatibility.
\param color Pen color
\param width Pen width
\param style Pen style
\sa pen(), brush()
*/
void QwtPlotSpectrogram::setDefaultContourPen(
const QColor &color, qreal width, Qt::PenStyle style )
{
setDefaultContourPen( QPen( color, width, style ) );
}
/*!
\brief Set the default pen for the contour lines
If the spectrogram has a valid default contour pen
a contour line is painted using the default contour pen.
Otherwise (pen.style() == Qt::NoPen) the pen is calculated
for each contour level using contourPen().
\sa defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::setDefaultContourPen( const QPen &pen )
{
if ( pen != d_data->defaultContourPen )
{
d_data->defaultContourPen = pen;
legendChanged();
itemChanged();
}
}
/*!
\return Default contour pen
\sa setDefaultContourPen()
*/
QPen QwtPlotSpectrogram::defaultContourPen() const
{
return d_data->defaultContourPen;
}
/*!
\brief Calculate the pen for a contour line
The color of the pen is the color for level calculated by the color map
\param level Contour level
\return Pen for the contour line
\note contourPen is only used if defaultContourPen().style() == Qt::NoPen
\sa setDefaultContourPen(), setColorMap(), setContourLevels()
*/
QPen QwtPlotSpectrogram::contourPen( double level ) const
{
if ( d_data->data == NULL || d_data->colorMap == NULL )
return QPen();
const QwtInterval intensityRange = d_data->data->interval(Qt::ZAxis);
const QColor c( d_data->colorMap->rgb( intensityRange, level ) );
return QPen( c );
}
/*!
Modify an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\param on On/Off
\sa testConrecFlag(), renderContourLines(),
QwtRasterData::contourLines()
*/
void QwtPlotSpectrogram::setConrecFlag(
QwtRasterData::ConrecFlag flag, bool on )
{
if ( bool( d_data->conrecFlags & flag ) == on )
return;
if ( on )
d_data->conrecFlags |= flag;
else
d_data->conrecFlags &= ~flag;
itemChanged();
}
/*!
Test an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\return true, is enabled
The default setting enables QwtRasterData::IgnoreAllVerticesOnLevel
\sa setConrecClag(), renderContourLines(),
QwtRasterData::contourLines()
*/
bool QwtPlotSpectrogram::testConrecFlag(
QwtRasterData::ConrecFlag flag ) const
{
return d_data->conrecFlags & flag;
}
/*!
Set the levels of the contour lines
\param levels Values of the contour levels
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
\note contourLevels returns the same levels but sorted.
*/
void QwtPlotSpectrogram::setContourLevels( const QList<double> &levels )
{
d_data->contourLevels = levels;
qSort( d_data->contourLevels );
legendChanged();
itemChanged();
}
/*!
\return Levels of the contour lines.
The levels are sorted in increasing order.
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
*/
QList<double> QwtPlotSpectrogram::contourLevels() const
{
return d_data->contourLevels;
}
/*!
Set the data to be displayed
\param data Spectrogram Data
\sa data()
*/
void QwtPlotSpectrogram::setData( QwtRasterData *data )
{
if ( data != d_data->data )
{
delete d_data->data;
d_data->data = data;
invalidateCache();
itemChanged();
}
}
/*!
\return Spectrogram data
\sa setData()
*/
const QwtRasterData *QwtPlotSpectrogram::data() const
{
return d_data->data;
}
/*!
\return Spectrogram data
\sa setData()
*/
QwtRasterData *QwtPlotSpectrogram::data()
{
return d_data->data;
}
/*!
\return Bounding interval for an axis
The default implementation returns the interval of the
associated raster data object.
\param axis X, Y, or Z axis
\sa QwtRasterData::interval()
*/
QwtInterval QwtPlotSpectrogram::interval(Qt::Axis axis) const
{
if ( d_data->data == NULL )
return QwtInterval();
return d_data->data->interval( axis );
}
/*!
\brief Pixel hint
The geometry of a pixel is used to calculated the resolution and
alignment of the rendered image.
The default implementation returns data()->pixelHint( rect );
\param area In most implementations the resolution of the data doesn't
depend on the requested area.
\return Bounding rectangle of a pixel
\sa QwtPlotRasterItem::pixelHint(), QwtRasterData::pixelHint(),
render(), renderImage()
*/
QRectF QwtPlotSpectrogram::pixelHint( const QRectF &area ) const
{
if ( d_data->data == NULL )
return QRectF();
return d_data->data->pixelHint( area );
}
/*!
\brief Render an image from data and color map.
For each pixel of area the value is mapped into a color.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param area Requested area for the image in scale coordinates
\param imageSize Size of the requested image
\return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending
on the color map.
\sa QwtRasterData::value(), QwtColorMap::rgb(),
QwtColorMap::colorIndex()
*/
QImage QwtPlotSpectrogram::renderImage(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &area, const QSize &imageSize ) const
{
if ( imageSize.isEmpty() || d_data->data == NULL
|| d_data->colorMap == NULL )
{
return QImage();
}
const QwtInterval intensityRange = d_data->data->interval( Qt::ZAxis );
if ( !intensityRange.isValid() )
return QImage();
QImage::Format format = ( d_data->colorMap->format() == QwtColorMap::RGB )
? QImage::Format_ARGB32 : QImage::Format_Indexed8;
QImage image( imageSize, format );
if ( d_data->colorMap->format() == QwtColorMap::Indexed )
image.setColorTable( d_data->colorMap->colorTable( intensityRange ) );
d_data->data->initRaster( area, image.size() );
#if DEBUG_RENDER
QElapsedTimer time;
time.start();
#endif
#if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE)
uint numThreads = renderThreadCount();
if ( numThreads <= 0 )
numThreads = QThread::idealThreadCount();
if ( numThreads <= 0 )
numThreads = 1;
const int numRows = imageSize.height() / numThreads;
QList< QFuture<void> > futures;
for ( uint i = 0; i < numThreads; i++ )
{
QRect tile( 0, i * numRows, image.width(), numRows );
if ( i == numThreads - 1 )
{
tile.setHeight( image.height() - i * numRows );
renderTile( xMap, yMap, tile, &image );
}
else
{
futures += QtConcurrent::run(
this, &QwtPlotSpectrogram::renderTile,
xMap, yMap, tile, &image );
}
}
for ( int i = 0; i < futures.size(); i++ )
futures[i].waitForFinished();
#else // QT_VERSION < 0x040400
const QRect tile( 0, 0, image.width(), image.height() );
renderTile( xMap, yMap, tile, &image );
#endif
#if DEBUG_RENDER
const qint64 elapsed = time.elapsed();
qDebug() << "renderImage" << imageSize << elapsed;
#endif
d_data->data->discardRaster();
return image;
}
/*!
\brief Render a tile of an image.
Rendering in tiles can be used to composite an image in parallel
threads.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param tile Geometry of the tile in image coordinates
\param image Image to be rendered
*/
void QwtPlotSpectrogram::renderTile(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRect &tile, QImage *image ) const
{
const QwtInterval range = d_data->data->interval( Qt::ZAxis );
if ( !range.isValid() )
return;
if ( d_data->colorMap->format() == QwtColorMap::RGB )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
QRgb *line = reinterpret_cast<QRgb *>( image->scanLine( y ) );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->rgb( range,
d_data->data->value( tx, ty ) );
}
}
}
else if ( d_data->colorMap->format() == QwtColorMap::Indexed )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
unsigned char *line = image->scanLine( y );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->colorIndex( range,
d_data->data->value( tx, ty ) );
}
}
}
}
/*!
\brief Return the raster to be used by the CONREC contour algorithm.
A larger size will improve the precision of the CONREC algorithm,
but will slow down the time that is needed to calculate the lines.
The default implementation returns rect.size() / 2 bounded to
the resolution depending on pixelSize().
\param area Rectangle, where to calculate the contour lines
\param rect Rectangle in pixel coordinates, where to paint the contour lines
\return Raster to be used by the CONREC contour algorithm.
\note The size will be bounded to rect.size().
\sa drawContourLines(), QwtRasterData::contourLines()
*/
QSize QwtPlotSpectrogram::contourRasterSize(
const QRectF &area, const QRect &rect ) const
{
QSize raster = rect.size() / 2;
const QRectF pixelRect = pixelHint( area );
if ( !pixelRect.isEmpty() )
{
const QSize res( qCeil( rect.width() / pixelRect.width() ),
qCeil( rect.height() / pixelRect.height() ) );
raster = raster.boundedTo( res );
}
return raster;
}
/*!
Calculate contour lines
\param rect Rectangle, where to calculate the contour lines
\param raster Raster, used by the CONREC algorithm
\return Calculated contour lines
\sa contourLevels(), setConrecFlag(),
QwtRasterData::contourLines()
*/
QwtRasterData::ContourLines QwtPlotSpectrogram::renderContourLines(
const QRectF &rect, const QSize &raster ) const
{
if ( d_data->data == NULL )
return QwtRasterData::ContourLines();
return d_data->data->contourLines( rect, raster,
d_data->contourLevels, d_data->conrecFlags );
}
/*!
Paint the contour lines
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param contourLines Contour lines
\sa renderContourLines(), defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::drawContourLines( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QwtRasterData::ContourLines &contourLines ) const
{
if ( d_data->data == NULL )
return;
const int numLevels = d_data->contourLevels.size();
for ( int l = 0; l < numLevels; l++ )
{
const double level = d_data->contourLevels[l];
QPen pen = defaultContourPen();
if ( pen.style() == Qt::NoPen )
pen = contourPen( level );
if ( pen.style() == Qt::NoPen )
continue;
painter->setPen( pen );
const QPolygonF &lines = contourLines[level];
for ( int i = 0; i < lines.size(); i += 2 )
{
const QPointF p1( xMap.transform( lines[i].x() ),
yMap.transform( lines[i].y() ) );
const QPointF p2( xMap.transform( lines[i+1].x() ),
yMap.transform( lines[i+1].y() ) );
QwtPainter::drawLine( painter, p1, p2 );
}
}
}
/*!
\brief Draw the spectrogram
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param canvasRect Contents rectangle of the canvas in painter coordinates
\sa setDisplayMode(), renderImage(),
QwtPlotRasterItem::draw(), drawContourLines()
*/
void QwtPlotSpectrogram::draw( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &canvasRect ) const
{
if ( d_data->displayMode & ImageMode )
QwtPlotRasterItem::draw( painter, xMap, yMap, canvasRect );
if ( d_data->displayMode & ContourMode )
{
// Add some pixels at the borders
const int margin = 2;
QRectF rasterRect( canvasRect.x() - margin, canvasRect.y() - margin,
canvasRect.width() + 2 * margin, canvasRect.height() + 2 * margin );
QRectF area = QwtScaleMap::invTransform( xMap, yMap, rasterRect );
const QRectF br = boundingRect();
if ( br.isValid() )
{
area &= br;
if ( area.isEmpty() )
return;
rasterRect = QwtScaleMap::transform( xMap, yMap, area );
}
QSize raster = contourRasterSize( area, rasterRect.toRect() );
raster = raster.boundedTo( rasterRect.toRect().size() );
if ( raster.isValid() )
{
const QwtRasterData::ContourLines lines =
renderContourLines( area, raster );
drawContourLines( painter, xMap, yMap, lines );
}
}
}
| 17,327
| 5,700
|
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#define FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#include <fcppt/math/to_array_type.hpp>
#include <fcppt/config/external_begin.hpp>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace math
{
/**
\brief Constructs an object with static storage from an array rvalue
\ingroup fcpptmath
*/
template<
typename Type
>
inline
Type
from_array(
fcppt::math::to_array_type<
Type
> &&_value
)
{
return
Type{
typename
Type::storage_type{
std::move(
_value
)
}
};
}
/**
\brief Constructs an object with static storage from an array lvalue
\ingroup fcpptmath
*/
template<
typename Type
>
inline
Type
from_array(
fcppt::math::to_array_type<
Type
> const &_value
)
{
return
Type{
typename
Type::storage_type{
_value
}
};
}
}
}
#endif
| 1,077
| 468
|
/**
* Copyright (c) 2017-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.
*/
#include "ServiceDiscoveryConfig.h"
#include <folly/Range.h>
#include "logdevice/common/debug.h"
#include "logdevice/common/types_internal.h"
namespace facebook { namespace logdevice { namespace configuration {
namespace nodes {
namespace {
template <typename F>
bool isFieldValid(const F& field, folly::StringPiece name) {
if (!field.valid()) {
RATELIMIT_ERROR(
std::chrono::seconds(10), 5, "invalid %s.", name.str().c_str());
return false;
}
return true;
}
template <typename F>
bool isOptionalFieldValid(const F& field, folly::StringPiece name) {
return !field.hasValue() || isFieldValid(field.value(), name);
}
} // namespace
bool NodeServiceDiscovery::isValid() const {
if (!isFieldValid(address, "address") &&
!isFieldValid(gossip_address, "gossip_address") &&
!isOptionalFieldValid(ssl_address, "ssl_address") &&
!isOptionalFieldValid(admin_address, "admin_address")) {
return false;
}
if (roles.count() == 0) {
RATELIMIT_ERROR(std::chrono::seconds(10),
5,
"no role is set. expect at least one role.");
return false;
}
return true;
}
template <>
bool ServiceDiscoveryConfig::attributeSpecificValidate() const {
// check for address duplication in service discovery
std::unordered_map<Sockaddr, node_index_t, Sockaddr::Hash> seen_addresses;
for (const auto& kv : node_states_) {
auto res =
seen_addresses.insert(std::make_pair(kv.second.address, kv.first));
if (!res.second) {
RATELIMIT_ERROR(std::chrono::seconds(10),
5,
"Multiple nodes with the same address (idx: %hd, %hd).",
res.first->second,
kv.first);
return false;
}
}
return true;
}
}}}} // namespace facebook::logdevice::configuration::nodes
| 2,067
| 654
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "details/Engine.h"
#include "MaterialParser.h"
#include "ResourceAllocator.h"
#include "backend/DriverEnums.h"
#include "details/DFG.h"
#include "details/VertexBuffer.h"
#include "details/Fence.h"
#include "details/Camera.h"
#include "details/IndexBuffer.h"
#include "details/IndirectLight.h"
#include "details/Material.h"
#include "details/Renderer.h"
#include "details/RenderPrimitive.h"
#include "details/Scene.h"
#include "details/Skybox.h"
#include "details/Stream.h"
#include "details/SwapChain.h"
#include "details/Texture.h"
#include "details/View.h"
#include <private/filament/SibGenerator.h>
#include <filament/MaterialEnums.h>
#include <utils/compiler.h>
#include <utils/Log.h>
#include <utils/Panic.h>
#include <utils/Systrace.h>
#include <utils/debug.h>
#include <memory>
#include "generated/resources/materials.h"
using namespace filament::math;
using namespace utils;
namespace filament {
using namespace backend;
using namespace filaflat;
FEngine* FEngine::create(Backend backend, Platform* platform, void* sharedGLContext) {
SYSTRACE_ENABLE();
SYSTRACE_CALL();
FEngine* instance = new FEngine(backend, platform, sharedGLContext);
// initialize all fields that need an instance of FEngine
// (this cannot be done safely in the ctor)
// Normally we launch a thread and create the context and Driver from there (see FEngine::loop).
// In the single-threaded case, we do so in the here and now.
if (!UTILS_HAS_THREADING) {
if (platform == nullptr) {
platform = DefaultPlatform::create(&instance->mBackend);
instance->mPlatform = platform;
instance->mOwnPlatform = true;
}
if (platform == nullptr) {
slog.e << "Selected backend not supported in this build." << io::endl;
return nullptr;
}
instance->mDriver = platform->createDriver(sharedGLContext);
} else {
// start the driver thread
instance->mDriverThread = std::thread(&FEngine::loop, instance);
// wait for the driver to be ready
instance->mDriverBarrier.await();
if (UTILS_UNLIKELY(!instance->mDriver)) {
// something went horribly wrong during driver initialization
instance->mDriverThread.join();
return nullptr;
}
}
// now we can initialize the largest part of the engine
instance->init();
if (!UTILS_HAS_THREADING) {
instance->execute();
}
return instance;
}
#if UTILS_HAS_THREADING
void FEngine::createAsync(CreateCallback callback, void* user,
Backend backend, Platform* platform, void* sharedGLContext) {
SYSTRACE_ENABLE();
SYSTRACE_CALL();
FEngine* instance = new FEngine(backend, platform, sharedGLContext);
// start the driver thread
instance->mDriverThread = std::thread(&FEngine::loop, instance);
// launch a thread to call the callback -- so it can't do any damage.
std::thread callbackThread = std::thread([instance, callback, user]() {
instance->mDriverBarrier.await();
callback(user, instance);
});
// let the callback thread die on its own
callbackThread.detach();
}
FEngine* FEngine::getEngine(void* token) {
FEngine* instance = static_cast<FEngine*>(token);
ASSERT_PRECONDITION(instance->mMainThreadId == std::this_thread::get_id(),
"Engine::createAsync() and Engine::getEngine() must be called on the same thread.");
// we use mResourceAllocator as a proxy for "am I already initialized"
if (!instance->mResourceAllocator) {
if (UTILS_UNLIKELY(!instance->mDriver)) {
// something went horribly wrong during driver initialization
instance->mDriverThread.join();
return nullptr;
}
// now we can initialize the largest part of the engine
instance->init();
}
return instance;
}
#endif
// these must be static because only a pointer is copied to the render stream
// Note that these coordinates are specified in OpenGL clip space. Other backends can transform
// these in the vertex shader as needed.
static constexpr float4 sFullScreenTriangleVertices[3] = {
{ -1.0f, -1.0f, 1.0f, 1.0f },
{ 3.0f, -1.0f, 1.0f, 1.0f },
{ -1.0f, 3.0f, 1.0f, 1.0f }
};
// these must be static because only a pointer is copied to the render stream
static const uint16_t sFullScreenTriangleIndices[3] = { 0, 1, 2 };
FEngine::FEngine(Backend backend, Platform* platform, void* sharedGLContext) :
mBackend(backend),
mPlatform(platform),
mSharedGLContext(sharedGLContext),
mPostProcessManager(*this),
mEntityManager(EntityManager::get()),
mRenderableManager(*this),
mTransformManager(),
mLightManager(*this),
mCameraManager(*this),
mCommandBufferQueue(CONFIG_MIN_COMMAND_BUFFERS_SIZE, CONFIG_COMMAND_BUFFERS_SIZE),
mPerRenderPassAllocator("per-renderpass allocator", CONFIG_PER_RENDER_PASS_ARENA_SIZE),
mEngineEpoch(std::chrono::steady_clock::now()),
mDriverBarrier(1),
mMainThreadId(std::this_thread::get_id())
{
// we're assuming we're on the main thread here.
// (it may not be the case)
mJobSystem.adopt();
slog.i << "FEngine (" << sizeof(void*) * 8 << " bits) created at " << this << " "
<< "(threading is " << (UTILS_HAS_THREADING ? "enabled)" : "disabled)") << io::endl;
}
/*
* init() is called just after the driver thread is initialized. Driver commands are therefore
* possible.
*/
void FEngine::init() {
SYSTRACE_CALL();
// this must be first.
mCommandStream = CommandStream(*mDriver, mCommandBufferQueue.getCircularBuffer());
DriverApi& driverApi = getDriverApi();
mResourceAllocator = new ResourceAllocator(driverApi);
mFullScreenTriangleVb = upcast(VertexBuffer::Builder()
.vertexCount(3)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT4, 0)
.build(*this));
mFullScreenTriangleVb->setBufferAt(*this, 0,
{ sFullScreenTriangleVertices, sizeof(sFullScreenTriangleVertices) });
mFullScreenTriangleIb = upcast(IndexBuffer::Builder()
.indexCount(3)
.bufferType(IndexBuffer::IndexType::USHORT)
.build(*this));
mFullScreenTriangleIb->setBuffer(*this,
{ sFullScreenTriangleIndices, sizeof(sFullScreenTriangleIndices) });
mFullScreenTriangleRph = driverApi.createRenderPrimitive();
driverApi.setRenderPrimitiveBuffer(mFullScreenTriangleRph,
mFullScreenTriangleVb->getHwHandle(), mFullScreenTriangleIb->getHwHandle(),
mFullScreenTriangleVb->getDeclaredAttributes().getValue());
driverApi.setRenderPrimitiveRange(mFullScreenTriangleRph, PrimitiveType::TRIANGLES,
0, 0, 2, (uint32_t)mFullScreenTriangleIb->getIndexCount());
mDefaultIblTexture = upcast(Texture::Builder()
.width(1).height(1).levels(1)
.format(Texture::InternalFormat::RGBA8)
.sampler(Texture::Sampler::SAMPLER_CUBEMAP)
.build(*this));
static uint32_t pixel = 0;
Texture::PixelBufferDescriptor buffer(
&pixel, 4, // 4 bytes in 1 RGBA pixel
Texture::Format::RGBA, Texture::Type::UBYTE);
Texture::FaceOffsets offsets = {};
mDefaultIblTexture->setImage(*this, 0, std::move(buffer), offsets);
// 3 bands = 9 float3
const float sh[9 * 3] = { 0.0f };
mDefaultIbl = upcast(IndirectLight::Builder()
.irradiance(3, reinterpret_cast<const float3*>(sh))
.build(*this));
mDefaultColorGrading = upcast(ColorGrading::Builder().build(*this));
// Always initialize the default material, most materials' depth shaders fallback on it.
mDefaultMaterial = upcast(
FMaterial::DefaultMaterialBuilder()
.package(MATERIALS_DEFAULTMATERIAL_DATA, MATERIALS_DEFAULTMATERIAL_SIZE)
.build(*const_cast<FEngine*>(this)));
mPostProcessManager.init();
mLightManager.init(*this);
mDFG = std::make_unique<DFG>(*this);
}
FEngine::~FEngine() noexcept {
SYSTRACE_CALL();
ASSERT_DESTRUCTOR(mTerminated, "Engine destroyed but not terminated!");
delete mResourceAllocator;
delete mDriver;
if (mOwnPlatform) {
DefaultPlatform::destroy((DefaultPlatform**)&mPlatform);
}
}
void FEngine::shutdown() {
SYSTRACE_CALL();
ASSERT_PRECONDITION(std::this_thread::get_id() == mMainThreadId,
"Engine::shutdown() called from the wrong thread!");
#ifndef NDEBUG
// print out some statistics about this run
size_t wm = mCommandBufferQueue.getHighWatermark();
size_t wmpct = wm / (CONFIG_COMMAND_BUFFERS_SIZE / 100);
slog.d << "CircularBuffer: High watermark "
<< wm / 1024 << " KiB (" << wmpct << "%)" << io::endl;
#endif
DriverApi& driver = getDriverApi();
/*
* Destroy our own state first
*/
mPostProcessManager.terminate(driver); // free-up post-process manager resources
mResourceAllocator->terminate();
mDFG->terminate(); // free-up the DFG
mRenderableManager.terminate(); // free-up all renderables
mLightManager.terminate(); // free-up all lights
mCameraManager.terminate(); // free-up all cameras
driver.destroyRenderPrimitive(mFullScreenTriangleRph);
destroy(mFullScreenTriangleIb);
destroy(mFullScreenTriangleVb);
destroy(mDefaultIblTexture);
destroy(mDefaultIbl);
destroy(mDefaultColorGrading);
destroy(mDefaultMaterial);
/*
* clean-up after the user -- we call terminate on each "leaked" object and clear each list.
*
* This should free up everything.
*/
// try to destroy objects in the inverse dependency
cleanupResourceList(mRenderers);
cleanupResourceList(mViews);
cleanupResourceList(mScenes);
cleanupResourceList(mSkyboxes);
cleanupResourceList(mColorGradings);
// this must be done after Skyboxes and before materials
destroy(mSkyboxMaterial);
cleanupResourceList(mIndexBuffers);
cleanupResourceList(mVertexBuffers);
cleanupResourceList(mTextures);
cleanupResourceList(mRenderTargets);
cleanupResourceList(mMaterials);
for (auto& item : mMaterialInstances) {
cleanupResourceList(item.second);
}
cleanupResourceList(mFences);
/*
* Shutdown the backend...
*/
// There might be commands added by the terminate() calls, so we need to flush all commands
// up to this point. After flushCommandBuffer() is called, all pending commands are guaranteed
// to be executed before the driver thread exits.
flushCommandBuffer(mCommandBufferQueue);
// now wait for all pending commands to be executed and the thread to exit
mCommandBufferQueue.requestExit();
if (!UTILS_HAS_THREADING) {
execute();
getDriverApi().terminate();
} else {
mDriverThread.join();
}
// Finally, call user callbacks that might have been scheduled.
// These callbacks CANNOT call driver APIs.
getDriver().purge();
/*
* Terminate the JobSystem...
*/
// detach this thread from the jobsystem
mJobSystem.emancipate();
mTerminated = true;
}
void FEngine::prepare() {
SYSTRACE_CALL();
// prepare() is called once per Renderer frame. Ideally we would upload the content of
// UBOs that are visible only. It's not such a big issue because the actual upload() is
// skipped is the UBO hasn't changed. Still we could have a lot of these.
FEngine::DriverApi& driver = getDriverApi();
for (auto& materialInstanceList : mMaterialInstances) {
for (const auto& item : materialInstanceList.second) {
item->commit(driver);
}
}
// Commit default material instances.
for (const auto& material : mMaterials) {
material->getDefaultInstance()->commit(driver);
}
}
void FEngine::gc() {
// Note: this runs in a Job
JobSystem& js = mJobSystem;
auto *parent = js.createJob();
auto em = std::ref(mEntityManager);
js.run(jobs::createJob(js, parent, &FRenderableManager::gc, &mRenderableManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FLightManager::gc, &mLightManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FTransformManager::gc, &mTransformManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FCameraManager::gc, &mCameraManager, em),
JobSystem::DONT_SIGNAL);
js.runAndWait(parent);
}
void FEngine::flush() {
// flush the command buffer
flushCommandBuffer(mCommandBufferQueue);
}
void FEngine::flushAndWait() {
#if defined(ANDROID)
// first make sure we've not terminated filament
ASSERT_PRECONDITION(!mCommandBufferQueue.isExitRequested(),
"calling Engine::flushAndWait() after Engine::shutdown()!");
#endif
// enqueue finish command -- this will stall in the driver until the GPU is done
getDriverApi().finish();
#if defined(ANDROID)
// then create a fence that will trigger when we're past the finish() above
size_t tryCount = 8;
FFence* fence = FEngine::createFence(FFence::Type::SOFT);
do {
FenceStatus status = fence->wait(FFence::Mode::FLUSH,250000000u);
// if the fence didn't trigger after 250ms, check that the command queue thread is still
// running (otherwise indicating a precondition violation).
if (UTILS_UNLIKELY(status == FenceStatus::TIMEOUT_EXPIRED)) {
ASSERT_PRECONDITION(!mCommandBufferQueue.isExitRequested(),
"called Engine::shutdown() WHILE in Engine::flushAndWait()!");
tryCount--;
ASSERT_POSTCONDITION(tryCount, "flushAndWait() failed inexplicably after 2s");
// if the thread is still running, maybe we just need to give it more time
continue;
}
break;
} while (true);
destroy(fence);
#else
FFence::waitAndDestroy(
FEngine::createFence(FFence::Type::SOFT), FFence::Mode::FLUSH);
#endif
// finally, execute callbacks that might have been scheduled
getDriver().purge();
}
// -----------------------------------------------------------------------------------------------
// Render thread / command queue
// -----------------------------------------------------------------------------------------------
int FEngine::loop() {
if (mPlatform == nullptr) {
mPlatform = DefaultPlatform::create(&mBackend);
mOwnPlatform = true;
const char* const backend = backendToString(mBackend);
slog.d << "FEngine resolved backend: " << backend << io::endl;
if (mPlatform == nullptr) {
slog.e << "Selected backend not supported in this build." << io::endl;
mDriverBarrier.latch();
return 0;
}
}
#if FILAMENT_ENABLE_MATDBG
#ifdef ANDROID
const char* portString = "8081";
#else
const char* portString = getenv("FILAMENT_MATDBG_PORT");
#endif
if (portString != nullptr) {
const int port = atoi(portString);
debug.server = new matdbg::DebugServer(mBackend, port);
// Sometimes the server can fail to spin up (e.g. if the above port is already in use).
// When this occurs, carry onward, developers can look at civetweb.txt for details.
if (!debug.server->isReady()) {
delete debug.server;
debug.server = nullptr;
} else {
debug.server->setEditCallback(FMaterial::onEditCallback);
debug.server->setQueryCallback(FMaterial::onQueryCallback);
}
}
#endif
JobSystem::setThreadName("FEngine::loop");
JobSystem::setThreadPriority(JobSystem::Priority::DISPLAY);
mDriver = mPlatform->createDriver(mSharedGLContext);
mDriverBarrier.latch();
if (UTILS_UNLIKELY(!mDriver)) {
// if we get here, it's because the driver couldn't be initialized and the problem has
// been logged.
return 0;
}
// We use the highest affinity bit, assuming this is a Big core in a big.little
// configuration. This is also a core not used by the JobSystem.
// Either way the main reason to do this is to avoid this thread jumping from core to core
// and loose its caches in the process.
uint32_t id = std::thread::hardware_concurrency() - 1;
while (true) {
// looks like thread affinity needs to be reset regularly (on Android)
JobSystem::setThreadAffinityById(id);
if (!execute()) {
break;
}
}
// terminate() is a synchronous API
getDriverApi().terminate();
return 0;
}
void FEngine::flushCommandBuffer(CommandBufferQueue& commandQueue) {
getDriver().purge();
commandQueue.flush();
}
const FMaterial* FEngine::getSkyboxMaterial() const noexcept {
FMaterial const* material = mSkyboxMaterial;
if (UTILS_UNLIKELY(material == nullptr)) {
material = FSkybox::createMaterial(*const_cast<FEngine*>(this));
mSkyboxMaterial = material;
}
return material;
}
// -----------------------------------------------------------------------------------------------
// Resource management
// -----------------------------------------------------------------------------------------------
/*
* Object created from a Builder
*/
template <typename T>
inline T* FEngine::create(ResourceList<T>& list, typename T::Builder const& builder) noexcept {
T* p = mHeapAllocator.make<T>(*this, builder);
list.insert(p);
return p;
}
FVertexBuffer* FEngine::createVertexBuffer(const VertexBuffer::Builder& builder) noexcept {
return create(mVertexBuffers, builder);
}
FIndexBuffer* FEngine::createIndexBuffer(const IndexBuffer::Builder& builder) noexcept {
return create(mIndexBuffers, builder);
}
FTexture* FEngine::createTexture(const Texture::Builder& builder) noexcept {
return create(mTextures, builder);
}
FIndirectLight* FEngine::createIndirectLight(const IndirectLight::Builder& builder) noexcept {
return create(mIndirectLights, builder);
}
FMaterial* FEngine::createMaterial(const Material::Builder& builder) noexcept {
return create(mMaterials, builder);
}
FSkybox* FEngine::createSkybox(const Skybox::Builder& builder) noexcept {
return create(mSkyboxes, builder);
}
FColorGrading* FEngine::createColorGrading(const ColorGrading::Builder& builder) noexcept {
return create(mColorGradings, builder);
}
FStream* FEngine::createStream(const Stream::Builder& builder) noexcept {
return create(mStreams, builder);
}
FRenderTarget* FEngine::createRenderTarget(const RenderTarget::Builder& builder) noexcept {
return create(mRenderTargets, builder);
}
/*
* Special cases
*/
FRenderer* FEngine::createRenderer() noexcept {
FRenderer* p = mHeapAllocator.make<FRenderer>(*this);
if (p) {
mRenderers.insert(p);
p->init();
}
return p;
}
FMaterialInstance* FEngine::createMaterialInstance(const FMaterial* material,
const char* name) noexcept {
FMaterialInstance* p = mHeapAllocator.make<FMaterialInstance>(*this, material, name);
if (p) {
auto pos = mMaterialInstances.emplace(material, "MaterialInstance");
pos.first->second.insert(p);
}
return p;
}
/*
* Objects created without a Builder
*/
FScene* FEngine::createScene() noexcept {
FScene* p = mHeapAllocator.make<FScene>(*this);
if (p) {
mScenes.insert(p);
}
return p;
}
FView* FEngine::createView() noexcept {
FView* p = mHeapAllocator.make<FView>(*this);
if (p) {
mViews.insert(p);
}
return p;
}
FFence* FEngine::createFence(FFence::Type type) noexcept {
FFence* p = mHeapAllocator.make<FFence>(*this, type);
if (p) {
mFences.insert(p);
}
return p;
}
FSwapChain* FEngine::createSwapChain(void* nativeWindow, uint64_t flags) noexcept {
if (UTILS_UNLIKELY(flags & backend::SWAP_CHAIN_CONFIG_APPLE_CVPIXELBUFFER)) {
// If this flag is set, then the nativeWindow is a CVPixelBufferRef.
// The call to setupExternalImage is synchronous, and allows the driver to take ownership of
// the buffer on this thread.
// For non-Metal backends, this is a no-op.
getDriverApi().setupExternalImage(nativeWindow);
}
FSwapChain* p = mHeapAllocator.make<FSwapChain>(*this, nativeWindow, flags);
if (p) {
mSwapChains.insert(p);
}
return p;
}
FSwapChain* FEngine::createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept {
FSwapChain* p = mHeapAllocator.make<FSwapChain>(*this, width, height, flags);
if (p) {
mSwapChains.insert(p);
}
return p;
}
/*
* Objects created with a component manager
*/
FCamera* FEngine::createCamera(Entity entity) noexcept {
return mCameraManager.create(entity);
}
FCamera* FEngine::getCameraComponent(Entity entity) noexcept {
auto ci = mCameraManager.getInstance(entity);
return ci ? mCameraManager.getCamera(ci) : nullptr;
}
void FEngine::destroyCameraComponent(utils::Entity entity) noexcept {
mCameraManager.destroy(entity);
}
void FEngine::createRenderable(const RenderableManager::Builder& builder, Entity entity) {
mRenderableManager.create(builder, entity);
auto& tcm = mTransformManager;
// if this entity doesn't have a transform component, add one.
if (!tcm.hasComponent(entity)) {
tcm.create(entity, 0, mat4f());
}
}
void FEngine::createLight(const LightManager::Builder& builder, Entity entity) {
mLightManager.create(builder, entity);
}
// -----------------------------------------------------------------------------------------------
template<typename T, typename L>
void FEngine::cleanupResourceList(ResourceList<T, L>& list) {
if (!list.empty()) {
#ifndef NDEBUG
slog.d << "cleaning up " << list.size()
<< " leaked " << CallStack::typeName<T>().c_str() << io::endl;
#endif
// Move the list (copy-and-clear). We can only modify/access the list from this
// thread, because it's not thread-safe.
auto copy(list.getListAndClear());
for (T* item : copy) {
item->terminate(*this);
mHeapAllocator.destroy(item);
}
}
}
// -----------------------------------------------------------------------------------------------
template<typename T, typename L>
bool FEngine::terminateAndDestroy(const T* ptr, ResourceList<T, L>& list) {
if (ptr == nullptr) return true;
bool success = list.remove(ptr);
if (ASSERT_PRECONDITION_NON_FATAL(success,
"Object %s at %p doesn't exist (double free?)",
CallStack::typeName<T>().c_str(), ptr)) {
const_cast<T*>(ptr)->terminate(*this);
mHeapAllocator.destroy(const_cast<T*>(ptr));
}
return success;
}
// -----------------------------------------------------------------------------------------------
bool FEngine::destroy(const FVertexBuffer* p) {
return terminateAndDestroy(p, mVertexBuffers);
}
bool FEngine::destroy(const FIndexBuffer* p) {
return terminateAndDestroy(p, mIndexBuffers);
}
inline bool FEngine::destroy(const FRenderer* p) {
return terminateAndDestroy(p, mRenderers);
}
inline bool FEngine::destroy(const FScene* p) {
return terminateAndDestroy(p, mScenes);
}
inline bool FEngine::destroy(const FSkybox* p) {
return terminateAndDestroy(p, mSkyboxes);
}
inline bool FEngine::destroy(const FColorGrading* p) {
return terminateAndDestroy(p, mColorGradings);
}
UTILS_NOINLINE
bool FEngine::destroy(const FTexture* p) {
return terminateAndDestroy(p, mTextures);
}
bool FEngine::destroy(const FRenderTarget* p) {
return terminateAndDestroy(p, mRenderTargets);
}
inline bool FEngine::destroy(const FView* p) {
return terminateAndDestroy(p, mViews);
}
inline bool FEngine::destroy(const FIndirectLight* p) {
return terminateAndDestroy(p, mIndirectLights);
}
UTILS_NOINLINE
bool FEngine::destroy(const FFence* p) {
return terminateAndDestroy(p, mFences);
}
bool FEngine::destroy(const FSwapChain* p) {
return terminateAndDestroy(p, mSwapChains);
}
bool FEngine::destroy(const FStream* p) {
return terminateAndDestroy(p, mStreams);
}
bool FEngine::destroy(const FMaterial* ptr) {
if (ptr == nullptr) return true;
auto pos = mMaterialInstances.find(ptr);
if (pos != mMaterialInstances.cend()) {
// ensure we've destroyed all instances before destroying the material
if (!ASSERT_PRECONDITION_NON_FATAL(pos->second.empty(),
"destroying material \"%s\" but %u instances still alive",
ptr->getName().c_str(), (*pos).second.size())) {
return false;
}
}
return terminateAndDestroy(ptr, mMaterials);
}
bool FEngine::destroy(const FMaterialInstance* ptr) {
if (ptr == nullptr) return true;
auto pos = mMaterialInstances.find(ptr->getMaterial());
assert_invariant(pos != mMaterialInstances.cend());
if (pos != mMaterialInstances.cend()) {
return terminateAndDestroy(ptr, pos->second);
}
// if we don't find this instance's material it might be because it's the default instance
// in which case it fine to ignore.
return true;
}
void FEngine::destroy(Entity e) {
mRenderableManager.destroy(e);
mLightManager.destroy(e);
mTransformManager.destroy(e);
mCameraManager.destroy(e);
}
void* FEngine::streamAlloc(size_t size, size_t alignment) noexcept {
// we allow this only for small allocations
if (size > 1024) {
return nullptr;
}
return getDriverApi().allocate(size, alignment);
}
bool FEngine::execute() {
// wait until we get command buffers to be executed (or thread exit requested)
auto buffers = mCommandBufferQueue.waitForCommands();
if (UTILS_UNLIKELY(buffers.empty())) {
return false;
}
// execute all command buffers
for (auto& item : buffers) {
if (UTILS_LIKELY(item.begin)) {
mCommandStream.execute(item.begin);
mCommandBufferQueue.releaseBuffer(item);
}
}
return true;
}
void FEngine::destroy(FEngine* engine) {
if (engine) {
engine->shutdown();
delete engine;
}
}
// ------------------------------------------------------------------------------------------------
// Trampoline calling into private implementation
// ------------------------------------------------------------------------------------------------
Engine* Engine::create(Backend backend, Platform* platform, void* sharedGLContext) {
return FEngine::create(backend, platform, sharedGLContext);
}
void Engine::destroy(Engine* engine) {
FEngine::destroy(upcast(engine));
}
#if UTILS_HAS_THREADING
void Engine::createAsync(Engine::CreateCallback callback, void* user, Backend backend,
Platform* platform, void* sharedGLContext) {
FEngine::createAsync(callback, user, backend, platform, sharedGLContext);
}
Engine* Engine::getEngine(void* token) {
return FEngine::getEngine(token);
}
#endif
void Engine::destroy(Engine** pEngine) {
if (pEngine) {
Engine* engine = *pEngine;
FEngine::destroy(upcast(engine));
*pEngine = nullptr;
}
}
// -----------------------------------------------------------------------------------------------
// Resource management
// -----------------------------------------------------------------------------------------------
const Material* Engine::getDefaultMaterial() const noexcept {
return upcast(this)->getDefaultMaterial();
}
Backend Engine::getBackend() const noexcept {
return upcast(this)->getBackend();
}
Renderer* Engine::createRenderer() noexcept {
return upcast(this)->createRenderer();
}
View* Engine::createView() noexcept {
return upcast(this)->createView();
}
Scene* Engine::createScene() noexcept {
return upcast(this)->createScene();
}
Camera* Engine::createCamera(Entity entity) noexcept {
return upcast(this)->createCamera(entity);
}
Camera* Engine::getCameraComponent(utils::Entity entity) noexcept {
return upcast(this)->getCameraComponent(entity);
}
void Engine::destroyCameraComponent(utils::Entity entity) noexcept {
upcast(this)->destroyCameraComponent(entity);
}
Fence* Engine::createFence() noexcept {
return upcast(this)->createFence(FFence::Type::SOFT);
}
SwapChain* Engine::createSwapChain(void* nativeWindow, uint64_t flags) noexcept {
return upcast(this)->createSwapChain(nativeWindow, flags);
}
SwapChain* Engine::createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept {
return upcast(this)->createSwapChain(width, height, flags);
}
bool Engine::destroy(const VertexBuffer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const IndexBuffer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const IndirectLight* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Material* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const MaterialInstance* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Renderer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const View* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Scene* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Skybox* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const ColorGrading* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Stream* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Texture* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const RenderTarget* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Fence* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const SwapChain* p) {
return upcast(this)->destroy(upcast(p));
}
void Engine::destroy(Entity e) {
upcast(this)->destroy(e);
}
void Engine::flushAndWait() {
upcast(this)->flushAndWait();
}
RenderableManager& Engine::getRenderableManager() noexcept {
return upcast(this)->getRenderableManager();
}
LightManager& Engine::getLightManager() noexcept {
return upcast(this)->getLightManager();
}
TransformManager& Engine::getTransformManager() noexcept {
return upcast(this)->getTransformManager();
}
void* Engine::streamAlloc(size_t size, size_t alignment) noexcept {
return upcast(this)->streamAlloc(size, alignment);
}
// The external-facing execute does a flush, and is meant only for single-threaded environments.
// It also discards the boolean return value, which would otherwise indicate a thread exit.
void Engine::execute() {
ASSERT_PRECONDITION(!UTILS_HAS_THREADING, "Execute is meant for single-threaded platforms.");
upcast(this)->flush();
upcast(this)->execute();
}
utils::JobSystem& Engine::getJobSystem() noexcept {
return upcast(this)->getJobSystem();
}
DebugRegistry& Engine::getDebugRegistry() noexcept {
return upcast(this)->getDebugRegistry();
}
Camera* Engine::createCamera() noexcept {
return createCamera(upcast(this)->getEntityManager().create());
}
void Engine::destroy(const Camera* camera) {
Entity e = camera->getEntity();
destroyCameraComponent(e);
upcast(this)->getEntityManager().destroy(e);
}
} // namespace filament
| 32,407
| 9,819
|
// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_string.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "chrome/browser/android/shortcut_info.h"
#include "chrome/browser/banners/app_banner_settings_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/engagement/site_engagement_service.h"
#include "chrome/browser/prefs/pref_metrics_service.h"
#include "chrome/browser/profiles/profile.h"
#include "components/rappor/public/rappor_utils.h"
#include "components/rappor/rappor_service_impl.h"
#include "content/public/browser/web_contents.h"
#include "jni/LaunchMetrics_jni.h"
#include "third_party/blink/public/common/manifest/web_display_mode.h"
#include "url/gurl.h"
using base::android::JavaParamRef;
namespace metrics {
enum class HomeScreenLaunchType { STANDALONE = 0, SHORTCUT = 1, COUNT = 2 };
static void JNI_LaunchMetrics_RecordLaunch(
JNIEnv* env,
const JavaParamRef<jclass>& caller,
jboolean is_shortcut,
const JavaParamRef<jstring>& jurl,
int source,
int display_mode,
const JavaParamRef<jobject>& jweb_contents) {
// Interpolate the legacy ADD_TO_HOMESCREEN source into standalone/shortcut.
// Unfortunately, we cannot concretely determine whether a standalone add to
// homescreen source means a full PWA (with service worker) or a site that has
// a manifest with display: standalone.
int histogram_source = source;
if (histogram_source == ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_DEPRECATED) {
if (is_shortcut)
histogram_source = ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_SHORTCUT;
else
histogram_source = ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_STANDALONE;
}
GURL url(base::android::ConvertJavaStringToUTF8(env, jurl));
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(jweb_contents);
if (web_contents &&
(histogram_source == ShortcutInfo::SOURCE_APP_BANNER ||
histogram_source == ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_PWA)) {
// What a user has installed on the Home screen can become disconnected from
// what Chrome believes is on the Home screen if the user clears their data.
// Use the launch as a signal that the shortcut still exists.
AppBannerSettingsHelper::RecordBannerEvent(
web_contents, url, url.spec(),
AppBannerSettingsHelper::APP_BANNER_EVENT_DID_ADD_TO_HOMESCREEN,
base::Time::Now());
// Tell the Site Engagement Service about this launch as sites recently
// launched from a shortcut receive a boost to their engagement.
SiteEngagementService* service = SiteEngagementService::Get(
Profile::FromBrowserContext(web_contents->GetBrowserContext()));
service->SetLastShortcutLaunchTime(web_contents, url);
}
std::string rappor_metric_source;
switch (histogram_source) {
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_DEPRECATED:
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_PWA:
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_STANDALONE:
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_SHORTCUT:
rappor_metric_source = "Launch.HomeScreenSource.AddToHomeScreen";
break;
case ShortcutInfo::SOURCE_APP_BANNER:
rappor_metric_source = "Launch.HomeScreenSource.AppBanner";
break;
case ShortcutInfo::SOURCE_BOOKMARK_NAVIGATOR_WIDGET:
rappor_metric_source = "Launch.HomeScreenSource.BookmarkNavigatorWidget";
break;
case ShortcutInfo::SOURCE_BOOKMARK_SHORTCUT_WIDGET:
rappor_metric_source = "Launch.HomeScreenSource.BookmarkShortcutWidget";
break;
case ShortcutInfo::SOURCE_NOTIFICATION:
rappor_metric_source = "Launch.HomeScreenSource.Notification";
break;
case ShortcutInfo::SOURCE_UNKNOWN:
case ShortcutInfo::SOURCE_COUNT:
rappor_metric_source = "Launch.HomeScreenSource.Unknown";
break;
}
UMA_HISTOGRAM_ENUMERATION("Launch.HomeScreenSource",
static_cast<ShortcutInfo::Source>(histogram_source),
ShortcutInfo::SOURCE_COUNT);
if (!is_shortcut) {
UMA_HISTOGRAM_ENUMERATION("Launch.WebAppDisplayMode",
static_cast<blink::WebDisplayMode>(display_mode),
blink::WebDisplayMode::kWebDisplayModeLast + 1);
}
rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
rappor_metric_source, url);
HomeScreenLaunchType action = is_shortcut ? HomeScreenLaunchType::SHORTCUT
: HomeScreenLaunchType::STANDALONE;
std::string rappor_metric_action = is_shortcut
? "Launch.HomeScreen.Shortcut"
: "Launch.HomeScreen.Standalone";
UMA_HISTOGRAM_ENUMERATION("Launch.HomeScreen", action,
HomeScreenLaunchType::COUNT);
rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
rappor_metric_action, url);
}
static void JNI_LaunchMetrics_RecordHomePageLaunchMetrics(
JNIEnv* env,
const JavaParamRef<jclass>& caller,
jboolean show_home_button,
jboolean homepage_is_ntp,
const JavaParamRef<jstring>& jhomepage_url) {
GURL homepage_url(base::android::ConvertJavaStringToUTF8(env, jhomepage_url));
PrefMetricsService::RecordHomePageLaunchMetrics(
show_home_button,
homepage_is_ntp,
homepage_url);
}
}; // namespace metrics
| 5,684
| 1,792
|
/*
* Copyright (C) 2013 Antony Woods <antony@teamwoods.org>
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* Author: Antony Woods <antony@teamwoods.org>
*/
#include "Timer.h"
namespace entityx {
namespace help {
Timer::Timer() {
_start = std::chrono::system_clock::now();
}
Timer::~Timer() {
}
void Timer::restart() {
_start = std::chrono::system_clock::now();
}
double Timer::elapsed() {
return std::chrono::duration<double>(std::chrono::system_clock::now() - _start).count();
}
} // namespace help
} // namespace entityx
| 651
| 224
|
// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <index/coinstatsindex.h>
#include <test/util/setup_common.h>
#include <util/time.h>
#include <validation.h>
#include <boost/test/unit_test.hpp>
#include <chrono>
BOOST_AUTO_TEST_SUITE(coinstatsindex_tests)
BOOST_FIXTURE_TEST_CASE(coinstatsindex_initial_sync, TestChain100Setup)
{
CoinStatsIndex coin_stats_index{1 << 20, true};
CCoinsStats coin_stats{CoinStatsHashType::MUHASH};
const CBlockIndex* block_index;
{
LOCK(cs_main);
block_index = ChainActive().Tip();
}
// CoinStatsIndex should not be found before it is started.
BOOST_CHECK(!coin_stats_index.LookUpStats(block_index, coin_stats));
// BlockUntilSyncedToCurrentChain should return false before CoinStatsIndex
// is started.
BOOST_CHECK(!coin_stats_index.BlockUntilSyncedToCurrentChain());
BOOST_REQUIRE(coin_stats_index.Start(::ChainstateActive()));
// Allow the CoinStatsIndex to catch up with the block index that is syncing
// in a background thread.
const auto timeout = GetTime<std::chrono::seconds>() + 120s;
while (!coin_stats_index.BlockUntilSyncedToCurrentChain()) {
BOOST_REQUIRE(timeout > GetTime<std::chrono::milliseconds>());
UninterruptibleSleep(100ms);
}
// Check that CoinStatsIndex works for genesis block.
const CBlockIndex* genesis_block_index;
{
LOCK(cs_main);
genesis_block_index = ChainActive().Genesis();
}
BOOST_CHECK(coin_stats_index.LookUpStats(genesis_block_index, coin_stats));
// Check that CoinStatsIndex updates with new blocks.
coin_stats_index.LookUpStats(block_index, coin_stats);
const CScript script_pub_key{CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG};
std::vector<CMutableTransaction> noTxns;
CreateAndProcessBlock(noTxns, script_pub_key);
// Let the CoinStatsIndex to catch up again.
BOOST_CHECK(coin_stats_index.BlockUntilSyncedToCurrentChain());
CCoinsStats new_coin_stats{CoinStatsHashType::MUHASH};
const CBlockIndex* new_block_index;
{
LOCK(cs_main);
new_block_index = ChainActive().Tip();
}
coin_stats_index.LookUpStats(new_block_index, new_coin_stats);
BOOST_CHECK(block_index != new_block_index);
// Shutdown sequence (c.f. Shutdown() in init.cpp)
coin_stats_index.Stop();
// Rest of shutdown sequence and destructors happen in ~TestingSetup()
}
BOOST_AUTO_TEST_SUITE_END()
| 2,634
| 912
|
/// See ../../License.txt for license info.
#pragma once
#include <cmath>
#include <vector>
#include "../Core/Vector3.hpp"
namespace HANDYMATH_NS
{
struct AABB3
{
Vector3 Min;
Vector3 Max;
AABB3();
AABB3(Vector3 const & point);
AABB3(std::vector<Vector3> const & points);
AABB3(Vector3 const & min, Vector3 const & max);
bool IsEverything() const;
bool IsNothing() const;
bool IsPoint() const;
Vector3 PointCenter() const;
Vector3 Size() const;
Vector3 HalfSize() const;
float Volume() const;
float SurfaceArea() const;
void AddPoint(Vector3 const & p);
void AddPoints(std::vector<Vector3> const & ps);
void AddAABB(AABB3 const & aabb);
bool Envelopes (AABB3 const & aabb) const;
bool Intersects(AABB3 const & aabb) const;
bool Intersects(Vector3 const & v) const;
static AABB3 Everything();
static AABB3 Nothing();
};
FORCEINLINE AABB3::AABB3() : Min(Vector3::NaN()), Max(Vector3::NaN()) { }
FORCEINLINE AABB3::AABB3(Vector3 const & point) : AABB3() { AddPoint(point); }
FORCEINLINE AABB3::AABB3(std::vector<Vector3> const & points) : AABB3() { AddPoints(points); }
FORCEINLINE AABB3::AABB3(Vector3 const & min, Vector3 const & max) : Min(min), Max(max) { }
FORCEINLINE bool AABB3::IsEverything() const { return Min.IsNegativeInfinity() && Max.IsPositiveInfinity(); }
FORCEINLINE bool AABB3::IsNothing() const { return Min.IsNaN() || Max.IsNaN(); }
FORCEINLINE bool AABB3::IsPoint() const { return Min == Max; }
FORCEINLINE Vector3 AABB3::PointCenter() const { return (Min + Max) * 0.5f; }
FORCEINLINE Vector3 AABB3::Size() const { return (Max - Min); }
FORCEINLINE Vector3 AABB3::HalfSize() const { return (Max - Min) * 0.5f; }
FORCEINLINE float AABB3::Volume() const { return Size().Product(); }
FORCEINLINE float AABB3::SurfaceArea() const { Vector3 sz = Size(); return 2.0f * (sz.X * sz.Y + sz.Y * sz.Z + sz.X * sz.Z); }
FORCEINLINE void AABB3::AddPoint(Vector3 const & point)
{
if (point.HasNaN())
throw std::runtime_error("Cannot add NaN to AABB2.");
if (IsEverything())
return;
if (IsNothing())
{
Min = Max = point;
return;
}
Min = Min.Min(point);
Max = Max.Max(point);
}
FORCEINLINE void AABB3::AddPoints(std::vector<Vector3> const & points)
{
if (IsEverything())
return;
for (auto const & point : points)
AddPoint(point);
}
FORCEINLINE void AABB3::AddAABB(AABB3 const & aabb)
{
if (aabb.IsNothing() || IsEverything())
return;
if (aabb.IsEverything() || IsNothing())
{
*this = aabb;
return;
}
AddPoint(aabb.Min);
AddPoint(aabb.Max);
}
FORCEINLINE bool AABB3::Envelopes(AABB3 const & aabb) const
{
if (IsNothing() || aabb.IsNothing())
return false;
if (IsEverything())
return true;
return Min.X <= aabb.Min.X && Min.Y <= aabb.Min.Y && Min.Z <= aabb.Min.Z &&
Max.X >= aabb.Max.X && Max.Y >= aabb.Max.Y && Max.Z >= aabb.Max.Z;
}
FORCEINLINE bool AABB3::Intersects(AABB3 const & aabb) const
{
if (IsNothing() || aabb.IsNothing())
return false;
if (IsEverything() || aabb.IsEverything())
return true;
return !(Max.X < aabb.Min.X || Min.X > aabb.Max.X ||
Max.Y < aabb.Min.Y || Min.Y > aabb.Max.Y ||
Max.Z < aabb.Min.Z || Min.Z > aabb.Max.Z);
}
FORCEINLINE bool AABB3::Intersects(Vector3 const & v) const
{
return Intersects(AABB3(v));
}
FORCEINLINE /*static*/ AABB3 AABB3::Everything() { return AABB3(Vector3::NegativeInfinity(), Vector3::PositiveInfinity()); }
FORCEINLINE /*static*/ AABB3 AABB3::Nothing() { return AABB3(Vector3::NaN(), Vector3::NaN()); }
}
| 3,644
| 1,464
|
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int i = nums1.size() + nums2.size();
int a = 0, b = 0;
int res1 = 0, res2 = 0;
while (a < nums1.size() && b < nums2.size() && (a + b) <= i/2) {
if (nums1[a] < nums2[b]) {
res2 = res1;
res1 = nums1[a++];
} else {
res2 = res1;
res1 = nums2[b++];
}
}
if (a == nums1.size()) {
while ( (a+b) <= i/2) {
res2 = res1;
res1 = nums2[b++];
}
} else if (b == nums2.size()) {
while ((a + b) <= i/2) {
res2 = res1;
res1 = nums1[a++];
}
}
if (i%2 == 1)
return (double)res1;
else
return (double)(res1 + res2)/2;
}
};
| 923
| 333
|
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// 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 <iostream>
#include <librealsense/rs.hpp>
#include <thread>
#include "Open3D/Open3D.h"
using namespace open3d;
int main(int argc, char **args) {
rs::context ctx;
utility::LogInfo("There are {:d} connected RealSense devices.",
ctx.get_device_count());
if (ctx.get_device_count() == 0) {
return 1;
}
rs::device *dev = ctx.get_device(0);
utility::LogInfo("Using device 0, an {}", dev->get_name());
utility::LogInfo(" Serial number: {}", dev->get_serial());
utility::LogInfo(" Firmware version: {}", dev->get_firmware_version());
dev->set_option(rs::option::color_enable_auto_exposure, 0.0);
dev->set_option(rs::option::color_exposure, 625);
dev->set_option(rs::option::color_gain, 128);
dev->set_option(rs::option::color_enable_auto_white_balance, 0.0);
dev->enable_stream(rs::stream::depth, 640, 480, rs::format::z16, 30);
dev->enable_stream(rs::stream::color, 1920, 1080, rs::format::rgb8, 30);
dev->start();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
dev->set_option(rs::option::color_white_balance, 2100.0);
auto depth_image_ptr = std::make_shared<geometry::Image>();
depth_image_ptr->Prepare(640, 480, 1, 2);
auto color_image_ptr = std::make_shared<geometry::Image>();
color_image_ptr->Prepare(1920, 1080, 3, 1);
utility::FPSTimer timer("Realsense stream");
rs::extrinsics extrinsics =
dev->get_extrinsics(rs::stream::depth, rs::stream::rectified_color);
for (int i = 0; i < 9; i++) {
utility::LogInfo("{:.6f} ", extrinsics.rotation[i]);
}
utility::LogInfo("");
for (int i = 0; i < 3; i++) {
utility::LogInfo("{:.6f} ", extrinsics.translation[i]);
}
utility::LogInfo("");
rs::intrinsics depth_intr = dev->get_stream_intrinsics(rs::stream::depth);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", depth_intr.width,
depth_intr.height, depth_intr.fx, depth_intr.fy,
depth_intr.ppx, depth_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", depth_intr.coeffs[i]);
}
utility::LogInfo("");
rs::intrinsics color_intr = dev->get_stream_intrinsics(rs::stream::color);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", color_intr.width,
color_intr.height, color_intr.fx, color_intr.fy,
color_intr.ppx, color_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", color_intr.coeffs[i]);
}
utility::LogInfo("");
rs::intrinsics rect_intr =
dev->get_stream_intrinsics(rs::stream::rectified_color);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", rect_intr.width,
rect_intr.height, rect_intr.fx, rect_intr.fy,
rect_intr.ppx, rect_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", rect_intr.coeffs[i]);
}
utility::LogInfo("");
visualization::Visualizer depth_vis, color_vis;
if (!depth_vis.CreateVisualizerWindow("Depth", 640, 480, 15, 50) ||
!depth_vis.AddGeometry(depth_image_ptr) ||
!color_vis.CreateVisualizerWindow("Color", 1920, 1080, 675, 50) ||
!color_vis.AddGeometry(color_image_ptr)) {
return 0;
}
while (depth_vis.PollEvents() && color_vis.PollEvents()) {
timer.Signal();
dev->wait_for_frames();
memcpy(depth_image_ptr->data_.data(),
dev->get_frame_data(rs::stream::depth), 640 * 480 * 2);
memcpy(color_image_ptr->data_.data(),
dev->get_frame_data(rs::stream::rectified_color),
1920 * 1080 * 3);
depth_vis.UpdateGeometry();
color_vis.UpdateGeometry();
utility::LogInfo("{:.2f}",
dev->get_option(rs::option::color_white_balance));
/*
rs::option opts[10] = {
rs::option::color_enable_auto_exposure,
rs::option::color_exposure,
rs::option::color_backlight_compensation,
rs::option::color_brightness,
rs::option::color_contrast,
rs::option::color_gain,
rs::option::color_gamma,
rs::option::color_saturation,
rs::option::color_sharpness,
rs::option::color_hue
};
double value[10];
dev->get_options((const rs::option *)opts, 10, (double *)value);
utility::LogInfo("{:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}
{:.2f} {:.2f}
{:.2f}", value[0], value[1], value[2], value[3], value[4], value[5],
value[6], value[7], value[8], value[9]);
*/
}
// DrawGeometryWithAnimationCallback(depth_image_ptr,
// [&](Visualizer &vis) {
// timer.Signal();
// dev->wait_for_frames();
// memcpy(depth_image_ptr->data_.data(),
// dev->get_frame_data(rs::stream::depth), 640 * 480 *
// 2);
// return true;
// }, "Depth", 640, 480);
return 0;
}
| 6,660
| 2,348
|
#include "StdAfx.h"
#include ".\recursivemutex.h"
#include "atlsync.h"
namespace clib
{
recursive_mutex::recursive_mutex() : m_lockCount(0)
{
}
recursive_mutex::~recursive_mutex()
{
}
LONG recursive_mutex::GetLockCount()
{
return m_lockCount;
}
void recursive_mutex::do_lock()
{
::InterlockedIncrement(&m_lockCount);
m_critSec.Lock();
}
void recursive_mutex::do_unlock()
{
m_critSec.Unlock();
::InterlockedDecrement(&m_lockCount);
}
rwrecursive_mutex::rwrecursive_mutex()
{
m_nReaders = 0;
m_nWriters = 0;
}
rwrecursive_mutex::~rwrecursive_mutex()
{
}
void rwrecursive_mutex::do_lockr()
{
for(;;)
{
::InterlockedIncrement(&m_nReaders);
if(m_nWriters == 0)
break;
::InterlockedDecrement(&m_nReaders);
::Sleep(0);
}
}
void rwrecursive_mutex::do_lockw()
{
for(;;)
{
if( ::InterlockedExchange( &m_nWriters, 1 ) == 1 )
::Sleep(0);
else
{
while(m_nReaders != 0)
::Sleep(0);
break;
}
}
}
void rwrecursive_mutex::do_unlockr()
{
//DWORD ThreadId = GetCurrentThreadId();
::InterlockedDecrement(&m_nReaders);
}
void rwrecursive_mutex::do_unlockw()
{
//DWORD ThreadId = GetCurrentThreadId();
::InterlockedDecrement(&m_nWriters);
}
scoped_lock_ref_counted::scoped_lock_ref_counted(recursive_mutex & m)
{
m_lock = new recursive_mutex::scoped_lock(m);
}
scoped_lock_ref_counted::~scoped_lock_ref_counted()
{
delete(m_lock);
}
rwscoped_lock_ref_counted::rwscoped_lock_ref_counted(CRWMutex &m)
{
m_lock = new rwscoped_mutex_lock(m);
}
rwscoped_lock_ref_counted::~rwscoped_lock_ref_counted()
{
delete(m_lock);
}
void CLockableUnknown::Lock(CComPtr<clib::scoped_lock_ref_counted> & lock)
{
lock = new clib::scoped_lock_ref_counted(m_mutex);
}
}
namespace boost
{
scoped_lock_ref_counted::scoped_lock_ref_counted(recursive_mutex & m)
{
m_lock = new recursive_mutex::scoped_lock(m);
}
scoped_lock_ref_counted::~scoped_lock_ref_counted()
{
delete(m_lock);
}
}
| 2,090
| 883
|
// Main test framework
#include <bandit/bandit.h>
// std includes
#include <iostream>
#include <memory>
// Threadily includes
#include <ReadyEvent.h>
#include <Observable.h>
#include <ThreadManager.h>
#include <ThreadQueueItem.h>
#include <ThreadIds.h>
using namespace snowhouse;
using namespace bandit;
namespace threadily
{
namespace test
{
go_bandit([]() {
describe("ObservableVectorUnitTest", []() {
it("Observable_Vector_Int_Insert_1", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(0, 1);
observableVector.insert(1, 2);
observableVector.insert(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Insert_2", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, 2);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(0, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Set", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, 2);
observableVector.set(1, 1);
observableVector.set(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Set_OutOfOrder", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.set(2, 2);
observableVector.set(1, 1);
observableVector.set(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Ptr_Insert_1", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(0, std::make_shared<int>(1));
observableVector.insert(1, std::make_shared<int>(2));
observableVector.insert(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Insert_2", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, std::make_shared<int>(2));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(observableVector.at(0).get(), IsNull());
AssertThat(observableVector.at(1).get(), IsNull());
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Set", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, std::make_shared<int>(2));
observableVector.set(1, std::make_shared<int>(1));
observableVector.set(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Set_OutOfOrder", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.set(2, std::make_shared<int>(2));
observableVector.set(1, std::make_shared<int>(1));
observableVector.set(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Subscription_Insert", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
auto valueAdded = std::make_shared<int>(4);
auto subscribe = observableVector.subscribe([valueAdded](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
AssertThat(valueAdded, Equals(newValue));
AssertThat((size_t)2, Equals(index));
AssertThat(ObservableActionType::Insert, Equals(action));
});
observableVector.insert(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.unsubscribe(subscribe);
});
it("Observable_Vector_Ptr_Subscription_Remove", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
bool isDeleted = false;
auto valueAdded = std::make_shared<int>(4);
auto subscribe = observableVector.subscribe([valueAdded, &isDeleted](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
if (ObservableActionType::Erase == action)
{
AssertThat(valueAdded, Equals(newValue));
AssertThat((size_t)2, Equals(index));
isDeleted = true;
}
});
observableVector.set(0, std::make_shared<int>(0));
observableVector.set(1, std::make_shared<int>(2));
observableVector.set(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.erase(2);
AssertThat((size_t)2, Equals(observableVector.size()));
AssertThat(isDeleted, IsTrue());
observableVector.unsubscribe(subscribe);
});
it("Observable_Vector_Ptr_Subscription_Update", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
bool isUpdated = false;
auto valueAdded = std::make_shared<int>(4);
auto valueUpdated = std::make_shared<int>(6);
auto subscribe = observableVector.subscribe([valueUpdated, &isUpdated](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
if (ObservableActionType::Set == action)
{
AssertThat(valueUpdated, Equals(newValue));
AssertThat((size_t)2, Equals(index));
AssertThat(ObservableActionType::Set, Equals(action));
isUpdated = true;
}
});
observableVector.set(0, std::make_shared<int>(0));
observableVector.set(1, std::make_shared<int>(2));
observableVector.set(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.set(2, valueUpdated);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(isUpdated, IsTrue());
observableVector.unsubscribe(subscribe);
});
});
});
}
}
| 7,386
| 2,786
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/ml.hpp"
#include <iostream>
#include <fstream>
#include <queue>
namespace cv
{
namespace text
{
using namespace std;
using namespace cv::ml;
/* OCR HMM Decoder */
void OCRHMMDecoder::run(Mat& image, string& output_text, vector<Rect>* component_rects,
vector<string>* component_texts, vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
output_text.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
}
void OCRHMMDecoder::run(Mat& image, Mat& mask, string& output_text, vector<Rect>* component_rects,
vector<string>* component_texts, vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( mask.type() == CV_8UC1 );
CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
output_text.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
}
CV_WRAP String OCRHMMDecoder::run(InputArray image, int min_confidence, int component_level)
{
std::string output1;
std::string output2;
vector<string> component_texts;
vector<float> component_confidences;
Mat image_m = image.getMat();
run(image_m, output1, NULL, &component_texts, &component_confidences, component_level);
for(unsigned int i = 0; i < component_texts.size(); i++)
{
//cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
if(component_confidences[i] > min_confidence)
{
output2 += component_texts[i];
}
}
return String(output2);
}
CV_WRAP cv::String OCRHMMDecoder::run(InputArray image, InputArray mask, int min_confidence, int component_level)
{
std::string output1;
std::string output2;
vector<string> component_texts;
vector<float> component_confidences;
Mat image_m = image.getMat();
Mat mask_m = mask.getMat();
run(image_m, mask_m, output1, NULL, &component_texts, &component_confidences, component_level);
for(unsigned int i = 0; i < component_texts.size(); i++)
{
cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
if(component_confidences[i] > min_confidence)
{
output2 += component_texts[i];
}
}
return String(output2);
}
void OCRHMMDecoder::ClassifierCallback::eval( InputArray image, vector<int>& out_class, vector<double>& out_confidence)
{
CV_Assert(( image.getMat().type() == CV_8UC3 ) || ( image.getMat().type() == CV_8UC1 ));
out_class.clear();
out_confidence.clear();
}
bool sort_rect_horiz (Rect a,Rect b);
bool sort_rect_horiz (Rect a,Rect b) { return (a.x<b.x); }
class OCRHMMDecoderImpl : public OCRHMMDecoder
{
public:
//Default constructor
OCRHMMDecoderImpl( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const string& _vocabulary,
InputArray transition_probabilities_table,
InputArray emission_probabilities_table,
decoder_mode _mode)
{
classifier = _classifier;
transition_p = transition_probabilities_table.getMat();
emission_p = emission_probabilities_table.getMat();
vocabulary = _vocabulary;
mode = _mode;
}
~OCRHMMDecoderImpl()
{
}
void run( Mat& image,
string& out_sequence,
vector<Rect>* component_rects,
vector<string>* component_texts,
vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( (image.cols > 0) && (image.rows > 0) );
CV_Assert( component_level == OCR_LEVEL_WORD );
out_sequence.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
// First we split a line into words
vector<Mat> words_mask;
vector<Rect> words_rect;
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat tmp;
image.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.size() < 6)
{
//do not split lines with less than 6 characters
words_mask.push_back(image);
words_rect.push_back(Rect(0,0,image.cols,image.rows));
}
else
{
Mat_<float> vector_w((int)image.cols,1);
reduce(image, vector_w, 0, REDUCE_SUM, -1);
vector<int> spaces;
vector<int> spaces_start;
vector<int> spaces_end;
int space_count=0;
int last_one_idx;
int s_init = 0, s_end=vector_w.cols;
for (int s=0; s<vector_w.cols; s++)
{
if (vector_w.at<float>(0,s) == 0)
s_init = s+1;
else
break;
}
for (int s=vector_w.cols-1; s>=0; s--)
{
if (vector_w.at<float>(0,s) == 0)
s_end = s;
else
break;
}
for (int s=s_init; s<s_end; s++)
{
if (vector_w.at<float>(0,s) == 0)
{
space_count++;
} else {
if (space_count!=0)
{
spaces.push_back(space_count);
spaces_start.push_back(last_one_idx);
spaces_end.push_back(s-1);
}
space_count = 0;
last_one_idx = s;
}
}
Scalar mean_space,std_space;
meanStdDev(Mat(spaces),mean_space,std_space);
int num_word_spaces = 0;
int last_word_space_end = 0;
for (int s=0; s<(int)spaces.size(); s++)
{
if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //this 1.1 is a param?
{
if (num_word_spaces == 0)
{
//cout << " we have a word from 0 to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(0,0,spaces_start.at(s),image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
else
{
//cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
num_word_spaces++;
last_word_space_end = spaces_end.at(s);
}
}
//cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
for (int w=0; w<(int)words_mask.size(); w++)
{
vector< vector<int> > observations;
vector< vector<double> > confidences;
vector<int> obs;
// First find contours and sort by x coordinate of bbox
words_mask[w].copyTo(tmp);
if (tmp.empty())
continue;
contours.clear();
hierarchy.clear();
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Rect> contours_rect;
for (int i=0; i<(int)contours.size(); i++)
{
contours_rect.push_back(boundingRect(contours[i]));
}
sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
// Do character recognition foreach contour
for (int i=0; i<(int)contours.size(); i++)
{
Mat tmp_mask;
words_mask[w](contours_rect.at(i)).copyTo(tmp_mask);
vector<int> out_class;
vector<double> out_conf;
classifier->eval(tmp_mask,out_class,out_conf);
if (!out_class.empty())
obs.push_back(out_class[0]);
observations.push_back(out_class);
confidences.push_back(out_conf);
//cout << " out class = " << vocabulary[out_class[0]] << endl;
}
//This must be extracted from dictionary, or just assumed to be equal for all characters
vector<double> start_p(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
start_p[i] = 1.0/vocabulary.size();
Mat V = Mat::zeros((int)observations.size(),(int)vocabulary.size(),CV_64FC1);
vector<string> path(vocabulary.size());
// Initialize base cases (t == 0)
for (int i=0; i<(int)vocabulary.size(); i++)
{
for (int j=0; j<(int)observations[0].size(); j++)
{
emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
}
V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
path[i] = vocabulary.at(i);
}
// Run Viterbi for t > 0
for (int t=1; t<(int)obs.size(); t++)
{
//Dude this has to be done each time!!
emission_p = Mat::eye(62,62,CV_64FC1);
for (int e=0; e<(int)observations[t].size(); e++)
{
emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
}
vector<string> newpath(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
{
double max_prob = 0;
int best_idx = 0;
for (int j=0; j<(int)vocabulary.size(); j++)
{
double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = j;
}
}
V.at<double>(t,i) = max_prob;
newpath[i] = path[best_idx] + vocabulary.at(i);
}
// Don't need to remember the old paths
path.swap(newpath);
}
double max_prob = 0;
int best_idx = 0;
for (int i=0; i<(int)vocabulary.size(); i++)
{
double prob = V.at<double>((int)obs.size()-1,i);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = i;
}
}
//cout << path[best_idx] << endl;
if (out_sequence.size()>0) out_sequence = out_sequence+" "+path[best_idx];
else out_sequence = path[best_idx];
if (component_rects != NULL)
component_rects->push_back(words_rect[w]);
if (component_texts != NULL)
component_texts->push_back(path[best_idx]);
if (component_confidences != NULL)
component_confidences->push_back((float)max_prob);
}
return;
}
void run( Mat& image,
Mat& mask,
string& out_sequence,
vector<Rect>* component_rects,
vector<string>* component_texts,
vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( mask.type() == CV_8UC1 );
CV_Assert( (image.cols > 0) && (image.rows > 0) );
CV_Assert( (image.cols == mask.cols) && (image.rows == mask.rows) );
CV_Assert( component_level == OCR_LEVEL_WORD );
out_sequence.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
// First we split a line into words
vector<Mat> words_mask;
vector<Rect> words_rect;
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat tmp;
mask.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.size() < 6)
{
//do not split lines with less than 6 characters
words_mask.push_back(mask);
words_rect.push_back(Rect(0,0,mask.cols,mask.rows));
}
else
{
Mat_<float> vector_w((int)mask.cols,1);
reduce(mask, vector_w, 0, REDUCE_SUM, -1);
vector<int> spaces;
vector<int> spaces_start;
vector<int> spaces_end;
int space_count=0;
int last_one_idx;
int s_init = 0, s_end=vector_w.cols;
for (int s=0; s<vector_w.cols; s++)
{
if (vector_w.at<float>(0,s) == 0)
s_init = s+1;
else
break;
}
for (int s=vector_w.cols-1; s>=0; s--)
{
if (vector_w.at<float>(0,s) == 0)
s_end = s;
else
break;
}
for (int s=s_init; s<s_end; s++)
{
if (vector_w.at<float>(0,s) == 0)
{
space_count++;
} else {
if (space_count!=0)
{
spaces.push_back(space_count);
spaces_start.push_back(last_one_idx);
spaces_end.push_back(s-1);
}
space_count = 0;
last_one_idx = s;
}
}
Scalar mean_space,std_space;
meanStdDev(Mat(spaces),mean_space,std_space);
int num_word_spaces = 0;
int last_word_space_end = 0;
for (int s=0; s<(int)spaces.size(); s++)
{
if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //this 1.1 is a param?
{
if (num_word_spaces == 0)
{
//cout << " we have a word from 0 to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(0,0,spaces_start.at(s),mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
else
{
//cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
num_word_spaces++;
last_word_space_end = spaces_end.at(s);
}
}
//cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
for (int w=0; w<(int)words_mask.size(); w++)
{
vector< vector<int> > observations;
vector< vector<double> > confidences;
vector<int> obs;
// First find contours and sort by x coordinate of bbox
words_mask[w].copyTo(tmp);
if (tmp.empty())
continue;
contours.clear();
hierarchy.clear();
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Rect> contours_rect;
for (int i=0; i<(int)contours.size(); i++)
{
contours_rect.push_back(boundingRect(contours[i]));
}
sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
// Do character recognition foreach contour
for (int i=0; i<(int)contours.size(); i++)
{
vector<int> out_class;
vector<double> out_conf;
//take the center of the char rect and translate it to the real origin
Point char_center = Point(contours_rect.at(i).x+contours_rect.at(i).width/2,
contours_rect.at(i).y+contours_rect.at(i).height/2);
char_center.x += words_rect[w].x;
char_center.y += words_rect[w].y;
int win_size = max(contours_rect.at(i).width,contours_rect.at(i).height);
win_size += (int)(win_size*0.6); // add some pixels in the border TODO: is this a parameter for the user space?
Rect char_rect = Rect(char_center.x-win_size/2,char_center.y-win_size/2,win_size,win_size);
char_rect &= Rect(0,0,image.cols,image.rows);
Mat tmp_image;
image(char_rect).copyTo(tmp_image);
classifier->eval(tmp_image,out_class,out_conf);
if (!out_class.empty())
obs.push_back(out_class[0]);
//cout << " out class = " << vocabulary[out_class[0]] << "(" << out_conf[0] << ")" << endl;
observations.push_back(out_class);
confidences.push_back(out_conf);
}
//This must be extracted from dictionary, or just assumed to be equal for all characters
vector<double> start_p(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
start_p[i] = 1.0/vocabulary.size();
Mat V = Mat::zeros((int)observations.size(),(int)vocabulary.size(),CV_64FC1);
vector<string> path(vocabulary.size());
// Initialize base cases (t == 0)
for (int i=0; i<(int)vocabulary.size(); i++)
{
for (int j=0; j<(int)observations[0].size(); j++)
{
emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
}
V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
path[i] = vocabulary.at(i);
}
// Run Viterbi for t > 0
for (int t=1; t<(int)obs.size(); t++)
{
//Dude this has to be done each time!!
emission_p = Mat::eye(62,62,CV_64FC1);
for (int e=0; e<(int)observations[t].size(); e++)
{
emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
}
vector<string> newpath(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
{
double max_prob = 0;
int best_idx = 0;
for (int j=0; j<(int)vocabulary.size(); j++)
{
double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = j;
}
}
V.at<double>(t,i) = max_prob;
newpath[i] = path[best_idx] + vocabulary.at(i);
}
// Don't need to remember the old paths
path.swap(newpath);
}
double max_prob = 0;
int best_idx = 0;
for (int i=0; i<(int)vocabulary.size(); i++)
{
double prob = V.at<double>((int)obs.size()-1,i);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = i;
}
}
//cout << path[best_idx] << endl;
if (out_sequence.size()>0) out_sequence = out_sequence+" "+path[best_idx];
else out_sequence = path[best_idx];
if (component_rects != NULL)
component_rects->push_back(words_rect[w]);
if (component_texts != NULL)
component_texts->push_back(path[best_idx]);
if (component_confidences != NULL)
component_confidences->push_back((float)max_prob);
}
return;
}
};
Ptr<OCRHMMDecoder> OCRHMMDecoder::create( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const string& _vocabulary,
InputArray transition_p,
InputArray emission_p,
decoder_mode _mode)
{
return makePtr<OCRHMMDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, _mode);
}
Ptr<OCRHMMDecoder> OCRHMMDecoder::create( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const String& _vocabulary,
InputArray transition_p,
InputArray emission_p,
int _mode)
{
return makePtr<OCRHMMDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, (decoder_mode)_mode);
}
class CV_EXPORTS OCRHMMClassifierKNN : public OCRHMMDecoder::ClassifierCallback
{
public:
//constructor
OCRHMMClassifierKNN(const std::string& filename);
// Destructor
~OCRHMMClassifierKNN() {}
void eval( InputArray mask, vector<int>& out_class, vector<double>& out_confidence );
private:
Ptr<KNearest> knn;
};
OCRHMMClassifierKNN::OCRHMMClassifierKNN (const string& filename)
{
knn = KNearest::create();
if (ifstream(filename.c_str()))
{
Mat hus, labels;
cv::FileStorage storage(filename.c_str(), cv::FileStorage::READ);
storage["hus"] >> hus;
storage["labels"] >> labels;
storage.release();
knn->train(hus, ROW_SAMPLE, labels);
}
else
CV_Error(Error::StsBadArg, "Default classifier data file not found!");
}
void OCRHMMClassifierKNN::eval( InputArray _mask, vector<int>& out_class, vector<double>& out_confidence )
{
CV_Assert( _mask.getMat().type() == CV_8UC1 );
out_class.clear();
out_confidence.clear();
int image_height = 35;
int image_width = 35;
int num_features = 200;
Mat img = _mask.getMat();
Mat tmp;
img.copyTo(tmp);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.empty())
return;
int idx = 0;
if (contours.size() > 1)
{
// this is to make sure we have the mask with a single contour
// e.g "i" and "j" have two contours, but it may be also a part of a neighbour character
// we take the larger one and clean the outside in order to have a single contour
int max_area = 0;
for (int cc=0; cc<(int)contours.size(); cc++)
{
int area_c = boundingRect(contours[cc]).area();
if ( area_c > max_area)
{
idx = cc;
max_area = area_c;
}
}
// clean-up the outside of the contour
Mat tmp_c = Mat::zeros(tmp.rows, tmp.cols, CV_8UC1);
drawContours(tmp_c, contours, idx, Scalar(255), FILLED);
img = img & tmp_c;
}
Rect bbox = boundingRect(contours[idx]);
//Crop to fit the exact rect of the contour and resize to a fixed-sized matrix of 35 x 35 pixel, while retaining the centroid of the region and aspect ratio.
Mat mask = Mat::zeros(image_height,image_width,CV_8UC1);
img(bbox).copyTo(tmp);
if (tmp.cols>tmp.rows)
{
int height = image_width*tmp.rows/tmp.cols;
if(height == 0) height = 1;
resize(tmp,tmp,Size(image_width,height));
tmp.copyTo(mask(Rect(0,(image_height-height)/2,image_width,height)));
}
else
{
int width = image_height*tmp.cols/tmp.rows;
if(width == 0) width = 1;
resize(tmp,tmp,Size(width,image_height));
tmp.copyTo(mask(Rect((image_width-width)/2,0,width,image_height)));
}
//find contours again (now resized)
mask.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Mat> maps;
for (int i=0; i<8; i++)
{
Mat map = Mat::zeros(image_height,image_width,CV_8UC1);
maps.push_back(map);
}
for (int c=0; c<(int)contours.size(); c++)
{
for (int i=0; i<(int)contours[c].size(); i++)
{
//cout << contours[c][i] << " -- " << contours[c][(i+1)%contours[c].size()] << endl;
double dy = contours[c][i].y - contours[c][(i+1)%contours[c].size()].y;
double dx = contours[c][i].x - contours[c][(i+1)%contours[c].size()].x;
double angle = atan2 (dy,dx) * 180 / 3.14159265;
//cout << " angle = " << angle << endl;
int idx_a = 0;
if ((angle>=157.5)||(angle<=-157.5))
idx_a = 0;
else if ((angle>=-157.5)&&(angle<=-112.5))
idx_a = 1;
else if ((angle>=-112.5)&&(angle<=-67.5))
idx_a = 2;
else if ((angle>=-67.5)&&(angle<=-22.5))
idx_a = 3;
else if ((angle>=-22.5)&&(angle<=22.5))
idx_a = 4;
else if ((angle>=22.5)&&(angle<=67.5))
idx_a = 5;
else if ((angle>=67.5)&&(angle<=112.5))
idx_a = 6;
else if ((angle>=112.5)&&(angle<=157.5))
idx_a = 7;
line(maps[idx_a],contours[c][i],contours[c][(i+1)%contours[c].size()],Scalar(255));
}
}
//On each bitmap a regular 7x7 Gaussian masks are evenly placed
for (int i=0; i<(int)maps.size(); i++)
{
copyMakeBorder(maps[i],maps[i],7,7,7,7,BORDER_CONSTANT,Scalar(0));
GaussianBlur(maps[i], maps[i], Size(7,7), 2, 2);
normalize(maps[i],maps[i],0,255,NORM_MINMAX);
resize(maps[i],maps[i],Size(image_width,image_height));
}
//Generate features for each bitmap
Mat sample = Mat(1,num_features,CV_32FC1);
Mat patch;
for (int i=0; i<(int)maps.size(); i++)
{
for(int y=0; y<image_height; y=y+7)
{
for(int x=0; x<image_width; x=x+7)
{
maps[i](Rect(x,y,7,7)).copyTo(patch);
Scalar mean,std;
meanStdDev(patch,mean,std);
sample.at<float>(0,i*25+((int)x/7)+((int)y/7)*5) = (float)(mean[0]/255);
//cout << " avg " << mean[0] << " in patch " << x << "," << y << " channel " << i << " idx = " << i*25+((int)x/7)+((int)y/7)*5<< endl;
}
}
}
Mat responses,dists,predictions;
knn->findNearest( sample, 11, predictions, responses, dists);
Scalar dist_sum = sum(dists);
Mat class_predictions = Mat::zeros(1,62,CV_64FC1);
vector<vector<int> > equivalency_mat(62);
equivalency_mat[2].push_back(28); // c -> C
equivalency_mat[28].push_back(2); // C -> c
equivalency_mat[8].push_back(34); // i -> I
equivalency_mat[8].push_back(11); // i -> l
equivalency_mat[11].push_back(8); // l -> i
equivalency_mat[11].push_back(34); // l -> I
equivalency_mat[34].push_back(8); // I -> i
equivalency_mat[34].push_back(11); // I -> l
equivalency_mat[9].push_back(35); // j -> J
equivalency_mat[35].push_back(9); // J -> j
equivalency_mat[14].push_back(40); // o -> O
equivalency_mat[14].push_back(52); // o -> 0
equivalency_mat[40].push_back(14); // O -> o
equivalency_mat[40].push_back(52); // O -> 0
equivalency_mat[52].push_back(14); // 0 -> o
equivalency_mat[52].push_back(40); // 0 -> O
equivalency_mat[15].push_back(41); // p -> P
equivalency_mat[41].push_back(15); // P -> p
equivalency_mat[18].push_back(44); // s -> S
equivalency_mat[44].push_back(18); // S -> s
equivalency_mat[20].push_back(46); // u -> U
equivalency_mat[46].push_back(20); // U -> u
equivalency_mat[21].push_back(47); // v -> V
equivalency_mat[47].push_back(21); // V -> v
equivalency_mat[22].push_back(48); // w -> W
equivalency_mat[48].push_back(22); // W -> w
equivalency_mat[23].push_back(49); // x -> X
equivalency_mat[49].push_back(23); // X -> x
equivalency_mat[25].push_back(51); // z -> Z
equivalency_mat[51].push_back(25); // Z -> z
for (int j=0; j<responses.cols; j++)
{
if (responses.at<float>(0,j)<0)
continue;
class_predictions.at<double>(0,(int)responses.at<float>(0,j)) += dists.at<float>(0,j);
for (int e=0; e<(int)equivalency_mat[(int)responses.at<float>(0,j)].size(); e++)
{
class_predictions.at<double>(0,equivalency_mat[(int)responses.at<float>(0,j)][e]) += dists.at<float>(0,j);
dist_sum[0] += dists.at<float>(0,j);
}
}
class_predictions = class_predictions/dist_sum[0];
out_class.push_back((int)predictions.at<float>(0,0));
out_confidence.push_back(class_predictions.at<double>(0,(int)predictions.at<float>(0,0)));
for (int i=0; i<class_predictions.cols; i++)
{
if ((class_predictions.at<double>(0,i) > 0) && (i != out_class[0]))
{
out_class.push_back(i);
out_confidence.push_back(class_predictions.at<double>(0,i));
}
}
}
Ptr<OCRHMMDecoder::ClassifierCallback> loadOCRHMMClassifierNM(const String& filename)
{
return makePtr<OCRHMMClassifierKNN>(std::string(filename));
}
class CV_EXPORTS OCRHMMClassifierCNN : public OCRHMMDecoder::ClassifierCallback
{
public:
//constructor
OCRHMMClassifierCNN(const std::string& filename);
// Destructor
~OCRHMMClassifierCNN() {}
void eval( InputArray image, vector<int>& out_class, vector<double>& out_confidence );
protected:
void normalizeAndZCA(Mat& patches);
double eval_feature(Mat& feature, double* prob_estimates);
private:
int nr_class; // number of classes
int nr_feature; // number of features
Mat feature_min; // scale range
Mat feature_max;
Mat weights; // Logistic Regression weights
Mat kernels; // CNN kernels
Mat M, P; // ZCA Whitening parameters
int window_size; // window size
int quad_size;
int patch_size;
int num_quads; // extract 25 quads (12x12) from each image
int num_tiles; // extract 25 patches (8x8) from each quad
double alpha; // used in non-linear activation function z = max(0, |D*a| - alpha)
};
OCRHMMClassifierCNN::OCRHMMClassifierCNN (const string& filename)
{
if (ifstream(filename.c_str()))
{
FileStorage fs(filename, FileStorage::READ);
// Load kernels bank and withenning params
fs["kernels"] >> kernels;
fs["M"] >> M;
fs["P"] >> P;
// Load Logistic Regression weights
fs["weights"] >> weights;
// Load feature scaling ranges
fs["feature_min"] >> feature_min;
fs["feature_max"] >> feature_max;
fs.release();
}
else
CV_Error(Error::StsBadArg, "Default classifier data file not found!");
// check all matrix dimensions match correctly and no one is empty
CV_Assert( (M.cols > 0) && (M.rows > 0) );
CV_Assert( (P.cols > 0) && (P.rows > 0) );
CV_Assert( (kernels.cols > 0) && (kernels.rows > 0) );
CV_Assert( (weights.cols > 0) && (weights.rows > 0) );
CV_Assert( (feature_min.cols > 0) && (feature_min.rows > 0) );
CV_Assert( (feature_max.cols > 0) && (feature_max.rows > 0) );
nr_feature = weights.rows;
nr_class = weights.cols;
patch_size = (int)sqrt((float)kernels.cols);
// algorithm internal parameters
window_size = 32;
num_quads = 25;
num_tiles = 25;
quad_size = 12;
alpha = 0.5;
}
void OCRHMMClassifierCNN::eval( InputArray _src, vector<int>& out_class, vector<double>& out_confidence )
{
CV_Assert(( _src.getMat().type() == CV_8UC3 ) || ( _src.getMat().type() == CV_8UC1 ));
out_class.clear();
out_confidence.clear();
Mat img = _src.getMat();
if(img.type() == CV_8UC3)
{
cvtColor(img,img,COLOR_RGB2GRAY);
}
// shall we resize the input image or make a copy ?
resize(img,img,Size(window_size,window_size));
Mat quad;
Mat tmp;
int patch_count = 0;
vector< vector<double> > data_pool(9);
int quad_id = 1;
for (int q_x=0; q_x<=window_size-quad_size; q_x=q_x+(int)(quad_size/2-1))
{
for (int q_y=0; q_y<=window_size-quad_size; q_y=q_y+(int)(quad_size/2-1))
{
Rect quad_rect = Rect(q_x,q_y,quad_size,quad_size);
quad = img(quad_rect);
//start sliding window (8x8) in each tile and store the patch as row in data_pool
for (int w_x=0; w_x<=quad_size-patch_size; w_x++)
{
for (int w_y=0; w_y<=quad_size-patch_size; w_y++)
{
quad(Rect(w_x,w_y,patch_size,patch_size)).copyTo(tmp);
tmp = tmp.reshape(0,1);
tmp.convertTo(tmp, CV_64F);
normalizeAndZCA(tmp);
vector<double> patch;
tmp.copyTo(patch);
if ((quad_id == 1)||(quad_id == 2)||(quad_id == 6)||(quad_id == 7))
data_pool[0].insert(data_pool[0].end(),patch.begin(),patch.end());
if ((quad_id == 2)||(quad_id == 7)||(quad_id == 3)||(quad_id == 8)||(quad_id == 4)||(quad_id == 9))
data_pool[1].insert(data_pool[1].end(),patch.begin(),patch.end());
if ((quad_id == 4)||(quad_id == 9)||(quad_id == 5)||(quad_id == 10))
data_pool[2].insert(data_pool[2].end(),patch.begin(),patch.end());
if ((quad_id == 6)||(quad_id == 11)||(quad_id == 16)||(quad_id == 7)||(quad_id == 12)||(quad_id == 17))
data_pool[3].insert(data_pool[3].end(),patch.begin(),patch.end());
if ((quad_id == 7)||(quad_id == 12)||(quad_id == 17)||(quad_id == 8)||(quad_id == 13)||(quad_id == 18)||(quad_id == 9)||(quad_id == 14)||(quad_id == 19))
data_pool[4].insert(data_pool[4].end(),patch.begin(),patch.end());
if ((quad_id == 9)||(quad_id == 14)||(quad_id == 19)||(quad_id == 10)||(quad_id == 15)||(quad_id == 20))
data_pool[5].insert(data_pool[5].end(),patch.begin(),patch.end());
if ((quad_id == 16)||(quad_id == 21)||(quad_id == 17)||(quad_id == 22))
data_pool[6].insert(data_pool[6].end(),patch.begin(),patch.end());
if ((quad_id == 17)||(quad_id == 22)||(quad_id == 18)||(quad_id == 23)||(quad_id == 19)||(quad_id == 24))
data_pool[7].insert(data_pool[7].end(),patch.begin(),patch.end());
if ((quad_id == 19)||(quad_id == 24)||(quad_id == 20)||(quad_id == 25))
data_pool[8].insert(data_pool[8].end(),patch.begin(),patch.end());
patch_count++;
}
}
quad_id++;
}
}
//do dot product of each normalized and whitened patch
//each pool is averaged and this yields a representation of 9xD
Mat feature = Mat::zeros(9,kernels.rows,CV_64FC1);
for (int i=0; i<9; i++)
{
Mat pool = Mat(data_pool[i]);
pool = pool.reshape(0,(int)data_pool[i].size()/kernels.cols);
for (int p=0; p<pool.rows; p++)
{
for (int f=0; f<kernels.rows; f++)
{
feature.row(i).at<double>(0,f) = feature.row(i).at<double>(0,f) + max(0.0,std::abs(pool.row(p).dot(kernels.row(f)))-alpha);
}
}
}
feature = feature.reshape(0,1);
// data must be normalized within the range obtained during training
double lower = -1.0;
double upper = 1.0;
for (int k=0; k<feature.cols; k++)
{
feature.at<double>(0,k) = lower + (upper-lower) *
(feature.at<double>(0,k)-feature_min.at<double>(0,k))/
(feature_max.at<double>(0,k)-feature_min.at<double>(0,k));
}
double *p = new double[nr_class];
double predict_label = eval_feature(feature,p);
//cout << " Prediction: " << vocabulary[predict_label] << " with probability " << p[0] << endl;
if (predict_label < 0)
CV_Error(Error::StsInternal, "OCRHMMClassifierCNN::eval Error: unexpected prediction in eval_feature()");
out_class.push_back((int)predict_label);
out_confidence.push_back(p[(int)predict_label]);
for (int i = 0; i<nr_class; i++)
{
if ( (i != (int)predict_label) && (p[i] != 0.) )
{
out_class.push_back(i);
out_confidence.push_back(p[i]);
}
}
}
// normalize for contrast and apply ZCA whitening to a set of image patches
void OCRHMMClassifierCNN::normalizeAndZCA(Mat& patches)
{
//Normalize for contrast
for (int i=0; i<patches.rows; i++)
{
Scalar row_mean, row_std;
meanStdDev(patches.row(i),row_mean,row_std);
row_std[0] = sqrt(pow(row_std[0],2)*patches.cols/(patches.cols-1)+10);
patches.row(i) = (patches.row(i) - row_mean[0]) / row_std[0];
}
//ZCA whitening
if ((M.dims == 0) || (P.dims == 0))
{
Mat CC;
calcCovarMatrix(patches,CC,M,COVAR_NORMAL|COVAR_ROWS|COVAR_SCALE);
CC = CC * patches.rows / (patches.rows-1);
Mat e_val,e_vec;
eigen(CC.t(),e_val,e_vec);
e_vec = e_vec.t();
sqrt(1./(e_val + 0.1), e_val);
Mat V = Mat::zeros(e_vec.rows, e_vec.cols, CV_64FC1);
Mat D = Mat::eye(e_vec.rows, e_vec.cols, CV_64FC1);
for (int i=0; i<e_vec.cols; i++)
{
e_vec.col(e_vec.cols-i-1).copyTo(V.col(i));
D.col(i) = D.col(i) * e_val.at<double>(0,e_val.rows-i-1);
}
P = V * D * V.t();
}
for (int i=0; i<patches.rows; i++)
patches.row(i) = patches.row(i) - M;
patches = patches * P;
}
double OCRHMMClassifierCNN::eval_feature(Mat& feature, double* prob_estimates)
{
for(int i=0;i<nr_class;i++)
prob_estimates[i] = 0;
for(int idx=0; idx<nr_feature; idx++)
for(int i=0;i<nr_class;i++)
prob_estimates[i] += weights.at<float>(idx,i)*feature.at<double>(0,idx); //TODO use vectorized dot product
int dec_max_idx = 0;
for(int i=1;i<nr_class;i++)
{
if(prob_estimates[i] > prob_estimates[dec_max_idx])
dec_max_idx = i;
}
for(int i=0;i<nr_class;i++)
prob_estimates[i]=1/(1+exp(-prob_estimates[i]));
double sum=0;
for(int i=0; i<nr_class; i++)
sum+=prob_estimates[i];
for(int i=0; i<nr_class; i++)
prob_estimates[i]=prob_estimates[i]/sum;
return dec_max_idx;
}
Ptr<OCRHMMDecoder::ClassifierCallback> loadOCRHMMClassifierCNN(const String& filename)
{
return makePtr<OCRHMMClassifierCNN>(std::string(filename));
}
/** @brief Utility function to create a tailored language model transitions table from a given list of words (lexicon).
@param vocabulary The language vocabulary (chars when ascii english text).
@param lexicon The list of words that are expected to be found in a particular image.
@param transition_probabilities_table Output table with transition probabilities between character pairs. cols == rows == vocabulary.size().
The function calculate frequency statistics of character pairs from the given lexicon and fills
the output transition_probabilities_table with them.
The transition_probabilities_table can be used as input in the OCRHMMDecoder::create() and OCRBeamSearchDecoder::create() methods.
@note
- (C++) An alternative would be to load the default generic language transition table provided in the text module samples folder (created from ispell 42869 english words list) :
<https://github.com/Itseez/opencv_contrib/blob/master/modules/text/samples/OCRHMM_transitions_table.xml>
*/
void createOCRHMMTransitionsTable(string& vocabulary, vector<string>& lexicon, OutputArray _transitions)
{
CV_Assert( vocabulary.size() > 0 );
CV_Assert( lexicon.size() > 0 );
if ( (_transitions.getMat().cols != (int)vocabulary.size()) ||
(_transitions.getMat().rows != (int)vocabulary.size()) ||
(_transitions.getMat().type() != CV_64F) )
{
_transitions.create((int)vocabulary.size(), (int)vocabulary.size(), CV_64F);
}
Mat transitions = _transitions.getMat();
transitions = Scalar(0);
Mat count_pairs = Mat::zeros(1, (int)vocabulary.size(), CV_64F);
for (size_t w=0; w<lexicon.size(); w++)
{
for (size_t i=0,j=1; i<lexicon[w].size()-1; i++,j++)
{
size_t idx_i = vocabulary.find(lexicon[w][i]);
size_t idx_j = vocabulary.find(lexicon[w][j]);
if ((idx_i == string::npos) || (idx_j == string::npos))
{
CV_Error(Error::StsBadArg, "Found a non-vocabulary char in lexicon!");
}
transitions.at<double>((int)idx_i,(int)idx_j) += 1;
count_pairs.at<double>(0,(int)idx_i) += 1;
}
}
for (int i=0; i<transitions.rows; i++)
{
transitions.row(i) = transitions.row(i) / count_pairs.at<double>(0,i); //normalize
}
return;
}
Mat createOCRHMMTransitionsTable(const String& vocabulary, vector<cv::String>& lexicon)
{
std::string voc(vocabulary);
vector<string> lex;
for(vector<cv::String>::iterator l = lexicon.begin(); l != lexicon.end(); l++)
lex.push_back(std::string(*l));
Mat _transitions;
createOCRHMMTransitionsTable(voc, lex, _transitions);
return _transitions;
}
}
}
| 46,677
| 15,681
|
/*
* mafObjectFactoryTest.cpp
* mafCoreTest
*
* Created by Paolo Quadrani on 22/09/09.
* Copyright 2009 SCS-B3C. All rights reserved.
*
* See Licence at: http://tiny.cc/QXJ4D
*
*/
#include <mafTestSuite.h>
#include <mafObjectBase.h>
#include <mafObject.h>
#include <mafSmartPointer.h>
using namespace mafCore;
/**
Class name: mafObjectFactoryTest
This class implements the test suite for mafObjectFactory.
*/
//! <title>
//mafObjectFactory
//! </title>
//! <description>
//mafObjectFactory represent the factory for all the MAF3 objects.
//Objects are instantiated by calling the static method CreateObject and passing as argument the typename of the object to create.
//! </description>
class mafObjectFactoryTest : public QObject {
Q_OBJECT
private Q_SLOTS:
/// Initialize test variables
void initTestCase() {
}
/// Cleanup tes variables memory allocation.
void cleanupTestCase() {
}
/// register new object in factory test case.
void registerObjectTest();
/// create object instance test case.
void instantiateObjectTest();
/// create object instance test case (return the base type).
void instantiateObjectBaseTest();
/// create object instance test case.
void instantiateQObjectTest();
/// create object instance test case (return the base type).
void instantiateQObjectFromStringTest();
/// unregister object test case.
void unregisterObjectTest();
/// smart pointer creation test case.
void instantiateSmartObjectTest();
/// smart pointer creation test case.
void bindObjectToIconTest();
private:
};
void mafObjectFactoryTest::registerObjectTest() {
mafUnregisterObject(mafCore::mafObjectBase);
// Not registered object should not be present in factory.
bool res = mafObjectFactory::instance()->isObjectRegistered("mafCore::mafObjectBase");
QVERIFY(res == false);
// Register mafObjectBase.
//! <snippet>
mafRegisterObject(mafCore::mafObjectBase);
//! </snippet>
// Now mafObjectBase is present into the factory.
//! <snippet>
res = mafObjectFactory::instance()->isObjectRegistered("mafCore::mafObjectBase");
//! </snippet>
QVERIFY(res == true);
// Register qt Object
mafRegisterQtObject(QObject)
res = mafObjectFactory::instance()->isQtObjectRegistered("QObject");
QVERIFY(res == true);
}
void mafObjectFactoryTest::instantiateObjectTest() {
// registered object.
mafObjectBase *obj_base = mafNEW(mafCore::mafObjectBase);
QVERIFY(obj_base != NULL);
mafDEL(obj_base);
}
void mafObjectFactoryTest::instantiateObjectBaseTest() {
mafRegisterObject(mafCore::mafObject);
mafObjectBase *obj = mafNEWFromString("mafCore::mafObject");
QVERIFY(obj != NULL);
QString cn = obj->metaObject()->className();
QVERIFY(cn == "mafCore::mafObject");
mafDEL(obj);
}
void mafObjectFactoryTest::instantiateQObjectTest() {
mafRegisterQtObject(QObject)
QObject *obj = mafNEWQt(QObject);
QVERIFY(obj != NULL);
delete obj;
}
void mafObjectFactoryTest::instantiateQObjectFromStringTest() {
mafRegisterQtObject(QObject);
QObject *obj = mafNEWQtFromString("QObject");
QVERIFY(obj != NULL);
QString cn = obj->metaObject()->className();
QVERIFY(cn == "QObject");
delete obj;
}
void mafObjectFactoryTest::unregisterObjectTest() {
mafUnregisterObject(mafCore::mafObjectBase);
bool res = mafObjectFactory::instance()->isObjectRegistered("mafCore::mafObjectBase");
QVERIFY(res == false);
}
void mafObjectFactoryTest::instantiateSmartObjectTest() {
// Register again mafObjectBase (previous test case unregistered it).
mafRegisterObject(mafCore::mafObjectBase);
mafSmartPointer<mafObjectBase> obj = mafCreateSmartObject(mafCore::mafObjectBase);
QVERIFY(obj.isNull() == false);
}
void mafObjectFactoryTest::bindObjectToIconTest() {
// Bind an object type with a file name
QString objectType = "mafTestType";
QString testFileName = "testFileName";
mafBindObjectToIcon(objectType, testFileName);
// Verify if the bind has worked, getting the file name form object type
QString returnFileName = mafIconFromObjectType(objectType);
QVERIFY(testFileName.compare(returnFileName) == 0);
}
MAF_REGISTER_TEST(mafObjectFactoryTest);
#include "mafObjectFactoryTest.moc"
| 4,376
| 1,386
|
/* Copyright 2018 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.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/side_effect_util.h"
#include "absl/strings/numbers.h"
#include "tensorflow/core/graph/algorithm.h"
namespace tensorflow {
const char kXlaTokenInputNodesAttrName[] = "_xla_token_input_nodes";
const char kXlaTokenArgNodeName[] = "_xla_token_arg_node";
const char kXlaHasHostTransferAttrName[] = "_xla_has_host_transfer";
const char kXlaReplicaIdAttrName[] = "_xla_replica_id";
const char kXlaIsPlaceholderForTailOcAttrName[] =
"_xla_is_placeholder_for_tail_oc";
const char kXlaOriginalOutsideCompilationNodeName[] =
"_xla_original_oc_node_name";
const char kXlaHostTransferRendezvousNameAttr[] =
"_xla_host_transfer_rendezvous";
const char kXlaHostTransferOriginalTypeAttr[] =
"_xla_host_transfer_original_type";
const char kXlaHostTransferIsLowerBitsAttr[] =
"_xla_host_transfer_is_lower_bits";
Status SetDeviceOrdinalAttributeForNode(Node* node, int device_ordinal) {
if (!HasNodeAttr(node->def(), kXlaHasHostTransferAttrName)) {
return errors::InvalidArgument("Node ", node->DebugString(),
" does not have attribute ",
kXlaHasHostTransferAttrName);
}
if (node->type_string() == "_XlaRecvAtHost" ||
node->type_string() == "_XlaSendFromHost") {
node->ClearAttr("device_ordinal");
node->AddAttr("device_ordinal", device_ordinal);
} else if (node->IsIfNode()) {
AttrValue device_ordinal_value;
device_ordinal_value.set_i(device_ordinal);
for (const string& attr_name :
std::vector<string>{"then_branch", "else_branch"}) {
NameAttrList branch_func;
TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func));
(*branch_func.mutable_attr())["_device_ordinal"] = device_ordinal_value;
node->ClearAttr(attr_name);
node->AddAttr(attr_name, branch_func);
}
} else if (node->IsWhileNode()) {
AttrValue device_ordinal_value;
device_ordinal_value.set_i(device_ordinal);
for (const string& attr_name : std::vector<string>{"cond", "body"}) {
NameAttrList branch_func;
TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func));
(*branch_func.mutable_attr())["_device_ordinal"] = device_ordinal_value;
node->ClearAttr(attr_name);
node->AddAttr(attr_name, branch_func);
}
} else if (HasNodeAttr(node->def(), "_device_ordinal")) {
// Function call node containing outside compilation.
node->ClearAttr("_device_ordinal");
node->AddAttr("_device_ordinal", device_ordinal);
} else {
return errors::Internal("Unknown node type to set 'device_ordinal': ",
node->DebugString());
}
return Status::OK();
}
std::set<std::string> CalculateTokenInputsForOutputToken(const Graph& g) {
std::set<std::string> results;
Node* first_side_effecting_node_on_path = nullptr;
ReverseDFS(g,
[&](Node* n) {
std::vector<string> token_input_nodes;
if (!GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName,
&token_input_nodes)
.ok() ||
token_input_nodes.empty()) {
return;
}
if (first_side_effecting_node_on_path != nullptr) {
return;
}
first_side_effecting_node_on_path = n;
string original_node_name;
TF_CHECK_OK(GetNodeAttr(n->def(),
kXlaOriginalOutsideCompilationNodeName,
&original_node_name));
results.insert(original_node_name);
},
[&](Node* n) {
if (first_side_effecting_node_on_path == n) {
first_side_effecting_node_on_path = nullptr;
}
},
NodeComparatorName());
return results;
}
bool HasSideEffectingNodes(const Graph& g) {
for (Node* n : g.nodes()) {
std::vector<string> token_input_nodes;
if (GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName, &token_input_nodes)
.ok() &&
!token_input_nodes.empty()) {
return true;
}
}
return false;
}
Status ParseHostComputeCoreList(absl::Span<const string> list_from_attr,
std::map<string, int>* host_compute_core) {
for (const auto& hc_core : list_from_attr) {
std::vector<string> parts = str_util::Split(hc_core, ":");
if (parts.size() != 2) {
return errors::InvalidArgument(
"Malformed host_compute_core entry ", hc_core,
" should be <cluster_name>:<core_number>.");
}
int core;
if (!absl::numbers_internal::safe_strto32_base(parts[1], &core, 10)) {
return errors::InvalidArgument("Malformed host_compute_core entry ",
hc_core,
" part after ':' should be an integer.");
}
if (host_compute_core->find(parts[0]) != host_compute_core->end()) {
return errors::InvalidArgument(
"Duplicate host_compute_core entry for cluster ", parts[0]);
}
(*host_compute_core)[parts[0]] = core;
}
return Status::OK();
}
} // namespace tensorflow
| 5,943
| 1,836
|
/*
* Copyright (c) 2015, 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 <glog/logging.h>
#include <gtest/gtest.h>
#include <memory>
#include <proxygen/lib/http/codec/compress/HPACKHeader.h>
#include <sstream>
using namespace proxygen;
using namespace std;
using namespace testing;
class HPACKHeaderTests : public testing::Test {
};
TEST_F(HPACKHeaderTests, size) {
HPACKHeader h(":path", "/");
EXPECT_EQ(h.bytes(), 32 + 5 + 1);
}
TEST_F(HPACKHeaderTests, operators) {
HPACKHeader h0(":path", "/");
HPACKHeader h1(":path", "/");
HPACKHeader h2(":path", "/index.php");
HPACKHeader h3("x-fb-debug", "test");
// ==
EXPECT_TRUE(h0 == h1);
EXPECT_FALSE(h1 == h2);
// <
EXPECT_FALSE(h1 < h1);
EXPECT_TRUE(h1 < h2);
EXPECT_TRUE(h1 < h3);
// >
EXPECT_FALSE(h2 > h2);
EXPECT_TRUE(h3 > h2);
EXPECT_TRUE(h2 > h1);
stringstream out;
out << h1;
EXPECT_EQ(out.str(), ":path: /");
}
TEST_F(HPACKHeaderTests, has_value) {
HPACKHeader h1(":path", "");
HPACKHeader h2(":path", "/");
EXPECT_FALSE(h1.hasValue());
EXPECT_TRUE(h2.hasValue());
}
TEST_F(HPACKHeaderTests, is_indexable) {
HPACKHeader path(":path", "index.php?q=42");
EXPECT_FALSE(path.isIndexable());
HPACKHeader cdn(":path", "/hprofile-ak-prn1/49496_6024432_1026115112_n.jpg");
EXPECT_FALSE(cdn.isIndexable());
HPACKHeader clen("content-length", "512");
EXPECT_FALSE(clen.isIndexable());
}
| 1,645
| 698
|
// GridCell.cpp : implementation file
//
// MFC Grid Control - Main grid cell class
//
// Provides the implementation for the "default" cell type of the
// grid control. Adds in cell editing.
//
// Written by Chris Maunder <cmaunder@mail.com>
// Copyright (c) 1998-2001. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.20+
//
// History:
// Eric Woodruff - 20 Feb 2000 - Added PrintCell() plus other minor changes
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// <kenbertelson@hotmail.com>
// C Maunder - 17 Jun 2000 - Font handling optimsed, Added CGridDefaultCell
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCell.h"
#include "InPlaceEdit.h"
#include "GridCtrl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGridCell, CGridCellBase)
IMPLEMENT_DYNCREATE(CGridDefaultCell, CGridCell)
/////////////////////////////////////////////////////////////////////////////
// GridCell
CGridCell::CGridCell()
{
m_plfFont = NULL;
Reset();
}
CGridCell::~CGridCell()
{
delete m_plfFont;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Attributes
void CGridCell::operator=(const CGridCell& cell)
{
CGridCellBase::operator=( cell);
}
void CGridCell::Reset()
{
CGridCellBase::Reset();
m_strText.Empty();
m_nImage = -1;
m_pGrid = NULL;
m_bEditing = FALSE;
m_pEditWnd = NULL;
m_nFormat = (DWORD)-1; // Use default from CGridDefaultCell
m_crBkClr = CLR_DEFAULT; // Background colour (or CLR_DEFAULT)
m_crFgClr = CLR_DEFAULT; // Forground colour (or CLR_DEFAULT)
m_nMargin = (UINT)-1; // Use default from CGridDefaultCell
delete m_plfFont;
m_plfFont = NULL; // Cell font
}
void CGridCell::SetFont(const LOGFONT* plf)
{
if (plf == NULL)
{
delete m_plfFont;
m_plfFont = NULL;
}
else
{
if (!m_plfFont)
m_plfFont = new LOGFONT;
if (m_plfFont)
memcpy(m_plfFont, plf, sizeof(LOGFONT));
}
}
LOGFONT* CGridCell::GetFont() const
{
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFont();
}
return m_plfFont;
}
CFont* CGridCell::GetFontObject() const
{
// If the default font is specified, use the default cell implementation
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFontObject();
}
else
{
static CFont Font;
Font.DeleteObject();
Font.CreateFontIndirect(m_plfFont);
return &Font;
}
}
DWORD CGridCell::GetFormat() const
{
if (m_nFormat == (DWORD)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetFormat();
}
return m_nFormat;
}
UINT CGridCell::GetMargin() const
{
if (m_nMargin == (UINT)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetMargin();
}
return m_nMargin;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Operations
BOOL CGridCell::Edit(int nRow, int nCol, CRect rect, CPoint /* point */, UINT nID, UINT nChar)
{
if ( m_bEditing )
{
if (m_pEditWnd)
m_pEditWnd->SendMessage ( WM_CHAR, nChar );
}
else
{
DWORD dwStyle = ES_LEFT;
if (GetFormat() & DT_RIGHT)
dwStyle = ES_RIGHT;
else if (GetFormat() & DT_CENTER)
dwStyle = ES_CENTER;
m_bEditing = TRUE;
// InPlaceEdit auto-deletes itself
CGridCtrl* pGrid = GetGrid();
m_pEditWnd = new CInPlaceEdit(pGrid, rect, dwStyle, nID, nRow, nCol, GetText(), nChar);
}
return TRUE;
}
void CGridCell::EndEdit()
{
if (m_pEditWnd)
((CInPlaceEdit*)m_pEditWnd)->EndEdit();
}
void CGridCell::OnEndEdit()
{
m_bEditing = FALSE;
m_pEditWnd = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CGridDefaultCell
CGridDefaultCell::CGridDefaultCell()
{
#ifdef _WIN32_WCE
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX;
#else
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX | DT_END_ELLIPSIS;
#endif
m_crFgClr = CLR_DEFAULT;
m_crBkClr = CLR_DEFAULT;
m_Size = CSize(30,10);
m_dwStyle = 0;
#ifdef _WIN32_WCE
LOGFONT lf;
GetObject(GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lf);
SetFont(&lf);
#else // not CE
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(NONCLIENTMETRICS);
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
SetFont(&(ncm.lfMessageFont));
#endif
}
CGridDefaultCell::~CGridDefaultCell()
{
m_Font.DeleteObject();
}
void CGridDefaultCell::SetFont(const LOGFONT* plf)
{
ASSERT(plf);
if (!plf) return;
m_Font.DeleteObject();
m_Font.CreateFontIndirect(plf);
CGridCell::SetFont(plf);
// Get the font size and hence the default cell size
CDC* pDC = CDC::FromHandle(::GetDC(NULL));
if (pDC)
{
CFont* pOldFont = pDC->SelectObject(&m_Font);
SetMargin(pDC->GetTextExtent(_T(" "), 1).cx);
m_Size = pDC->GetTextExtent(_T(" XXXXXXXXXXXX "), 14);
m_Size.cy = (m_Size.cy * 3) / 2;
pDC->SelectObject(pOldFont);
ReleaseDC(NULL, pDC->GetSafeHdc());
}
else
{
SetMargin(3);
m_Size = CSize(40,16);
}
}
LOGFONT* CGridDefaultCell::GetFont() const
{
ASSERT(m_plfFont); // This is the default - it CAN'T be NULL!
return m_plfFont;
}
CFont* CGridDefaultCell::GetFontObject() const
{
ASSERT(m_Font.GetSafeHandle());
return (CFont*) &m_Font;
}
| 6,989
| 2,546
|
class Solution {
public:
string removeKdigits(string num, int k) {
string ans = "";
for (char i: num)
{
while (ans.length() && ans.back() > i && k)
{
ans.pop_back();
k--;
}
if (ans.length() || i != '0')
ans.push_back(i);
}
while (ans.length() && k--)
ans.pop_back();
return ans.empty() ? "0" : ans;
}
};
| 472
| 148
|
#include "MySimple3D.h"
#include <QPaintEvent>
#include <QResizeEvent>
#include <QPainter>
#include <QPainterPath>
#include <QtMath>
#include <algorithm>
#include <QTimer>
#include <QtConcurrent>
#include <QDebug>
MySimple3D::MySimple3D(QWidget *parent)
: QWidget(parent)
{
initItems();
//异步处理结束,获取结果并刷新窗口
connect(&watcher,&QFutureWatcher<QImage>::finished,[this](){
image=watcher.result();
update();
});
fpsTime=QTime::currentTime();
fpsTime.start();
//定时旋转风车
QTimer *timer=new QTimer(this);
connect(timer,&QTimer::timeout,[=]{
animationStep+=2.0;
drawImage(width(),height());
});
timer->start(50);
}
MySimple3D::~MySimple3D()
{
if(!watcher.isFinished())
watcher.waitForFinished();
}
void MySimple3D::paintEvent(QPaintEvent *event)
{
event->accept();
QPainter painter(this);
painter.fillRect(this->rect(),Qt::black);
if(image.size().isValid())
painter.drawImage(0,0,image);
//fps统计
if(fpsTime.elapsed()>1000){
fpsTime.restart();
fpsCounter=fpsTemp;
fpsTemp=0;
}else{
fpsTemp++;
}
painter.setPen(QPen(Qt::white));
painter.drawText(10,30,"FPS:"+QString::number(fpsCounter));
painter.drawText(10,50,"Drag Moving ... ...");
}
void MySimple3D::mousePressEvent(QMouseEvent *event)
{
mousePressed=true;
mousePos=event->pos();
QWidget::mousePressEvent(event);
}
void MySimple3D::mouseMoveEvent(QMouseEvent *event)
{
if(mousePressed){
const QPoint posOffset=event->pos()-mousePos;
mousePos=event->pos();
//旋转矩阵 x和y分量
xRotate+=-posOffset.y();
yRotate+=-posOffset.x();
//update();
drawImage(width(),height());
}
QWidget::mouseMoveEvent(event);
}
void MySimple3D::mouseReleaseEvent(QMouseEvent *event)
{
mousePressed=false;
QWidget::mouseReleaseEvent(event);
}
void MySimple3D::resizeEvent(QResizeEvent *event)
{
if(event->size().isValid()){
const int width=event->size().width();
const int height=event->size().height();
drawImage(width,height);
}
QWidget::resizeEvent(event);
}
void MySimple3D::initItems()
{
//模板的嵌套时自动格式化太难看了
//四个扇叶
My3DMeta* sub_fan1=new My3DMeta{{
QVector3D(0,0,0),QVector3D(-250,250,0),QVector3D(-300,200,10),QVector3D(-100,0,10)},
QColor(110,250,250,200)};
My3DMeta* sub_fan2=new My3DMeta{{
QVector3D(0,0,0),QVector3D(-250,-250,0),QVector3D(-200,-300,10),QVector3D(0,-100,10)},
QColor(130,250,250,200)};
My3DMeta* sub_fan3=new My3DMeta{{
QVector3D(0,0,0),QVector3D(250,-250,0),QVector3D(300,-200,10),QVector3D(100,0,10)},
QColor(110,250,250,200)};
My3DMeta* sub_fan4=new My3DMeta{{
QVector3D(0,0,0),QVector3D(250,250,0),QVector3D(200,300,10),QVector3D(0,100,10)},
QColor(130,250,250,200)};
auto sub_fanmetas=QList<QSharedPointer<My3DMeta>>{QSharedPointer<My3DMeta>(sub_fan1),
QSharedPointer<My3DMeta>(sub_fan2),
QSharedPointer<My3DMeta>(sub_fan3),
QSharedPointer<My3DMeta>(sub_fan4)};
auto sub_fansubs=QList<QSharedPointer<My3DItem>>{};
My3DItem *sub_fanitem=new My3DItem{
QVector3D(0,400,-150),
QVector3D(0,0,0),
sub_fanmetas,
sub_fansubs,
QVector3D(0,0,-1)}; //给z加了动画因子
//风车主干,共9个面,顶部尖塔4+主干4+底面
My3DMeta* sub_main1=new My3DMeta{{
QVector3D(100,400,100),QVector3D(-100,400,100),QVector3D(0,500,0)},
QColor(250,0,0)};
My3DMeta* sub_main2=new My3DMeta{{
QVector3D(-100,400,100),QVector3D(-100,400,-100),QVector3D(0,500,0)},
QColor(0,250,0)};
My3DMeta* sub_main3=new My3DMeta{{
QVector3D(-100,400,-100),QVector3D(100,400,-100),QVector3D(0,500,0)},
QColor(0,0,250)};
My3DMeta* sub_main4=new My3DMeta{{
QVector3D(100,400,-100),QVector3D(100,400,100),QVector3D(0,500,0)},
QColor(250,250,0)};
My3DMeta* sub_main5=new My3DMeta{{
QVector3D(100,400,100),QVector3D(-100,400,100),QVector3D(-120,0,120),QVector3D(120,0,120)},
QColor(205,150,100)};
My3DMeta* sub_main6=new My3DMeta{{
QVector3D(-100,400,100),QVector3D(-100,400,-100),QVector3D(-120,0,-120),QVector3D(-120,0,120)},
QColor(220,150,100)};
My3DMeta* sub_main7=new My3DMeta{{
QVector3D(-100,400,-100),QVector3D(100,400,-100),QVector3D(120,0,-120),QVector3D(-120,0,-120)},
QColor(235,150,100)};
My3DMeta* sub_main8=new My3DMeta{{
QVector3D(100,400,-100),QVector3D(100,400,100),QVector3D(120,0,120),QVector3D(120,0,-120)},
QColor(250,150,100)};
My3DMeta* sub_main9=new My3DMeta{{
QVector3D(-120,0,120),QVector3D(-120,0,-120),QVector3D(120,0,-120),QVector3D(120,0,120)},
QColor(200,150,0)};
auto sub_mainmetas=QList<QSharedPointer<My3DMeta>>{QSharedPointer<My3DMeta>(sub_main1),
QSharedPointer<My3DMeta>(sub_main2),
QSharedPointer<My3DMeta>(sub_main3),
QSharedPointer<My3DMeta>(sub_main4),
QSharedPointer<My3DMeta>(sub_main5),
QSharedPointer<My3DMeta>(sub_main6),
QSharedPointer<My3DMeta>(sub_main7),
QSharedPointer<My3DMeta>(sub_main8),
QSharedPointer<My3DMeta>(sub_main9)};
auto sub_mainsubs=QList<QSharedPointer<My3DItem>>{QSharedPointer<My3DItem>(sub_fanitem)};
My3DItem *sub_mainitem=new My3DItem{
QVector3D(0,0,0),
QVector3D(0,0,0),
sub_mainmetas,
sub_mainsubs};
//根节点,一个平面,(平面用半透明是为了穿模时看起来没那么别扭)
My3DMeta* root_meta=new My3DMeta{{
QVector3D(-200,0,200),QVector3D(200,0,200),
QVector3D(200,0,-200),QVector3D(-200,0,-200)},
QColor(255,255,255,100)};
auto root_metas=QList<QSharedPointer<My3DMeta>>{QSharedPointer<My3DMeta>(root_meta)};
auto root_subs=QList<QSharedPointer<My3DItem>>{QSharedPointer<My3DItem>(sub_mainitem)};
rootItem=My3DItem{
QVector3D(0,-300,0),
QVector3D(0,0,0),
root_metas,
root_subs,
QVector3D(0,0.1f,0)}; //给y加了动画因子
}
void MySimple3D::drawImage(int width, int height)
{
if(width>10&&height>10&&watcher.isFinished()){
QVector3D rotate=QVector3D(xRotate,yRotate,0);
int step=animationStep;
//多线程绘制到image上,绘制完后返回image并绘制到窗口上
QFuture<QImage> futures=QtConcurrent::run([this,width,height,rotate,step](){
QImage img(width,height,QImage::Format_ARGB32);
img.fill(Qt::transparent);
QPainter painter(&img);
if(!painter.isActive())
return img;
painter.fillRect(img.rect(),Qt::black);
//painter.save();
//坐标原点移动到中心
painter.translate(width/2,height/2);
//计算所有的图元顶点路径
QList<QSharedPointer<My3DMeta>> surface_metas=rootItem.calculateSurfaceMetas(QVector3D(0,0,0),rotate,step);
//根据z轴排序
std::sort(surface_metas.begin(),surface_metas.end(),
[](const QSharedPointer<My3DMeta> &left,const QSharedPointer<My3DMeta> &right){
return left->z<right->z;
});
//根据z值从远处开始绘制图元路径
for(QSharedPointer<My3DMeta> meta:surface_metas)
{
painter.fillPath(meta->path,meta->color);
}
//painter.restore();
return img;
});
watcher.setFuture(futures);
}
}
| 8,094
| 3,410
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: IGamePause
#include "GlobalNamespace/IGamePause.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: TutorialSongController
class TutorialSongController;
// Forward declaring type: SaberManager
class SaberManager;
// Forward declaring type: AudioListenerController
class AudioListenerController;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: TutorialPause
class TutorialPause;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::TutorialPause);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::TutorialPause*, "", "TutorialPause");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x41
#pragma pack(push, 1)
// Autogenerated type: TutorialPause
// [TokenAttribute] Offset: FFFFFFFF
class TutorialPause : public ::Il2CppObject/*, public ::GlobalNamespace::IGamePause*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// [InjectAttribute] Offset: 0x12565E0
// private readonly TutorialSongController _tutorialSongController
// Size: 0x8
// Offset: 0x10
::GlobalNamespace::TutorialSongController* tutorialSongController;
// Field size check
static_assert(sizeof(::GlobalNamespace::TutorialSongController*) == 0x8);
// [InjectAttribute] Offset: 0x12565F0
// private readonly SaberManager _saberManager
// Size: 0x8
// Offset: 0x18
::GlobalNamespace::SaberManager* saberManager;
// Field size check
static_assert(sizeof(::GlobalNamespace::SaberManager*) == 0x8);
// [InjectAttribute] Offset: 0x1256600
// private readonly AudioListenerController _audioListenerController
// Size: 0x8
// Offset: 0x20
::GlobalNamespace::AudioListenerController* audioListenerController;
// Field size check
static_assert(sizeof(::GlobalNamespace::AudioListenerController*) == 0x8);
// private System.Action didPauseEvent
// Size: 0x8
// Offset: 0x28
::System::Action* didPauseEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Action willResumeEvent
// Size: 0x8
// Offset: 0x30
::System::Action* willResumeEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Action didResumeEvent
// Size: 0x8
// Offset: 0x38
::System::Action* didResumeEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Boolean _pause
// Size: 0x1
// Offset: 0x40
bool pause;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Creating interface conversion operator: operator ::GlobalNamespace::IGamePause
operator ::GlobalNamespace::IGamePause() noexcept {
return *reinterpret_cast<::GlobalNamespace::IGamePause*>(this);
}
// Get instance field reference: private readonly TutorialSongController _tutorialSongController
::GlobalNamespace::TutorialSongController*& dyn__tutorialSongController();
// Get instance field reference: private readonly SaberManager _saberManager
::GlobalNamespace::SaberManager*& dyn__saberManager();
// Get instance field reference: private readonly AudioListenerController _audioListenerController
::GlobalNamespace::AudioListenerController*& dyn__audioListenerController();
// Get instance field reference: private System.Action didPauseEvent
::System::Action*& dyn_didPauseEvent();
// Get instance field reference: private System.Action willResumeEvent
::System::Action*& dyn_willResumeEvent();
// Get instance field reference: private System.Action didResumeEvent
::System::Action*& dyn_didResumeEvent();
// Get instance field reference: private System.Boolean _pause
bool& dyn__pause();
// public System.Boolean get_isPaused()
// Offset: 0x2AB2338
bool get_isPaused();
// public System.Void add_didPauseEvent(System.Action value)
// Offset: 0x2AB2340
void add_didPauseEvent(::System::Action* value);
// public System.Void remove_didPauseEvent(System.Action value)
// Offset: 0x2AB23E4
void remove_didPauseEvent(::System::Action* value);
// public System.Void add_willResumeEvent(System.Action value)
// Offset: 0x2AB2488
void add_willResumeEvent(::System::Action* value);
// public System.Void remove_willResumeEvent(System.Action value)
// Offset: 0x2AB252C
void remove_willResumeEvent(::System::Action* value);
// public System.Void add_didResumeEvent(System.Action value)
// Offset: 0x2AB25D0
void add_didResumeEvent(::System::Action* value);
// public System.Void remove_didResumeEvent(System.Action value)
// Offset: 0x2AB2674
void remove_didResumeEvent(::System::Action* value);
// public System.Void Pause()
// Offset: 0x2AB2718
void Pause();
// public System.Void WillResume()
// Offset: 0x2AB2798
void WillResume();
// public System.Void Resume()
// Offset: 0x2AB27AC
void Resume();
// public System.Void .ctor()
// Offset: 0x2AB2828
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TutorialPause* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::TutorialPause::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TutorialPause*, creationType>()));
}
}; // TutorialPause
#pragma pack(pop)
static check_size<sizeof(TutorialPause), 64 + sizeof(bool)> __GlobalNamespace_TutorialPauseSizeCheck;
static_assert(sizeof(TutorialPause) == 0x41);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::get_isPaused
// Il2CppName: get_isPaused
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::get_isPaused)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "get_isPaused", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_didPauseEvent
// Il2CppName: add_didPauseEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_didPauseEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_didPauseEvent
// Il2CppName: remove_didPauseEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_didPauseEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_willResumeEvent
// Il2CppName: add_willResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_willResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_willResumeEvent
// Il2CppName: remove_willResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_willResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_didResumeEvent
// Il2CppName: add_didResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_didResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_didResumeEvent
// Il2CppName: remove_didResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_didResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::Pause
// Il2CppName: Pause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::Pause)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "Pause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::WillResume
// Il2CppName: WillResume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::WillResume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "WillResume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::Resume
// Il2CppName: Resume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::Resume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "Resume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 12,809
| 4,202
|
// Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8TrackEvent.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/UnionTypesCore.h"
#include "bindings/core/v8/V8AudioTrack.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8TextTrack.h"
#include "bindings/core/v8/V8TrackEventInit.h"
#include "bindings/core/v8/V8VideoTrack.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/LocalDOMWindow.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TrackEvent::wrapperTypeInfo = { gin::kEmbedderBlink, V8TrackEvent::domTemplate, V8TrackEvent::refObject, V8TrackEvent::derefObject, V8TrackEvent::trace, 0, 0, V8TrackEvent::preparePrototypeObject, V8TrackEvent::installConditionallyEnabledProperties, "TrackEvent", &V8Event::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TrackEvent.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TrackEvent::s_wrapperTypeInfo = V8TrackEvent::wrapperTypeInfo;
namespace TrackEventV8Internal {
static void trackAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TrackEvent* impl = V8TrackEvent::toImpl(holder);
VideoTrackOrAudioTrackOrTextTrack result;
impl->track(result);
v8SetReturnValue(info, result);
}
static void trackAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TrackEventV8Internal::trackAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TrackEvent", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
V8StringResource<> type;
TrackEventInit eventInitDict;
{
type = info[0];
if (!type.prepare())
return;
if (!isUndefinedOrNull(info[1]) && !info[1]->IsObject()) {
exceptionState.throwTypeError("parameter 2 ('eventInitDict') is not an object.");
exceptionState.throwIfNeeded();
return;
}
V8TrackEventInit::toImpl(info.GetIsolate(), info[1], eventInitDict, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
RefPtrWillBeRawPtr<TrackEvent> impl = TrackEvent::create(type, eventInitDict);
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TrackEvent::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
} // namespace TrackEventV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8TrackEventAccessors[] = {
{"track", TrackEventV8Internal::trackAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
void V8TrackEvent::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMConstructor");
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("TrackEvent"));
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
TrackEventV8Internal::constructor(info);
}
static void installV8TrackEventTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "TrackEvent", V8Event::domTemplate(isolate), V8TrackEvent::internalFieldCount,
0, 0,
V8TrackEventAccessors, WTF_ARRAY_LENGTH(V8TrackEventAccessors),
0, 0);
functionTemplate->SetCallHandler(V8TrackEvent::constructorCallback);
functionTemplate->SetLength(1);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8TrackEvent::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TrackEventTemplate);
}
bool V8TrackEvent::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8TrackEvent::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TrackEvent* V8TrackEvent::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8TrackEvent::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TrackEvent>()->ref();
#endif
}
void V8TrackEvent::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TrackEvent>()->deref();
#endif
}
} // namespace blink
| 7,117
| 2,312
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n; cin >> n;
vector<vector<int> > arr(n, vector<int>());
for(int i = 0; i < n; i++)
{
int nums = 0; cin >> nums;
for(int j = 0; j < nums; j++)
{
int v; cin >> v; arr[i].push_back(v);
}
sort(arr[i].begin(), arr[i].end());
}
int q; cin >> q;
while(q--)
{
int l, r, k, p;
cin >> l >> r >> k >> p;
l--;r--;k--;
int f = arr[k][arr[k].size()-p];
int ans = 0;
for(int i = l; i <= r; i++)
{
auto ret = upper_bound(arr[i].begin(), arr[i].end(), f);
ans += distance(ret, arr[i].end());
}
cout << ans+1 << endl;
}
return 0;
}
| 797
| 309
|
#include "palette.h"
Palette::Palette() {
int pat1[16] = {0,128,128,128,128,128,128,192,128,255,255,255,255,255,255,255};
int pat2[6] = {0,95,135,175,215,255};
short t=0, j=0, k=0;
int gray = 8;
// vector version
rgb_table.resize(256, std::vector<int>(3,0)); // 256x3 w/ value 0
int rgb[] = {0,0,0};
for (short i = 0; i < 256; i++) {
if (i < 16) { // system colors
switch (i%8) {
case 0: rgb[0] = pat1[i]; rgb[1] = pat1[i]; rgb[2] = pat1[i]; break;
case 1: rgb[0] = pat1[i]; rgb[1] = 0; rgb[2] = 0; break;
case 2: rgb[0] = 0; rgb[1] = pat1[i]; rgb[2] = 0; break;
case 3: rgb[0] = pat1[i]; rgb[1] = pat1[i]; rgb[2] = 0; break;
case 4: rgb[0] = 0; rgb[1] = 0; rgb[2] = pat1[i]; break;
case 5: rgb[0] = pat1[i]; rgb[1] = 0; rgb[2] = pat1[i]; break;
case 6: rgb[0] = 0; rgb[1] = pat1[i]; rgb[2] = pat1[i]; break;
case 7: rgb[0] = pat1[i]; rgb[1] = pat1[i]; rgb[2] = pat1[i]; break;
}
} else if (i>=16 && i<=231) { // extra colors
t = i - 16;
rgb[0] = pat2[k%6]; rgb[1] = pat2[j%6]; rgb[2] = pat2[t%6];
if (t%6==5) {
if (j%6==5) {
k += 1;
}
j += 1;
}
} else { // black-white gradient
rgb[0] = gray; rgb[1] = gray; rgb[2] = gray;
gray += 10;
}
rgb_table[i].assign(rgb,rgb+3);
}
}
Palette::~Palette() {
// for (short i = 0; i < 256; i++) {
// delete [] rgb_table[i];
// }
// delete [] rgb_table;
}
void Palette::setRGB (int r, int g, int b) {
int xterm_code = rgb2xterm(r,g,b);
char command[16] = "tput sgr0";
sprintf(command,"tput setaf %d", xterm_code);
system(command);
}
void Palette::setColor(int c) {
}
int Palette::rgb2xterm(int r, int g, int b) {
std::vector<float> d; // (squared) distance between input & table
for (short i = 0; i < 256; i++) {
int r_temp = rgb_table[i][0] - r;
int g_temp = rgb_table[i][1] - g;
int b_temp = rgb_table[i][2] - b;
d.push_back(std::pow(r_temp,2) + std::pow(g_temp,2) + std::pow(b_temp,2));
}
int color_code = std::distance(d.begin(), std::min_element(d.begin(), d.end()));
printf("color code %d\n", color_code);
return color_code;
}
void Palette::hsl2rgb(float hue, float sat, float light) {
// `abs` is a function in <cstdlib> which only takes int values
// `std::abs` is the versatile one
float chroma = (1 - std::abs(2*light-1))*sat;
int h = floor(hue/60);
float x = chroma*(1 - std::abs(h%2-1));
float r1, g1, b1; // not ready
switch (h) {
case 0: r1=chroma, g1=x, b1=0;
case 1: r1=x, g1=chroma, b1=0;
case 2: r1=0, g1=chroma, b1=x;
case 3: r1=0, g1=x, b1=chroma;
case 4: r1=x, g1=0, b1=chroma;
case 5: r1=chroma, g1=0, b1=x;
default: r1=0, g1=0, b1=0;
}
float m = light - 0.5*chroma;
int r = round(r1+m), g= round(g1+m), b = round(b1+m);
}
| 2,885
| 1,449
|
// =================================================================================================
// Copyright 2003 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
#include "public/include/XMP_Environment.h" // ! This must be the first include!
#include "XMPCore/source/XMPCore_Impl.hpp"
#include "XMPCore/source/XMPUtils.hpp"
#include <algorithm> // For binary_search.
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <errno.h>
#include <stdio.h> // For snprintf.
#if XMP_WinBuild
#pragma warning ( disable : 4800 ) // forcing value to bool 'true' or 'false' (performance warning)
#endif
// =================================================================================================
// Local Types and Constants
// =========================
typedef unsigned long UniCodePoint;
enum UniCharKind {
UCK_normal,
UCK_space,
UCK_comma,
UCK_semicolon,
UCK_quote,
UCK_control
};
typedef enum UniCharKind UniCharKind;
#define UnsByte(c) ((unsigned char)(c))
#define UCP(u) ((UniCodePoint)(u))
// ! Needed on Windows (& PC Linux?) for inequalities with literals ito avoid sign extension.
#ifndef TraceMultiFile
#define TraceMultiFile 0
#endif
// =================================================================================================
// Static Variables
// ================
// =================================================================================================
// Local Utilities
// ===============
// -------------------------------------------------------------------------------------------------
// ClassifyCharacter
// -----------------
static void
ClassifyCharacter ( XMP_StringPtr fullString, size_t offset,
UniCharKind * charKind, size_t * charSize, UniCodePoint * uniChar )
{
*charKind = UCK_normal; // Assume typical case.
unsigned char currByte = UnsByte ( fullString[offset] );
if ( currByte < UnsByte(0x80) ) {
// ----------------------------------------
// We've got a single byte ASCII character.
*charSize = 1;
*uniChar = currByte;
if ( currByte > UnsByte(0x22) ) {
if ( currByte == UnsByte(0x2C) ) {
*charKind = UCK_comma;
} else if ( currByte == UnsByte(0x3B) ) {
*charKind = UCK_semicolon;
}
// [2674672] Discontinue to interpret square brackets
// as Asian quotes in XMPUtils::SeparateArrayItems(..))
// *** else if ( (currByte == UnsByte(0x5B)) || (currByte == UnsByte(0x5D)) ) {
// *** *charKind = UCK_quote; // ! ASCII '[' and ']' are used as quotes in Chinese and Korean.
// *** }
} else { // currByte <= 0x22
if ( currByte == UnsByte(0x22) ) {
*charKind = UCK_quote;
} else if ( currByte == UnsByte(0x21) ) {
*charKind = UCK_normal;
} else if ( currByte == UnsByte(0x20) ) {
*charKind = UCK_space;
} else {
*charKind = UCK_control;
}
}
} else { // currByte >= 0x80
// ---------------------------------------------------------------------------------------
// We've got a multibyte Unicode character. The first byte has the number of bytes and the
// highest order bits. The other bytes each add 6 more bits. Compose the UTF-32 form so we
// can classify directly with the Unicode code points. Order the upperBits tests to be
// fastest for Japan, probably the most common non-ASCII usage.
*charSize = 0;
*uniChar = currByte;
while ( (*uniChar & 0x80) != 0 ) { // Count the leading 1 bits in the byte.
++(*charSize);
*uniChar = *uniChar << 1;
}
XMP_Assert ( (offset + *charSize) <= strlen(fullString) );
*uniChar = *uniChar & 0x7F; // Put the character bits in the bottom of uniChar.
*uniChar = *uniChar >> *charSize;
for ( size_t i = (offset + 1); i < (offset + *charSize); ++i ) {
*uniChar = (*uniChar << 6) | (UnsByte(fullString[i]) & 0x3F);
}
XMP_Uns32 upperBits = *uniChar >> 8; // First filter on just the high order 24 bits.
if ( upperBits == 0xFF ) { // U+FFxx
if ( *uniChar == UCP(0xFF0C) ) {
*charKind = UCK_comma; // U+FF0C, full width comma.
} else if ( *uniChar == UCP(0xFF1B) ) {
*charKind = UCK_semicolon; // U+FF1B, full width semicolon.
} else if ( *uniChar == UCP(0xFF64) ) {
*charKind = UCK_comma; // U+FF64, half width ideographic comma.
}
} else if ( upperBits == 0xFE ) { // U+FE--
if ( *uniChar == UCP(0xFE50) ) {
*charKind = UCK_comma; // U+FE50, small comma.
} else if ( *uniChar == UCP(0xFE51) ) {
*charKind = UCK_comma; // U+FE51, small ideographic comma.
} else if ( *uniChar == UCP(0xFE54) ) {
*charKind = UCK_semicolon; // U+FE54, small semicolon.
}
} else if ( upperBits == 0x30 ) { // U+30--
if ( *uniChar == UCP(0x3000) ) {
*charKind = UCK_space; // U+3000, ideographic space.
} else if ( *uniChar == UCP(0x3001) ) {
*charKind = UCK_comma; // U+3001, ideographic comma.
} else if ( (UCP(0x3008) <= *uniChar) && (*uniChar <= UCP(0x300F)) ) {
*charKind = UCK_quote; // U+3008..U+300F, various quotes.
} else if ( *uniChar == UCP(0x303F) ) {
*charKind = UCK_space; // U+303F, ideographic half fill space.
} else if ( (UCP(0x301D) <= *uniChar) && (*uniChar <= UCP(0x301F)) ) {
*charKind = UCK_quote; // U+301D..U+301F, double prime quotes.
}
} else if ( upperBits == 0x20 ) { // U+20--
if ( (UCP(0x2000) <= *uniChar) && (*uniChar <= UCP(0x200B)) ) {
*charKind = UCK_space; // U+2000..U+200B, en quad through zero width space.
} else if ( *uniChar == UCP(0x2015) ) {
*charKind = UCK_quote; // U+2015, dash quote.
} else if ( (UCP(0x2018) <= *uniChar) && (*uniChar <= UCP(0x201F)) ) {
*charKind = UCK_quote; // U+2018..U+201F, various quotes.
} else if ( *uniChar == UCP(0x2028) ) {
*charKind = UCK_control; // U+2028, line separator.
} else if ( *uniChar == UCP(0x2029) ) {
*charKind = UCK_control; // U+2029, paragraph separator.
} else if ( (*uniChar == UCP(0x2039)) || (*uniChar == UCP(0x203A)) ) {
*charKind = UCK_quote; // U+2039 and U+203A, guillemet quotes.
}
} else if ( upperBits == 0x06 ) { // U+06--
if ( *uniChar == UCP(0x060C) ) {
*charKind = UCK_comma; // U+060C, Arabic comma.
} else if ( *uniChar == UCP(0x061B) ) {
*charKind = UCK_semicolon; // U+061B, Arabic semicolon.
}
} else if ( upperBits == 0x05 ) { // U+05--
if ( *uniChar == UCP(0x055D) ) {
*charKind = UCK_comma; // U+055D, Armenian comma.
}
} else if ( upperBits == 0x03 ) { // U+03--
if ( *uniChar == UCP(0x037E) ) {
*charKind = UCK_semicolon; // U+037E, Greek "semicolon" (really a question mark).
}
} else if ( upperBits == 0x00 ) { // U+00--
if ( (*uniChar == UCP(0x00AB)) || (*uniChar == UCP(0x00BB)) ) {
*charKind = UCK_quote; // U+00AB and U+00BB, guillemet quotes.
}
}
}
} // ClassifyCharacter
// -------------------------------------------------------------------------------------------------
// IsClosingingQuote
// -----------------
static inline bool
IsClosingingQuote ( UniCodePoint uniChar, UniCodePoint openQuote, UniCodePoint closeQuote )
{
if ( (uniChar == closeQuote) ||
( (openQuote == UCP(0x301D)) && ((uniChar == UCP(0x301E)) || (uniChar == UCP(0x301F))) ) ) {
return true;
} else {
return false;
}
} // IsClosingingQuote
// -------------------------------------------------------------------------------------------------
// IsSurroundingQuote
// ------------------
static inline bool
IsSurroundingQuote ( UniCodePoint uniChar, UniCodePoint openQuote, UniCodePoint closeQuote )
{
if ( (uniChar == openQuote) || IsClosingingQuote ( uniChar, openQuote, closeQuote ) ) {
return true;
} else {
return false;
}
} // IsSurroundingQuote
// -------------------------------------------------------------------------------------------------
// GetClosingQuote
// ---------------
static UniCodePoint
GetClosingQuote ( UniCodePoint openQuote )
{
UniCodePoint closeQuote;
switch ( openQuote ) {
case UCP(0x0022) : closeQuote = UCP(0x0022); // ! U+0022 is both opening and closing.
break;
// *** [2674672] Discontinue to interpret square brackets
// *** as Asian quotes in XMPUtils::SeparateArrayItems(..))
// *** case UCP(0x005B) : closeQuote = UCP(0x005D);
// *** break;
case UCP(0x00AB) : closeQuote = UCP(0x00BB); // ! U+00AB and U+00BB are reversible.
break;
case UCP(0x00BB) : closeQuote = UCP(0x00AB);
break;
case UCP(0x2015) : closeQuote = UCP(0x2015); // ! U+2015 is both opening and closing.
break;
case UCP(0x2018) : closeQuote = UCP(0x2019);
break;
case UCP(0x201A) : closeQuote = UCP(0x201B);
break;
case UCP(0x201C) : closeQuote = UCP(0x201D);
break;
case UCP(0x201E) : closeQuote = UCP(0x201F);
break;
case UCP(0x2039) : closeQuote = UCP(0x203A); // ! U+2039 and U+203A are reversible.
break;
case UCP(0x203A) : closeQuote = UCP(0x2039);
break;
case UCP(0x3008) : closeQuote = UCP(0x3009);
break;
case UCP(0x300A) : closeQuote = UCP(0x300B);
break;
case UCP(0x300C) : closeQuote = UCP(0x300D);
break;
case UCP(0x300E) : closeQuote = UCP(0x300F);
break;
case UCP(0x301D) : closeQuote = UCP(0x301F); // ! U+301E also closes U+301D.
break;
default : closeQuote = 0;
break;
}
return closeQuote;
} // GetClosingQuote
// -------------------------------------------------------------------------------------------------
// CodePointToUTF8
// ---------------
static void
CodePointToUTF8 ( UniCodePoint uniChar, XMP_VarString & utf8Str )
{
size_t i, byteCount;
XMP_Uns8 buffer [8];
UniCodePoint cpTemp;
if ( uniChar <= 0x7F ) {
i = 7;
byteCount = 1;
buffer[7] = char(uniChar);
} else {
// ---------------------------------------------------------------------------------------
// Copy the data bits from the low order end to the high order end, include the 0x80 mask.
i = 8;
cpTemp = uniChar;
while ( cpTemp != 0 ) {
-- i; // Exit with i pointing to the last byte stored.
buffer[i] = UnsByte(0x80) | (UnsByte(cpTemp) & 0x3F);
cpTemp = cpTemp >> 6;
}
byteCount = 8 - i; // The total number of bytes needed.
XMP_Assert ( (2 <= byteCount) && (byteCount <= 6) );
// -------------------------------------------------------------------------------------
// Make sure the high order byte can hold the byte count mask, compute and set the mask.
size_t bitCount = 0; // The number of data bits in the first byte.
for ( cpTemp = (buffer[i] & UnsByte(0x3F)); cpTemp != 0; cpTemp = cpTemp >> 1 ) bitCount += 1;
if ( bitCount > (8 - (byteCount + 1)) ) byteCount += 1;
i = 8 - byteCount; // First byte index and mask shift count.
XMP_Assert ( (0 <= i) && (i <= 6) );
buffer[i] |= (UnsByte(0xFF) << i) & UnsByte(0xFF); // AUDIT: Safe, i is between 0 and 6.
}
utf8Str.assign ( (char*)(&buffer[i]), byteCount );
} // CodePointToUTF8
// -------------------------------------------------------------------------------------------------
// ApplyQuotes
// -----------
static void
ApplyQuotes ( XMP_VarString * item, UniCodePoint openQuote, UniCodePoint closeQuote, bool allowCommas )
{
bool prevSpace = false;
size_t charOffset, charLen;
UniCharKind charKind;
UniCodePoint uniChar;
// -----------------------------------------------------------------------------------------
// See if there are any separators in the value. Stop at the first occurrance. This is a bit
// tricky in order to make typical typing work conveniently. The purpose of applying quotes
// is to preserve the values when splitting them back apart. That is CatenateContainerItems
// and SeparateContainerItems must round trip properly. For the most part we only look for
// separators here. Internal quotes, as in -- Irving "Bud" Jones -- won't cause problems in
// the separation. An initial quote will though, it will make the value look quoted.
charOffset = 0;
ClassifyCharacter ( item->c_str(), charOffset, &charKind, &charLen, &uniChar );
if ( charKind != UCK_quote ) {
for ( charOffset = 0; size_t(charOffset) < item->size(); charOffset += charLen ) {
ClassifyCharacter ( item->c_str(), charOffset, &charKind, &charLen, &uniChar );
if ( charKind == UCK_space ) {
if ( prevSpace ) break; // Multiple spaces are a separator.
prevSpace = true;
} else {
prevSpace = false;
if ( (charKind == UCK_semicolon) || (charKind == UCK_control) ) break;
if ( (charKind == UCK_comma) && (! allowCommas) ) break;
}
}
}
if ( size_t(charOffset) < item->size() ) {
// --------------------------------------------------------------------------------------
// Create a quoted copy, doubling any internal quotes that match the outer ones. Internal
// quotes did not stop the "needs quoting" search, but they do need doubling. So we have
// to rescan the front of the string for quotes. Handle the special case of U+301D being
// closed by either U+301E or U+301F.
XMP_VarString newItem;
size_t splitPoint;
for ( splitPoint = 0; splitPoint <= charOffset; ++splitPoint ) {
ClassifyCharacter ( item->c_str(), splitPoint, &charKind, &charLen, &uniChar );
if ( charKind == UCK_quote ) break;
}
CodePointToUTF8 ( openQuote, newItem );
newItem.append ( *item, 0, splitPoint ); // Copy the leading "normal" portion.
for ( charOffset = splitPoint; size_t(charOffset) < item->size(); charOffset += charLen ) {
ClassifyCharacter ( item->c_str(), charOffset, &charKind, &charLen, &uniChar );
newItem.append ( *item, charOffset, charLen );
if ( (charKind == UCK_quote) && IsSurroundingQuote ( uniChar, openQuote, closeQuote ) ) {
newItem.append ( *item, charOffset, charLen );
}
}
XMP_VarString closeStr;
CodePointToUTF8 ( closeQuote, closeStr );
newItem.append ( closeStr );
*item = newItem;
}
} // ApplyQuotes
// -------------------------------------------------------------------------------------------------
// IsInternalProperty
// ------------------
// *** Need static checks of the schema prefixes!
static const char * kExternalxmpDM[] =
{ "xmpDM:album",
"xmpDM:altTapeName",
"xmpDM:altTimecode",
"xmpDM:artist",
"xmpDM:cameraAngle",
"xmpDM:cameraLabel",
"xmpDM:cameraModel",
"xmpDM:cameraMove",
"xmpDM:client",
"xmpDM:comment",
"xmpDM:composer",
"xmpDM:director",
"xmpDM:directorPhotography",
"xmpDM:engineer",
"xmpDM:genre",
"xmpDM:good",
"xmpDM:instrument",
"xmpDM:logComment",
"xmpDM:projectName",
"xmpDM:releaseDate",
"xmpDM:scene",
"xmpDM:shotDate",
"xmpDM:shotDay",
"xmpDM:shotLocation",
"xmpDM:shotName",
"xmpDM:shotNumber",
"xmpDM:shotSize",
"xmpDM:speakerPlacement",
"xmpDM:takeNumber",
"xmpDM:tapeName",
"xmpDM:trackNumber",
"xmpDM:videoAlphaMode",
"xmpDM:videoAlphaPremultipleColor",
0 }; // ! Must have zero sentinel!
typedef const char ** CharStarIterator; // Used for binary search of kExternalxmpDM;
static const char ** kLastExternalxmpDM = 0; // Set on first use.
static int CharStarLess (const char * left, const char * right )
{ return (strcmp ( left, right ) < 0); }
#define IsExternalProperty(s,p) (! IsInternalProperty ( s, p ))
static bool
IsInternalProperty ( const XMP_VarString & schema, const XMP_VarString & prop )
{
bool isInternal = false;
if ( schema == kXMP_NS_DC ) {
if ( (prop == "dc:format") ||
(prop == "dc:language") ) {
isInternal = true;
}
} else if ( schema == kXMP_NS_XMP ) {
if ( (prop == "xmp:BaseURL") ||
(prop == "xmp:CreatorTool") ||
(prop == "xmp:Format") ||
(prop == "xmp:Locale") ||
(prop == "xmp:MetadataDate") ||
(prop == "xmp:ModifyDate") ) {
isInternal = true;
}
} else if ( schema == kXMP_NS_PDF ) {
if ( (prop == "pdf:BaseURL") ||
(prop == "pdf:Creator") ||
(prop == "pdf:ModDate") ||
(prop == "pdf:PDFVersion") ||
(prop == "pdf:Producer") ) {
isInternal = true;
}
} else if ( schema == kXMP_NS_TIFF ) {
isInternal = true; // ! The TIFF properties are internal by default.
if ( (prop == "tiff:ImageDescription") || // ! ImageDescription, Artist, and Copyright are aliased.
(prop == "tiff:Artist") ||
(prop == "tiff:Copyright") ) {
isInternal = false;
}
} else if ( schema == kXMP_NS_EXIF ) {
isInternal = true; // ! The EXIF properties are internal by default.
if ( prop == "exif:UserComment" ) isInternal = false;
} else if ( schema == kXMP_NS_EXIF_Aux ) {
isInternal = true; // ! The EXIF Aux properties are internal by default.
} else if ( schema == kXMP_NS_Photoshop ) {
if ( (prop == "photoshop:ICCProfile") ||
(prop == "photoshop:TextLayers") ) isInternal = true;
} else if ( schema == kXMP_NS_CameraRaw ) {
isInternal = true; // All of crs: is internal, they are processing settings.
} else if ( schema == kXMP_NS_DM ) {
// ! Most of the xmpDM schema is internal, and unknown properties default to internal.
if ( kLastExternalxmpDM == 0 ) {
for ( kLastExternalxmpDM = &kExternalxmpDM[0]; *kLastExternalxmpDM != 0; ++kLastExternalxmpDM ) {}
}
isInternal = (! std::binary_search ( &kExternalxmpDM[0], kLastExternalxmpDM, prop.c_str(), CharStarLess ));
} else if ( schema == kXMP_NS_Script ) {
isInternal = true; // ! Most of the xmpScript schema is internal, and unknown properties default to internal.
if ( (prop == "xmpScript:action") || (prop == "xmpScript:character") || (prop == "xmpScript:dialog") ||
(prop == "xmpScript:sceneSetting") || (prop == "xmpScript:sceneTimeOfDay") ) {
isInternal = false;
}
} else if ( schema == kXMP_NS_BWF ) {
if ( prop == "bext:version" ) isInternal = true;
} else if ( schema == kXMP_NS_AdobeStockPhoto ) {
isInternal = true; // ! The bmsp schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_MM ) {
isInternal = true; // ! The xmpMM schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Text ) {
isInternal = true; // ! The xmpT schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_PagedFile ) {
isInternal = true; // ! The xmpTPg schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Graphics ) {
isInternal = true; // ! The xmpG schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Image ) {
isInternal = true; // ! The xmpGImg schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Font ) {
isInternal = true; // ! The stFNT schema has only internal properties.
}
return isInternal;
} // IsInternalProperty
// -------------------------------------------------------------------------------------------------
// RemoveSchemaChildren
// --------------------
static void
RemoveSchemaChildren ( XMP_NodePtrPos schemaPos, bool doAll )
{
XMP_Node * schemaNode = *schemaPos;
XMP_Assert ( XMP_NodeIsSchema ( schemaNode->options ) );
// ! Iterate backwards to reduce shuffling as children are erased and to simplify the logic for
// ! denoting the current child. (Erasing child n makes the old n+1 now be n.)
size_t propCount = schemaNode->children.size();
XMP_NodePtrPos beginPos = schemaNode->children.begin();
for ( size_t propNum = propCount-1, propLim = (size_t)(-1); propNum != propLim; --propNum ) {
XMP_NodePtrPos currProp = beginPos + propNum;
if ( doAll || IsExternalProperty ( schemaNode->name, (*currProp)->name ) ) {
delete *currProp; // ! Both delete the node and erase the pointer from the parent.
schemaNode->children.erase ( currProp );
}
}
if ( schemaNode->children.empty() ) {
XMP_Node * tree = schemaNode->parent;
tree->children.erase ( schemaPos );
delete schemaNode;
}
} // RemoveSchemaChildren
// -------------------------------------------------------------------------------------------------
// ItemValuesMatch
// ---------------
//
// Does the value comparisons for array merging as part of XMPUtils::AppendProperties.
static bool
ItemValuesMatch ( const XMP_Node * leftNode, const XMP_Node * rightNode )
{
const XMP_OptionBits leftForm = leftNode->options & kXMP_PropCompositeMask;
const XMP_OptionBits rightForm = leftNode->options & kXMP_PropCompositeMask;
if ( leftForm != rightForm ) return false;
if ( leftForm == 0 ) {
// Simple nodes, check the values and xml:lang qualifiers.
if ( leftNode->value != rightNode->value ) return false;
if ( (leftNode->options & kXMP_PropHasLang) != (rightNode->options & kXMP_PropHasLang) ) return false;
if ( leftNode->options & kXMP_PropHasLang ) {
if ( leftNode->qualifiers[0]->value != rightNode->qualifiers[0]->value ) return false;
}
} else if ( leftForm == kXMP_PropValueIsStruct ) {
// Struct nodes, see if all fields match, ignoring order.
if ( leftNode->children.size() != rightNode->children.size() ) return false;
for ( size_t leftNum = 0, leftLim = leftNode->children.size(); leftNum != leftLim; ++leftNum ) {
const XMP_Node * leftField = leftNode->children[leftNum];
const XMP_Node * rightField = FindConstChild ( rightNode, leftField->name.c_str() );
if ( (rightField == 0) || (! ItemValuesMatch ( leftField, rightField )) ) return false;
}
} else {
// Array nodes, see if the "leftNode" values are present in the "rightNode", ignoring order, duplicates,
// and extra values in the rightNode-> The rightNode is the destination for AppendProperties.
XMP_Assert ( leftForm & kXMP_PropValueIsArray );
for ( size_t leftNum = 0, leftLim = leftNode->children.size(); leftNum != leftLim; ++leftNum ) {
const XMP_Node * leftItem = leftNode->children[leftNum];
size_t rightNum, rightLim;
for ( rightNum = 0, rightLim = rightNode->children.size(); rightNum != rightLim; ++rightNum ) {
const XMP_Node * rightItem = rightNode->children[rightNum];
if ( ItemValuesMatch ( leftItem, rightItem ) ) break;
}
if ( rightNum == rightLim ) return false;
}
}
return true; // All of the checks passed.
} // ItemValuesMatch
// -------------------------------------------------------------------------------------------------
// AppendSubtree
// -------------
//
// The main implementation of XMPUtils::AppendProperties. See the description in TXMPMeta.hpp.
static void
AppendSubtree ( const XMP_Node * sourceNode, XMP_Node * destParent,
const bool mergeCompound, const bool replaceOld, const bool deleteEmpty )
{
XMP_NodePtrPos destPos;
XMP_Node * destNode = FindChildNode ( destParent, sourceNode->name.c_str(), kXMP_ExistingOnly, &destPos );
bool valueIsEmpty = false;
if ( XMP_PropIsSimple ( sourceNode->options ) ) {
valueIsEmpty = sourceNode->value.empty();
} else {
valueIsEmpty = sourceNode->children.empty();
}
if ( valueIsEmpty ) {
if ( deleteEmpty && (destNode != 0) ) {
delete ( destNode );
destParent->children.erase ( destPos );
}
return; // ! Done, empty values are either ignored or cause deletions.
}
if ( destNode == 0 ) {
// The one easy case, the destination does not exist.
destNode = CloneSubtree ( sourceNode, destParent, true /* skipEmpty */ );
XMP_Assert ( (destNode == 0) || (! destNode->value.empty()) || (! destNode->children.empty()) );
return;
}
// If we get here we're going to modify an existing property, either replacing or merging.
XMP_Assert ( (! valueIsEmpty) && (destNode != 0) );
XMP_OptionBits sourceForm = sourceNode->options & kXMP_PropCompositeMask;
XMP_OptionBits destForm = destNode->options & kXMP_PropCompositeMask;
bool replaceThis = replaceOld; // ! Don't modify replaceOld, it gets passed to inner calls.
if ( mergeCompound && (! XMP_PropIsSimple ( sourceForm )) ) replaceThis = false;
if ( replaceThis ) {
destNode->value = sourceNode->value; // *** Should use SetNode.
destNode->options = sourceNode->options;
destNode->RemoveChildren();
destNode->RemoveQualifiers();
CloneOffspring ( sourceNode, destNode, true /* skipEmpty */ );
if ( (! XMP_PropIsSimple ( destNode->options )) && destNode->children.empty() ) {
// Don't keep an empty array or struct. The source might be implicitly empty due to
// all children being empty. In this case CloneOffspring should skip them.
DeleteSubtree ( destPos );
}
return;
}
// From here on are cases for merging arrays or structs.
if ( XMP_PropIsSimple ( sourceForm ) || (sourceForm != destForm) ) return;
if ( sourceForm == kXMP_PropValueIsStruct ) {
// To merge a struct process the fields recursively. E.g. add simple missing fields. The
// recursive call to AppendSubtree will handle deletion for fields with empty values.
for ( size_t sourceNum = 0, sourceLim = sourceNode->children.size(); sourceNum != sourceLim && destNode!= NULL; ++sourceNum ) {
const XMP_Node * sourceField = sourceNode->children[sourceNum];
AppendSubtree ( sourceField, destNode, mergeCompound, replaceOld, deleteEmpty );
if ( deleteEmpty && destNode->children.empty() ) {
delete ( destNode );
destParent->children.erase ( destPos );
}
}
} else if ( sourceForm & kXMP_PropArrayIsAltText ) {
// Merge AltText arrays by the xml:lang qualifiers. Make sure x-default is first. Make a
// special check for deletion of empty values. Meaningful in AltText arrays because the
// xml:lang qualifier provides unambiguous source/dest correspondence.
XMP_Assert ( mergeCompound );
for ( size_t sourceNum = 0, sourceLim = sourceNode->children.size(); sourceNum != sourceLim && destNode!= NULL; ++sourceNum ) {
const XMP_Node * sourceItem = sourceNode->children[sourceNum];
if ( sourceItem->qualifiers.empty() || (sourceItem->qualifiers[0]->name != "xml:lang") ) continue;
XMP_Index destIndex = LookupLangItem ( destNode, sourceItem->qualifiers[0]->value );
if ( sourceItem->value.empty() ) {
if ( deleteEmpty && (destIndex != -1) ) {
delete ( destNode->children[destIndex] );
destNode->children.erase ( destNode->children.begin() + destIndex );
if ( destNode->children.empty() ) {
delete ( destNode );
destParent->children.erase ( destPos );
}
}
} else {
if ( destIndex != -1 ) {
// The source and dest arrays both have this language item.
if ( replaceOld ) { // ! Yes, check replaceOld not replaceThis!
destNode->children[destIndex]->value = sourceItem->value;
}
} else {
// The dest array does not have this language item, add it.
if ( (sourceItem->qualifiers[0]->value != "x-default") || destNode->children.empty() ) {
// Typical case, empty dest array or not "x-default". Non-empty should always have "x-default".
CloneSubtree ( sourceItem, destNode, true /* skipEmpty */ );
} else {
// Edge case, non-empty dest array had no "x-default", insert that at the beginning.
XMP_Node * destItem = new XMP_Node ( destNode, sourceItem->name, sourceItem->value, sourceItem->options );
CloneOffspring ( sourceItem, destItem, true /* skipEmpty */ );
destNode->children.insert ( destNode->children.begin(), destItem );
}
}
}
}
} else if ( sourceForm & kXMP_PropValueIsArray ) {
// Merge other arrays by item values. Don't worry about order or duplicates. Source
// items with empty values do not cause deletion, that conflicts horribly with merging.
for ( size_t sourceNum = 0, sourceLim = sourceNode->children.size(); sourceNum != sourceLim; ++sourceNum ) {
const XMP_Node * sourceItem = sourceNode->children[sourceNum];
size_t destNum, destLim;
for ( destNum = 0, destLim = destNode->children.size(); destNum != destLim; ++destNum ) {
const XMP_Node * destItem = destNode->children[destNum];
if ( ItemValuesMatch ( sourceItem, destItem ) ) break;
}
if ( destNum == destLim ) CloneSubtree ( sourceItem, destNode, true /* skipEmpty */ );
}
}
} // AppendSubtree
// =================================================================================================
// Class Static Functions
// ======================
// -------------------------------------------------------------------------------------------------
// CatenateArrayItems
// ------------------
/* class static */ void
XMPUtils::CatenateArrayItems ( const XMPMeta & xmpObj,
XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_StringPtr separator,
XMP_StringPtr quotes,
XMP_OptionBits options,
XMP_VarString * catedStr )
{
XMP_Assert ( (schemaNS != 0) && (arrayName != 0) ); // ! Enforced by wrapper.
XMP_Assert ( (separator != 0) && (quotes != 0) && (catedStr != 0) ); // ! Enforced by wrapper.
size_t strLen, strPos, charLen;
UniCharKind charKind;
UniCodePoint currUCP, openQuote, closeQuote;
const bool allowCommas = ((options & kXMPUtil_AllowCommas) != 0);
const XMP_Node * arrayNode = 0; // ! Move up to avoid gcc complaints.
XMP_OptionBits arrayForm = 0;
const XMP_Node * currItem = 0;
// Make sure the separator is OK. It must be one semicolon surrounded by zero or more spaces.
// Any of the recognized semicolons or spaces are allowed.
strPos = 0;
strLen = strlen ( separator );
bool haveSemicolon = false;
while ( strPos < strLen ) {
ClassifyCharacter ( separator, strPos, &charKind, &charLen, &currUCP );
strPos += charLen;
if ( charKind == UCK_semicolon ) {
if ( haveSemicolon ) XMP_Throw ( "Separator can have only one semicolon", kXMPErr_BadParam );
haveSemicolon = true;
} else if ( charKind != UCK_space ) {
XMP_Throw ( "Separator can have only spaces and one semicolon", kXMPErr_BadParam );
}
};
if ( ! haveSemicolon ) XMP_Throw ( "Separator must have one semicolon", kXMPErr_BadParam );
// Make sure the open and close quotes are a legitimate pair.
strLen = strlen ( quotes );
ClassifyCharacter ( quotes, 0, &charKind, &charLen, &openQuote );
if ( charKind != UCK_quote ) XMP_Throw ( "Invalid quoting character", kXMPErr_BadParam );
if ( charLen == strLen ) {
closeQuote = openQuote;
} else {
strPos = charLen;
ClassifyCharacter ( quotes, strPos, &charKind, &charLen, &closeQuote );
if ( charKind != UCK_quote ) XMP_Throw ( "Invalid quoting character", kXMPErr_BadParam );
if ( (strPos + charLen) != strLen ) XMP_Throw ( "Quoting string too long", kXMPErr_BadParam );
}
if ( closeQuote != GetClosingQuote ( openQuote ) ) XMP_Throw ( "Mismatched quote pair", kXMPErr_BadParam );
// Return an empty result if the array does not exist, hurl if it isn't the right form.
catedStr->erase();
XMP_ExpandedXPath arrayPath;
ExpandXPath ( schemaNS, arrayName, &arrayPath );
arrayNode = FindConstNode ( &xmpObj.tree, arrayPath );
if ( arrayNode == 0 ) return;
arrayForm = arrayNode->options & kXMP_PropCompositeMask;
if ( (! (arrayForm & kXMP_PropValueIsArray)) || (arrayForm & kXMP_PropArrayIsAlternate) ) {
XMP_Throw ( "Named property must be non-alternate array", kXMPErr_BadParam );
}
if ( arrayNode->children.empty() ) return;
// Build the result, quoting the array items, adding separators. Hurl if any item isn't simple.
// Start the result with the first value, then add the rest with a preceeding separator.
currItem = arrayNode->children[0];
if ( (currItem->options & kXMP_PropCompositeMask) != 0 ) XMP_Throw ( "Array items must be simple", kXMPErr_BadParam );
*catedStr = currItem->value;
ApplyQuotes ( catedStr, openQuote, closeQuote, allowCommas );
for ( size_t itemNum = 1, itemLim = arrayNode->children.size(); itemNum != itemLim; ++itemNum ) {
const XMP_Node * item = arrayNode->children[itemNum];
if ( (item->options & kXMP_PropCompositeMask) != 0 ) XMP_Throw ( "Array items must be simple", kXMPErr_BadParam );
XMP_VarString tempStr ( item->value );
ApplyQuotes ( &tempStr, openQuote, closeQuote, allowCommas );
*catedStr += separator;
*catedStr += tempStr;
}
} // CatenateArrayItems
// -------------------------------------------------------------------------------------------------
// SeparateArrayItems
// ------------------
/* class static */ void
XMPUtils::SeparateArrayItems ( XMPMeta * xmpObj,
XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_OptionBits options,
XMP_StringPtr catedStr )
{
XMP_Assert ( (schemaNS != 0) && (arrayName != 0) && (catedStr != 0) ); // ! Enforced by wrapper.
XMP_VarString itemValue;
size_t itemStart, itemEnd;
size_t nextSize, charSize = 0; // Avoid VS uninit var warnings.
UniCharKind nextKind, charKind = UCK_normal;
UniCodePoint nextChar, uniChar = 0;
// Extract "special" option bits, verify and normalize the others.
bool preserveCommas = false;
if ( options & kXMPUtil_AllowCommas ) {
preserveCommas = true;
options ^= kXMPUtil_AllowCommas;
}
options = VerifySetOptions ( options, 0 ); // Keep a zero value, has special meaning below.
if ( options & ~kXMP_PropArrayFormMask ) XMP_Throw ( "Options can only provide array form", kXMPErr_BadOptions );
// Find the array node, make sure it is OK. Move the current children aside, to be readded later if kept.
XMP_ExpandedXPath arrayPath;
ExpandXPath ( schemaNS, arrayName, &arrayPath );
XMP_Node * arrayNode = FindNode ( &xmpObj->tree, arrayPath, kXMP_ExistingOnly );
if ( arrayNode != 0 ) {
// The array exists, make sure the form is compatible. Zero arrayForm means take what exists.
XMP_OptionBits arrayForm = arrayNode->options & kXMP_PropArrayFormMask;
if ( (arrayForm == 0) || (arrayForm & kXMP_PropArrayIsAlternate) ) {
XMP_Throw ( "Named property must be non-alternate array", kXMPErr_BadXPath );
}
if ( (options != 0) && (options != arrayForm) ) XMP_Throw ( "Mismatch of specified and existing array form", kXMPErr_BadXPath ); // *** Right error?
} else {
// The array does not exist, try to create it.
arrayNode = FindNode ( &xmpObj->tree, arrayPath, kXMP_CreateNodes, (options | kXMP_PropValueIsArray) );
if ( arrayNode == 0 ) XMP_Throw ( "Failed to create named array", kXMPErr_BadXPath );
}
XMP_NodeOffspring oldChildren ( arrayNode->children );
size_t oldChildCount = oldChildren.size();
arrayNode->children.clear();
// Extract the item values one at a time, until the whole input string is done. Be very careful
// in the extraction about the string positions. They are essentially byte pointers, while the
// contents are UTF-8. Adding or subtracting 1 does not necessarily move 1 Unicode character!
size_t endPos = strlen ( catedStr );
itemEnd = 0;
while ( itemEnd < endPos ) {
// Skip any leading spaces and separation characters. Always skip commas here. They can be
// kept when within a value, but not when alone between values.
for ( itemStart = itemEnd; itemStart < endPos; itemStart += charSize ) {
ClassifyCharacter ( catedStr, itemStart, &charKind, &charSize, &uniChar );
if ( (charKind == UCK_normal) || (charKind == UCK_quote) ) break;
}
if ( itemStart >= endPos ) break;
if ( charKind != UCK_quote ) {
// This is not a quoted value. Scan for the end, create an array item from the substring.
for ( itemEnd = itemStart; itemEnd < endPos; itemEnd += charSize ) {
ClassifyCharacter ( catedStr, itemEnd, &charKind, &charSize, &uniChar );
if ( (charKind == UCK_normal) || (charKind == UCK_quote) ) continue;
if ( (charKind == UCK_comma) && preserveCommas ) continue;
if ( charKind != UCK_space ) break;
if ( (itemEnd + charSize) >= endPos ) break; // Anything left?
ClassifyCharacter ( catedStr, (itemEnd+charSize), &nextKind, &nextSize, &nextChar );
if ( (nextKind == UCK_normal) || (nextKind == UCK_quote) ) continue;
if ( (nextKind == UCK_comma) && preserveCommas ) continue;
break; // Have multiple spaces, or a space followed by a separator.
}
itemValue.assign ( catedStr, itemStart, (itemEnd - itemStart) );
} else {
// Accumulate quoted values into a local string, undoubling internal quotes that
// match the surrounding quotes. Do not undouble "unmatching" quotes.
UniCodePoint openQuote = uniChar;
UniCodePoint closeQuote = GetClosingQuote ( openQuote );
itemStart += charSize; // Skip the opening quote;
itemValue.erase();
for ( itemEnd = itemStart; itemEnd < endPos; itemEnd += charSize ) {
ClassifyCharacter ( catedStr, itemEnd, &charKind, &charSize, &uniChar );
if ( (charKind != UCK_quote) || (! IsSurroundingQuote ( uniChar, openQuote, closeQuote)) ) {
// This is not a matching quote, just append it to the item value.
itemValue.append ( catedStr, itemEnd, charSize );
} else {
// This is a "matching" quote. Is it doubled, or the final closing quote? Tolerate
// various edge cases like undoubled opening (non-closing) quotes, or end of input.
if ( (itemEnd + charSize) < endPos ) {
ClassifyCharacter ( catedStr, itemEnd+charSize, &nextKind, &nextSize, &nextChar );
} else {
nextKind = UCK_semicolon; nextSize = 0; nextChar = 0x3B;
}
if ( uniChar == nextChar ) {
// This is doubled, copy it and skip the double.
itemValue.append ( catedStr, itemEnd, charSize );
itemEnd += nextSize; // Loop will add in charSize.
} else if ( ! IsClosingingQuote ( uniChar, openQuote, closeQuote ) ) {
// This is an undoubled, non-closing quote, copy it.
itemValue.append ( catedStr, itemEnd, charSize );
} else {
// This is an undoubled closing quote, skip it and exit the loop.
itemEnd += charSize;
break;
}
}
} // Loop to accumulate the quoted value.
}
// Add the separated item to the array. Keep a matching old value in case it had separators.
size_t oldChild;
for ( oldChild = 0; oldChild < oldChildCount; ++oldChild ) {
if ( (oldChildren[oldChild] != 0) && (itemValue == oldChildren[oldChild]->value) ) break;
}
XMP_Node * newItem = 0;
if ( oldChild == oldChildCount ) {
newItem = new XMP_Node ( arrayNode, kXMP_ArrayItemName, itemValue.c_str(), 0 );
} else {
newItem = oldChildren[oldChild];
oldChildren[oldChild] = 0; // ! Don't match again, let duplicates be seen.
}
arrayNode->children.push_back ( newItem );
} // Loop through all of the returned items.
// Delete any of the old children that were not kept.
for ( size_t i = 0; i < oldChildCount; ++i ) {
if ( oldChildren[i] != 0 ) delete oldChildren[i];
}
} // SeparateArrayItems
// -------------------------------------------------------------------------------------------------
// ApplyTemplate
// -------------
/* class static */ void
XMPUtils::ApplyTemplate ( XMPMeta * workingXMP,
const XMPMeta & templateXMP,
XMP_OptionBits actions )
{
bool doClear = XMP_OptionIsSet ( actions, kXMPTemplate_ClearUnnamedProperties );
bool doAdd = XMP_OptionIsSet ( actions, kXMPTemplate_AddNewProperties );
bool doReplace = XMP_OptionIsSet ( actions, kXMPTemplate_ReplaceExistingProperties );
bool deleteEmpty = XMP_OptionIsSet ( actions, kXMPTemplate_ReplaceWithDeleteEmpty );
doReplace |= deleteEmpty; // Delete-empty implies Replace.
deleteEmpty &= (! doClear); // Clear implies not delete-empty, but keep the implicit Replace.
bool doAll = XMP_OptionIsSet ( actions, kXMPTemplate_IncludeInternalProperties );
// ! In several places we do loops backwards so that deletions do not perturb the remaining indices.
// ! These loops use ordinals (size .. 1), we must use a zero based index inside the loop.
if ( doClear ) {
// Visit the top level working properties, delete if not in the template.
for ( size_t schemaOrdinal = workingXMP->tree.children.size(); schemaOrdinal > 0; --schemaOrdinal ) {
size_t schemaNum = schemaOrdinal-1; // ! Convert ordinal to index!
XMP_Node * workingSchema = workingXMP->tree.children[schemaNum];
const XMP_Node * templateSchema = FindConstSchema ( &templateXMP.tree, workingSchema->name.c_str() );
if ( templateSchema == 0 ) {
// The schema is not in the template, delete all properties or just all external ones.
if ( doAll ) {
workingSchema->RemoveChildren(); // Remove the properties here, delete the schema below.
} else {
for ( size_t propOrdinal = workingSchema->children.size(); propOrdinal > 0; --propOrdinal ) {
size_t propNum = propOrdinal-1; // ! Convert ordinal to index!
XMP_Node * workingProp = workingSchema->children[propNum];
if ( IsExternalProperty ( workingSchema->name, workingProp->name ) ) {
delete ( workingProp );
workingSchema->children.erase ( workingSchema->children.begin() + propNum );
}
}
}
} else {
// Check each of the working XMP's properties to see if it is in the template.
for ( size_t propOrdinal = workingSchema->children.size(); propOrdinal > 0; --propOrdinal ) {
size_t propNum = propOrdinal-1; // ! Convert ordinal to index!
XMP_Node * workingProp = workingSchema->children[propNum];
if ( (doAll || IsExternalProperty ( workingSchema->name, workingProp->name )) &&
(FindConstChild ( templateSchema, workingProp->name.c_str() ) == 0) ) {
delete ( workingProp );
workingSchema->children.erase ( workingSchema->children.begin() + propNum );
}
}
}
if ( workingSchema->children.empty() ) {
delete ( workingSchema );
workingXMP->tree.children.erase ( workingXMP->tree.children.begin() + schemaNum );
}
}
}
if ( doAdd | doReplace ) {
for ( size_t schemaNum = 0, schemaLim = templateXMP.tree.children.size(); schemaNum < schemaLim; ++schemaNum ) {
const XMP_Node * templateSchema = templateXMP.tree.children[schemaNum];
// Make sure we have an output schema node, then process the top level template properties.
XMP_NodePtrPos workingSchemaPos;
XMP_Node * workingSchema = FindSchemaNode ( &workingXMP->tree, templateSchema->name.c_str(),
kXMP_ExistingOnly, &workingSchemaPos );
if ( workingSchema == 0 ) {
workingSchema = new XMP_Node ( &workingXMP->tree, templateSchema->name, templateSchema->value, kXMP_SchemaNode );
workingXMP->tree.children.push_back ( workingSchema );
workingSchemaPos = workingXMP->tree.children.end() - 1;
}
for ( size_t propNum = 0, propLim = templateSchema->children.size(); propNum < propLim; ++propNum ) {
const XMP_Node * templateProp = templateSchema->children[propNum];
if ( doAll || IsExternalProperty ( templateSchema->name, templateProp->name ) ) {
AppendSubtree ( templateProp, workingSchema, doAdd, doReplace, deleteEmpty );
}
}
if ( workingSchema->children.empty() ) {
delete ( workingSchema );
workingXMP->tree.children.erase ( workingSchemaPos );
}
}
}
} // ApplyTemplate
// -------------------------------------------------------------------------------------------------
// RemoveProperties
// ----------------
/* class static */ void
XMPUtils::RemoveProperties ( XMPMeta * xmpObj,
XMP_StringPtr schemaNS,
XMP_StringPtr propName,
XMP_OptionBits options )
{
XMP_Assert ( (schemaNS != 0) && (propName != 0) ); // ! Enforced by wrapper.
const bool doAll = XMP_TestOption (options, kXMPUtil_DoAllProperties );
const bool includeAliases = XMP_TestOption ( options, kXMPUtil_IncludeAliases );
if ( *propName != 0 ) {
// Remove just the one indicated property. This might be an alias, the named schema might
// not actually exist. So don't lookup the schema node.
if ( *schemaNS == 0 ) XMP_Throw ( "Property name requires schema namespace", kXMPErr_BadParam );
XMP_ExpandedXPath expPath;
ExpandXPath ( schemaNS, propName, &expPath );
XMP_NodePtrPos propPos;
XMP_Node * propNode = FindNode ( &(xmpObj->tree), expPath, kXMP_ExistingOnly, kXMP_NoOptions, &propPos );
if ( propNode != 0 ) {
if ( doAll || IsExternalProperty ( expPath[kSchemaStep].step, expPath[kRootPropStep].step ) ) {
XMP_Node * parent = propNode->parent; // *** Should have XMP_Node::RemoveChild(pos).
delete propNode; // ! Both delete the node and erase the pointer from the parent.
parent->children.erase ( propPos );
DeleteEmptySchema ( parent );
}
}
} else if ( *schemaNS != 0 ) {
// Remove all properties from the named schema. Optionally include aliases, in which case
// there might not be an actual schema node.
XMP_NodePtrPos schemaPos;
XMP_Node * schemaNode = FindSchemaNode ( &xmpObj->tree, schemaNS, kXMP_ExistingOnly, &schemaPos );
if ( schemaNode != 0 ) RemoveSchemaChildren ( schemaPos, doAll );
if ( includeAliases ) {
// We're removing the aliases also. Look them up by their namespace prefix. Yes, the
// alias map is sorted so we could process just that portion. But that takes more code
// and the extra speed isn't worth it. (Plus this way we avoid a dependence on the map
// implementation.) Lookup the XMP node from the alias, to make sure the actual exists.
XMP_StringPtr nsPrefix;
XMP_StringLen nsLen;
(void) XMPMeta::GetNamespacePrefix ( schemaNS, &nsPrefix, &nsLen );
XMP_AliasMapPos currAlias = sRegisteredAliasMap->begin();
XMP_AliasMapPos endAlias = sRegisteredAliasMap->end();
for ( ; currAlias != endAlias; ++currAlias ) {
if ( strncmp ( currAlias->first.c_str(), nsPrefix, nsLen ) == 0 ) {
XMP_NodePtrPos actualPos;
XMP_Node * actualProp = FindNode ( &xmpObj->tree, currAlias->second, kXMP_ExistingOnly, kXMP_NoOptions, &actualPos );
if ( actualProp != 0 ) {
XMP_Node * rootProp = actualProp;
while ( ! XMP_NodeIsSchema ( rootProp->parent->options ) ) rootProp = rootProp->parent;
if ( doAll || IsExternalProperty ( rootProp->parent->name, rootProp->name ) ) {
XMP_Node * parent = actualProp->parent;
delete actualProp; // ! Both delete the node and erase the pointer from the parent.
parent->children.erase ( actualPos );
DeleteEmptySchema ( parent );
}
}
}
}
}
} else {
// Remove all appropriate properties from all schema. In this case we don't have to be
// concerned with aliases, they are handled implicitly from the actual properties.
// ! Iterate backwards to reduce shuffling if schema are erased and to simplify the logic
// ! for denoting the current schema. (Erasing schema n makes the old n+1 now be n.)
size_t schemaCount = xmpObj->tree.children.size();
XMP_NodePtrPos beginPos = xmpObj->tree.children.begin();
for ( size_t schemaNum = schemaCount-1, schemaLim = (size_t)(-1); schemaNum != schemaLim; --schemaNum ) {
XMP_NodePtrPos currSchema = beginPos + schemaNum;
RemoveSchemaChildren ( currSchema, doAll );
}
}
} // RemoveProperties
// -------------------------------------------------------------------------------------------------
// DuplicateSubtree
// ----------------
/* class static */ void
XMPUtils::DuplicateSubtree ( const XMPMeta & source,
XMPMeta * dest,
XMP_StringPtr sourceNS,
XMP_StringPtr sourceRoot,
XMP_StringPtr destNS,
XMP_StringPtr destRoot,
XMP_OptionBits options )
{
IgnoreParam(options);
bool fullSourceTree = false;
bool fullDestTree = false;
XMP_ExpandedXPath sourcePath, destPath;
const XMP_Node * sourceNode = 0;
XMP_Node * destNode = 0;
XMP_Assert ( (sourceNS != 0) && (*sourceNS != 0) );
XMP_Assert ( (sourceRoot != 0) && (*sourceRoot != 0) );
XMP_Assert ( (dest != 0) && (destNS != 0) && (destRoot != 0) );
if ( *destNS == 0 ) destNS = sourceNS;
if ( *destRoot == 0 ) destRoot = sourceRoot;
if ( XMP_LitMatch ( sourceNS, "*" ) ) fullSourceTree = true;
if ( XMP_LitMatch ( destNS, "*" ) ) fullDestTree = true;
if ( (&source == dest) && (fullSourceTree | fullDestTree) ) {
XMP_Throw ( "Can't duplicate tree onto itself", kXMPErr_BadParam );
}
if ( fullSourceTree & fullDestTree ) XMP_Throw ( "Use Clone for full tree to full tree", kXMPErr_BadParam );
if ( fullSourceTree ) {
// The destination must be an existing empty struct, copy all of the source top level as fields.
ExpandXPath ( destNS, destRoot, &destPath );
destNode = FindNode ( &dest->tree, destPath, kXMP_ExistingOnly );
if ( (destNode == 0) || (! XMP_PropIsStruct ( destNode->options )) ) {
XMP_Throw ( "Destination must be an existing struct", kXMPErr_BadXPath );
}
if ( ! destNode->children.empty() ) {
if ( options & kXMP_DeleteExisting ) {
destNode->RemoveChildren();
} else {
XMP_Throw ( "Destination must be an empty struct", kXMPErr_BadXPath );
}
}
for ( size_t schemaNum = 0, schemaLim = source.tree.children.size(); schemaNum < schemaLim; ++schemaNum ) {
const XMP_Node * currSchema = source.tree.children[schemaNum];
for ( size_t propNum = 0, propLim = currSchema->children.size(); propNum < propLim; ++propNum ) {
sourceNode = currSchema->children[propNum];
XMP_Node * copyNode = new XMP_Node ( destNode, sourceNode->name, sourceNode->value, sourceNode->options );
destNode->children.push_back ( copyNode );
CloneOffspring ( sourceNode, copyNode );
}
}
} else if ( fullDestTree ) {
// The source node must be an existing struct, copy all of the fields to the dest top level.
XMP_ExpandedXPath srcPath;
ExpandXPath ( sourceNS, sourceRoot, &srcPath );
sourceNode = FindConstNode ( &source.tree, srcPath );
if ( (sourceNode == 0) || (! XMP_PropIsStruct ( sourceNode->options )) ) {
XMP_Throw ( "Source must be an existing struct", kXMPErr_BadXPath );
}
destNode = &dest->tree;
if ( ! destNode->children.empty() ) {
if ( options & kXMP_DeleteExisting ) {
destNode->RemoveChildren();
} else {
XMP_Throw ( "Destination tree must be empty", kXMPErr_BadXPath );
}
}
std::string nsPrefix;
XMP_StringPtr nsURI;
XMP_StringLen nsLen;
for ( size_t fieldNum = 0, fieldLim = sourceNode->children.size(); fieldNum < fieldLim; ++fieldNum ) {
const XMP_Node * currField = sourceNode->children[fieldNum];
size_t colonPos = currField->name.find ( ':' );
if ( colonPos == std::string::npos ) continue;
nsPrefix.assign ( currField->name.c_str(), colonPos );
bool nsOK = XMPMeta::GetNamespaceURI ( nsPrefix.c_str(), &nsURI, &nsLen );
if ( ! nsOK ) XMP_Throw ( "Source field namespace is not global", kXMPErr_BadSchema );
XMP_Node * destSchema = FindSchemaNode ( &dest->tree, nsURI, kXMP_CreateNodes );
if ( destSchema == 0 ) XMP_Throw ( "Failed to find destination schema", kXMPErr_BadSchema );
XMP_Node * copyNode = new XMP_Node ( destSchema, currField->name, currField->value, currField->options );
destSchema->children.push_back ( copyNode );
CloneOffspring ( currField, copyNode );
}
} else {
// Find the root nodes for the source and destination subtrees.
ExpandXPath ( sourceNS, sourceRoot, &sourcePath );
ExpandXPath ( destNS, destRoot, &destPath );
sourceNode = FindConstNode ( &source.tree, sourcePath );
if ( sourceNode == 0 ) XMP_Throw ( "Can't find source subtree", kXMPErr_BadXPath );
destNode = FindNode ( &dest->tree, destPath, kXMP_ExistingOnly ); // Dest must not yet exist.
if ( destNode != 0 ) XMP_Throw ( "Destination subtree must not exist", kXMPErr_BadXPath );
destNode = FindNode ( &dest->tree, destPath, kXMP_CreateNodes ); // Now create the dest.
if ( destNode == 0 ) XMP_Throw ( "Can't create destination root node", kXMPErr_BadXPath );
// Make sure the destination is not within the source! The source can't be inside the destination
// because the source already existed and the destination was just created.
if ( &source == dest ) {
for ( XMP_Node * testNode = destNode; testNode != 0; testNode = testNode->parent ) {
if ( testNode == sourceNode ) {
// *** delete the just-created dest root node
XMP_Throw ( "Destination subtree is within the source subtree", kXMPErr_BadXPath );
}
}
}
// *** Could use a CloneTree util here and maybe elsewhere.
destNode->value = sourceNode->value; // *** Should use SetNode.
destNode->options = sourceNode->options;
CloneOffspring ( sourceNode, destNode );
}
} // DuplicateSubtree
// =================================================================================================
| 52,694
| 19,573
|
/* -*- Mode: C++; -*- */
// copyright (c) 2010 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "RSAPI.h"
#include "GeometricDistribution.h"
#include "RandomNumberGenerator.h"
RolloutState::RolloutState(Environment<Vector, int>* environment_,
AbstractPolicy<Vector, int>* policy_,
Vector& start_state_, real gamma_)
: environment(environment_),
policy(policy_),
start_state(start_state_),
gamma(gamma_) {
V_U = 0;
V_L = 0;
V = 0;
U = INF;
}
RolloutState::~RolloutState() {
for (uint i = 0; i < rollouts.size(); ++i) {
delete rollouts[i];
}
}
Rollout<Vector, int, AbstractPolicy<Vector, int> >* RolloutState::NewRollout(
AbstractPolicy<Vector, int>* policy, int action) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout =
new Rollout<Vector, int, AbstractPolicy<Vector, int> >(
start_state, action, policy, environment, gamma); // valgrind
rollouts.push_back(rollout);
return rollout;
}
/// Extend all rollouts by T
void RolloutState::ExtendAllRollouts(const int T) {
for (uint i = 0; i < rollouts.size(); ++i) {
// logmsg("performing %d-th rollout for state\n", i);
rollouts[i]->Sample(T);
}
}
/// Get the best empirical action in isolation
///
/// If no improved action is found, then it returns the normal action
int RolloutState::BestEmpiricalAction(real delta) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
Q_U += 1 / (1 - gamma);
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (rollout->running) {
error_bound = exp(rollout->T * log_gamma);
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / (N + 1); // normalise
Q_L = Q_L / (N + 1); // normalise
Vector confidence_interval =
pow(N + 1, (real)-0.5) * sqrt(0.5 * log(1.0 / delta));
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
policy->setState(start_state);
int normal_action = policy->SelectAction();
start_action = normal_action;
// int optimistic_action = ArgMax(Q_U);
int pessimistic_action = ArgMax(Q_L);
real gap = (Q_L(pessimistic_action) - Q_U(normal_action));
#if 0
dbgmsg("CI: "); confidence_interval.print(stdout);
dbgmsg("QU: "); Q_U.print(stdout);
dbgmsg("QL: "); Q_L.print(stdout);
dbgmsg ("gap: %f, %f %f, a: %d->%d, s: ",
gap,
Q_U(pessimistic_action),
Q_U(normal_action),
normal_action,
pessimistic_action);
start_state.print(stdout);
#endif
if (gap > 0) {
return pessimistic_action;
} else {
return normal_action;
}
}
real RolloutState::Gap() {
Vector Q((int)environment->getNActions()); // Average Q
Vector N(
(int)environment->getNActions()); // number of times action was played
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
int a = rollout->start_action;
N(a)++;
Q(a) += rollout->discounted_reward;
}
Q /= N; // normalise
real maxQ = Max(Q);
real Q2 = -1e-9;
for (uint i = 0; i < environment->getNActions(); ++i) {
if (Q(i) > Q2 && Q(i) < maxQ) {
Q2 = Q(i);
}
}
return maxQ - Q2;
}
/// Get the best empirical action in isolation
///
/// This actually returns no action if no improvement seems possible.
///
int RolloutState::BestHighProbabilityAction(real delta) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (0) { // rollout->running) {
error_bound = exp(rollout->T * log_gamma);
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / N; // normalise
Q_L = Q_L / N; // normalise
Vector confidence_interval =
pow(N, (real)-0.5) * sqrt(0.5 * log(1.0 / delta));
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
policy->setState(start_state);
int normal_action = policy->SelectAction();
// int optimistic_action = ArgMax(Q_U);
int pessimistic_action = ArgMax(Q_L);
real gap = (Q_L(pessimistic_action) - Q_U(normal_action));
#if 0
printf ("# gap: %f, p:[%f %f] n:[%f %f] u:[%f %f]\n",
gap,
Q_L(pessimistic_action), Q_U(pessimistic_action),
Q_L(normal_action), Q_U(normal_action),
Q_L(optimistic_action), Q_U(optimistic_action));
#endif
if (gap > 0) {
// dbgmsg ("# gap: %f, a: %d->%d, s: ", gap, normal_action,
// pessimistic_action); start_state.print(stdout);
return pessimistic_action;
} else {
return -1;
}
}
/** Sample from the current policy.
This uses a gamma-discount sample from the current policy.
The idea is the following.
An infinite horizon problem with discount factor \f$\gamma\f$ is
equivalent to a finite horizon problem with a random horizon,
geometrically distributed, such that at any time \f$t > 0\f$, the
probability that the horizon \f$T = t\f$ is equal to \f$1 - \gamma\f$.
We can thus sample from that distribution easily.
*/
Vector RolloutState::SampleFromPolicy() {
GeometricDistribution horizon_distribution(1 - gamma);
int horizon_sample = horizon_distribution.generate();
policy->setState(start_state);
int normal_action = policy->SelectAction();
Rollout<Vector, int, AbstractPolicy<Vector, int> > rollout(
start_state, normal_action, policy, environment, gamma);
rollout.Sample(horizon_sample);
return rollout.end_state;
}
/// Group best and worst actions together.
///
/// Give 0 probability to any completely dominated action.
/// Other actions get a probability proportional to the number
/// of other actions they dominate.
std::pair<Vector, bool> RolloutState::BestGroupAction(real delta) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (rollout->running) {
error_bound = exp(rollout->T * log_gamma);
// printf ("error bound not zero: %f\n", error_bound);
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / N; // normalise
Q_L = Q_L / N; // normalise
Vector confidence_interval =
pow(N, (real)-0.5) * sqrt(0.5 * log(1.0 / delta));
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
policy->setState(start_state);
std::pair<Vector, bool> retval;
Vector& Pr = retval.first;
Pr.Resize(environment->getNActions()); // Action probabilitie
bool& domination = retval.second;
domination = false;
for (uint i = 0; i < environment->getNActions(); ++i) {
Pr(i) = 0.5;
for (uint j = 0; j < environment->getNActions(); ++j) {
if (i == j) {
continue;
}
if (Q_U(i) <= Q_L(j)) {
Pr(i) = 0;
domination = true;
}
if (Q_L(i) >= Q_U(j)) {
Pr(i) += 1;
domination = true;
}
}
}
Pr /= Pr.Sum();
// printf("U: "); Q_U.print(stdout);
// printf("L: "); Q_L.print(stdout);
#if 0
if (domination) {
printf("# S: "); start_state.print(stdout);
printf("# P: "); Pr.print(stdout);
}
#endif
return retval;
}
/** Bootstrap from values of neighbouring states.
TODO This does not work at the moment.
*/
void RolloutState::Bootstrap(KDTree<RolloutState>& tree, real L) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (rollout->running) {
error_bound = exp(rollout->T * log_gamma);
Vector s_T = rollout->end_state;
OrderedFixedList<KDNode> knn_list = tree.FindKNearestNeighbours(s_T, 3);
#if 0
std::list<std::pair<real, KDNode*> >::iterator knn_iter;
for (knn_iter = knn_list.S.begin();
knn_iter != knn_list.S.end();
++knn_iter) {
KDNode* node = knn_iter->second;
}
#endif
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / N; // normalise
Q_L = Q_L / N; // normalise
Vector confidence_interval = pow(N, (real)-0.5);
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
// Serror("Buggy!\n");
// exit(-1);
}
RSAPI::RSAPI(Environment<Vector, int>* environment_,
RandomNumberGenerator* rng_, real gamma_)
: environment(environment_), policy(NULL), rng(rng_), gamma(gamma_) {
// nothing to do here.
}
RSAPI::~RSAPI() {
for (uint i = 0; i < states.size(); ++i) {
delete states[i];
}
}
void RSAPI::AddState(Vector& state) {
states.push_back(new RolloutState(environment, policy, state, gamma));
}
/// Sample a new state
Vector RSAPI::SampleStateFromPolicy() const {
int k = rng->discrete_uniform(states.size());
return states[k]->SampleFromPolicy();
}
void RSAPI::SampleRandomly(const int T) {
RolloutState* state = states[rng->discrete_uniform(states.size())];
// logmsg("Randomly sampling state");
state->ExtendAllRollouts(T);
}
void RSAPI::NewRandomRollouts(const int K, const int T) {
for (int k = 0; k < K; ++k) {
RolloutState* state = states[rng->discrete_uniform(states.size())];
state->NewRollout(policy,
rng->discrete_uniform(environment->getNActions()));
state->ExtendAllRollouts(T);
}
}
/// Sample uniformly from all states
///
/// Take K rollouts from all state-action pairs, of length T
void RSAPI::SampleUniformly(const int K, const int T) {
for (uint i = 0; i < states.size(); ++i) {
RolloutState* state = states[i];
for (uint a = 0; a < environment->getNActions(); ++a) {
for (int k = 0; k < K; ++k) {
state->NewRollout(policy, a);
}
}
// logmsg("Sampling state %d\n", i);
state->ExtendAllRollouts(T);
}
}
/// Sample uniformly from all states till an error bound is met
///
/// Take K rollouts from all state-action pairs, of length T
void RSAPI::SampleToErrorBound(const int K, const int T, const real delta) {
int total_rollouts = states.size() * K;
int k = 0;
int n_sampled_states = 1;
int total_updates = 0;
std::vector<bool> state_ok(states.size());
for (uint i = 0; i < states.size(); ++i) {
state_ok[i] = false;
}
while (k < total_rollouts && n_sampled_states) {
n_sampled_states = 0;
for (uint i = 0; i < states.size(); ++i) {
if (state_ok[i]) {
continue;
}
RolloutState* state = states[i];
++n_sampled_states;
++k;
for (uint a = 0; a < environment->getNActions(); ++a) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout =
state->NewRollout(policy, a);
rollout->Sample(T);
}
int a_max = state->BestHighProbabilityAction(delta);
if (a_max >= 0) {
state_ok[i] = true;
total_updates++;
}
}
}
// printf ("# n updates: %d\n", total_updates);
}
void RSAPI::SampleUpperBound(const int K, const int T, const real delta) {
int total_rollouts = states.size() * K;
int total_updates = 0;
Vector U((uint)states.size());
U += 1e9;
for (int k = 0; k < total_rollouts; ++k) {
uint i = ArgMax(U);
if (U(i) == 0) {
// logmsg("Early break from upper bound sampling\n");
break;
}
RolloutState* state = states[i];
++k;
for (uint a = 0; a < environment->getNActions(); ++a) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout =
state->NewRollout(policy, a);
rollout->Sample(T);
}
int a_max = state->BestHighProbabilityAction(delta);
if (a_max >= 0) {
U(i) = 0;
total_updates++;
}
}
// printf ("# n updates: %d\n", total_updates);
}
/// Simply train the classifier
int RSAPI::TrainClassifier(Classifier<Vector, int, Vector>* classifier,
real delta) {
int n_improved_actions = 0;
for (uint i = 0; i < states.size(); ++i) {
int best_action = states[i]->BestEmpiricalAction(delta);
// int best_action = states[i]->BestHighProbabilityAction(delta);
if (best_action >= 0 && best_action != states[i]->start_action) {
// printf("# Action: %d state: ", best_action);
// states[i]->start_state.print(stdout);
n_improved_actions++;
}
if (best_action >= 0) {
classifier->Observe(states[i]->start_state, best_action);
}
}
return n_improved_actions;
}
real RSAPI::LipschitzBound() {
real L = 1e-3;
for (uint i = 0; i < states.size(); ++i) {
for (uint j = 0; j < states.size(); ++j) {
if (i == j) {
continue;
}
real D_U = states[i]->V_U - states[j]->V_U;
real D_L = states[i]->V_L - states[j]->V_L;
real D = std::max(D_U, D_L);
real s = EuclideanNorm(&states[i]->start_state, &states[j]->start_state);
if (s > 0) {
L = std::max(L, D / s);
}
}
}
return L;
}
void RSAPI::Bootstrap() {
/// Make a KNN tree.
KDTree<RolloutState> tree(environment->getNStates());
for (uint i = 0; i < states.size(); ++i) {
tree.AddVectorObject(states[i]->start_state, states[i]);
}
#if 0
for (uint i=0; i<states.size(); ++i) {
printf ("%f %f # state bounds\n", states[i]->V_U, states[i]->V_L);
}
#endif
real L = LipschitzBound();
for (uint i = 0; i < states.size(); ++i) {
states[i]->Bootstrap(tree, L);
}
#if 0
for (uint i=0; i<states.size(); ++i) {
printf ("%f %f # new state bounds\n", states[i]->V_U, states[i]->V_L);
}
#endif
}
/// Simply train the classifier with action groups
///
/// delta is the error probability that is deemed acceptable
int RSAPI::GroupTrainClassifier(Classifier<Vector, int, Vector>* classifier,
real delta) {
int n_improved_actions = 0;
for (uint i = 0; i < states.size(); ++i) {
std::pair<Vector, bool> retval = states[i]->BestGroupAction(delta);
if (retval.second) {
n_improved_actions++;
classifier->Observe(states[i]->start_state, retval.first);
}
}
return n_improved_actions;
}
| 16,332
| 5,888
|
/*
* Copyright 2011, Ben Langmead <langmea@cs.jhu.edu>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 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.
*
* Bowtie 2 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 Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "presets.h"
#include "opts.h"
using namespace std;
void PresetsV0::apply(
const std::string& preset,
std::string& policy,
EList<std::pair<int, std::string> >& opts)
{
// Presets: Same as:
// For --end-to-end:
// --very-fast -D 5 -R 1 -N 0 -L 22 -i S,0,2.50
// --fast -D 10 -R 2 -N 0 -L 22 -i S,0,2.50
// --sensitive -D 15 -R 2 -N 0 -L 22 -i S,1,1.15
// --very-sensitive -D 20 -R 3 -N 0 -L 20 -i S,1,0.50
if(preset == "very-fast") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=5";
policy += ";ROUNDS=1";
policy += ";IVAL=S,0,2.50";
} else if(preset == "fast") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=10";
policy += ";ROUNDS=2";
policy += ";IVAL=S,0,2.50";
} else if(preset == "sensitive") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=15";
policy += ";ROUNDS=2";
policy += ";IVAL=S,1,1.15";
} else if(preset == "very-sensitive") {
policy += ";SEED=0";
policy += ";SEEDLEN=20";
policy += ";DPS=20";
policy += ";ROUNDS=3";
policy += ";IVAL=S,1,0.50";
}
// For --local:
// --very-fast-local -D 5 -R 1 -N 0 -L 25 -i S,1,2.00
// --fast-local -D 10 -R 2 -N 0 -L 22 -i S,1,1.75
// --sensitive-local -D 15 -R 2 -N 0 -L 20 -i S,1,0.75 (default)
// --very-sensitive-local -D 20 -R 3 -N 0 -L 20 -i S,1,0.50
else if(preset == "very-fast-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=25";
policy += ";DPS=5";
policy += ";ROUNDS=1";
policy += ";IVAL=S,1,2.00";
} else if(preset == "fast-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=10";
policy += ";ROUNDS=2";
policy += ";IVAL=S,1,1.75";
} else if(preset == "sensitive-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=20";
policy += ";DPS=15";
policy += ";ROUNDS=2";
policy += ";IVAL=S,1,0.75";
} else if(preset == "very-sensitive-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=20";
policy += ";DPS=20";
policy += ";ROUNDS=3";
policy += ";IVAL=S,1,0.50";
}
else {
cerr << "Unknown preset: " << preset.c_str() << endl;
}
}
| 2,929
| 1,342
|
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2017 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Shader cross-stage interface tests
*//*--------------------------------------------------------------------*/
#include "vktSpvAsmCrossStageInterfaceTests.hpp"
#include "tcuTestLog.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuImageCompare.hpp"
#include "vkDefs.hpp"
#include "vkMemUtil.hpp"
#include "deSharedPtr.hpp"
#include "vkQueryUtil.hpp"
#include "vkRefUtil.hpp"
#include "vkStrUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"
#include "deUniquePtr.hpp"
#include "vktSpvAsmGraphicsShaderTestUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vktTestGroupUtil.hpp"
#include <map>
#include <vector>
namespace vkt
{
namespace SpirVAssembly
{
using namespace vk;
namespace
{
using std::string;
using std::map;
using std::vector;
typedef de::SharedPtr<Unique<VkShaderModule> > ShaderModuleSP;
using de::MovePtr;
using tcu::Vec4;
enum TestType
{
TEST_TYPE_FLAT = 0,
TEST_TYPE_NOPERSPECTIVE,
TEST_TYPE_RELAXEDPRECISION,
TEST_TYPE_LAST
};
struct TestParameters
{
TestParameters (TestType q, size_t s)
:testOptions (s)
,qualifier (q)
{}
vector<int> testOptions;
TestType qualifier;
};
VkBufferCreateInfo makeBufferCreateInfo (const VkDeviceSize bufferSize, const VkBufferUsageFlags usage)
{
const VkBufferCreateInfo bufferCreateInfo =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkBufferCreateFlags)0, // VkBufferCreateFlags flags;
bufferSize, // VkDeviceSize size;
usage, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
0u, // deUint32 queueFamilyIndexCount;
DE_NULL, // const deUint32* pQueueFamilyIndices;
};
return bufferCreateInfo;
}
VkImageCreateInfo makeImageCreateInfo (const VkImageType imageType, const VkExtent3D& extent, const VkFormat format, const VkImageUsageFlags usage, deUint32 queueFamilyIndex)
{
const VkImageCreateInfo imageInfo =
{
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkImageCreateFlags)0, // VkImageCreateFlags flags;
imageType, // VkImageType imageType;
format, // VkFormat format;
{extent.width, extent.height, 1u}, // VkExtent3D extent;
1u, // uint32_t mipLevels;
extent.depth, // uint32_t arrayLayers;
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples;
VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling;
usage, // VkImageUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // uint32_t queueFamilyIndexCount;
&queueFamilyIndex, // const uint32_t* pQueueFamilyIndices;
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout;
};
return imageInfo;
}
Move<VkImageView> makeImageView (const DeviceInterface& vk,
const VkDevice device,
const VkImage image,
const VkImageViewType viewType,
const VkFormat format,
const VkImageSubresourceRange subresourceRange)
{
const VkImageViewCreateInfo imageViewParams =
{
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkImageViewCreateFlags)0, // VkImageViewCreateFlags flags;
image, // VkImage image;
viewType, // VkImageViewType viewType;
format, // VkFormat format;
makeComponentMappingRGBA(), // VkComponentMapping components;
subresourceRange, // VkImageSubresourceRange subresourceRange;
};
return createImageView(vk, device, &imageViewParams);
}
Move<VkFramebuffer> makeFramebuffer (const DeviceInterface& vk,
const VkDevice device,
const VkRenderPass renderPass,
const VkImageView attachments,
const deUint32 width,
const deUint32 height)
{
const VkFramebufferCreateInfo framebufferInfo =
{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkFramebufferCreateFlags)0, // VkFramebufferCreateFlags flags;
renderPass, // VkRenderPass renderPass;
1u, // uint32_t attachmentCount;
&attachments, // const VkImageView* pAttachments;
width, // uint32_t width;
height, // uint32_t height;
1u, // uint32_t layers;
};
return createFramebuffer(vk, device, &framebufferInfo);
}
Move<VkPipelineLayout> makePipelineLayout (const DeviceInterface& vk,
const VkDevice device)
{
VkPipelineLayoutCreateInfo pipelineLayoutParams =
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineLayoutCreateFlags)0,
0u, // deUint32 descriptorSetCount;
DE_NULL, // const VkDescriptorSetLayout* pSetLayouts;
0u, // deUint32 pushConstantRangeCount;
DE_NULL, // const VkPushConstantRange* pPushConstantRanges;
};
return createPipelineLayout(vk, device, &pipelineLayoutParams);
}
void imageBarrier (const DeviceInterface& vk,
const VkCommandBuffer cmdBuffer,
const VkImage image,
const VkImageSubresourceRange subresourceRange,
const VkImageLayout oldLayout,
const VkImageLayout newLayout,
const VkAccessFlags srcAccessMask,
const VkAccessFlags dstAccessMask,
const VkPipelineStageFlags srcStageMask,
const VkPipelineStageFlags dstStageMask)
{
const VkImageMemoryBarrier barrier =
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType;
DE_NULL, // const void* pNext;
srcAccessMask, // VkAccessFlags srcAccessMask;
dstAccessMask, // VkAccessFlags dstAccessMask;
oldLayout, // VkImageLayout oldLayout;
newLayout, // VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex;
image, // VkImage image;
subresourceRange, // VkImageSubresourceRange subresourceRange;
};
vk.cmdPipelineBarrier(cmdBuffer, srcStageMask, dstStageMask, (VkDependencyFlags)0, 0u, (const VkMemoryBarrier*)DE_NULL,
0u, (const VkBufferMemoryBarrier*)DE_NULL,
1u, &barrier);
}
class CrossStageTestInstance : public TestInstance
{
public:
CrossStageTestInstance (Context& context, const TestParameters& parameters)
: TestInstance (context)
, m_parameters (parameters)
, m_verticesCount (4u)
, m_data (2u * m_verticesCount)
, m_colorFormat (VK_FORMAT_R8G8B8A8_UNORM)
, m_colorRed (1.0f, 0.0f, 0.0f, 1.0f)
, m_colorGreen (0.0f, 1.0f, 0.0f, 1.0f)
{
createVertexData();
m_extent.width = 51u;
m_extent.height = 51u;
m_extent.depth = 1u;
}
enum
{
DECORATION_IN_VERTEX = 0,
DECORATION_IN_FRAGMENT,
DECORATION_IN_ALL_SHADERS,
DECORATION_LAST
};
protected:
tcu::TestStatus iterate (void);
private:
void createVertexData (void);
void makeShaderModule (map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModule,
const VkShaderStageFlagBits stageFlag,
const int optionNdx);
Move<VkPipeline> makeGraphicsPipeline (const VkRenderPass renderPass,
const VkPipelineLayout pipelineLayout,
const VkShaderStageFlagBits stageFlags,
map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModules,
const VkPrimitiveTopology primitiveTopology);
bool checkImage (VkImage image,
VkCommandBuffer cmdBuffer,
const string& description,
const tcu::Texture2DArray& referenceFrame);
void interpolationFill (tcu::Texture2DArray& referenceFrame);
void perspectiveFill (tcu::Texture2DArray& referenceFrame);
void redFill (tcu::Texture2DArray& referenceFrame);
const TestParameters m_parameters;
const deUint32 m_verticesCount;
vector<Vec4> m_data;
VkExtent3D m_extent;
const VkFormat m_colorFormat;
const Vec4 m_colorRed;
const Vec4 m_colorGreen;
};
tcu::TestStatus CrossStageTestInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const VkPhysicalDeviceFeatures& features = m_context.getDeviceFeatures();
const bool supportsGeometry = features.geometryShader == VK_TRUE;
const bool supportsTessellation = features.tessellationShader == VK_TRUE;
const VkDeviceSize vertexDataSize = static_cast<VkDeviceSize>(deAlignSize(static_cast<size_t>( m_data.size() * sizeof(Vec4)),
static_cast<size_t>(m_context.getDeviceProperties().limits.nonCoherentAtomSize)));
const VkBufferCreateInfo bufferInfo = makeBufferCreateInfo(vertexDataSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
Move<VkBuffer> vertexBuffer = createBuffer(vk, vkDevice, &bufferInfo);
MovePtr<Allocation> allocationVertex = m_context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *vertexBuffer), MemoryRequirement::HostVisible);
const VkImageSubresourceRange imageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
const VkImageCreateInfo colorAttachmentInfo = makeImageCreateInfo(VK_IMAGE_TYPE_2D, m_extent, m_colorFormat,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, m_context.getUniversalQueueFamilyIndex());
Move<VkImage> colorAttachmentImage = createImage(vk, vkDevice, &colorAttachmentInfo);
MovePtr<Allocation> allocationAttachment = m_context.getDefaultAllocator().allocate(getImageMemoryRequirements(vk, vkDevice, *colorAttachmentImage), MemoryRequirement::Any);
VK_CHECK(vk.bindImageMemory(vkDevice, *colorAttachmentImage, allocationAttachment->getMemory(), allocationAttachment->getOffset()));
Move<VkImageView> colorAttachmentView = makeImageView(vk, vkDevice, *colorAttachmentImage, VK_IMAGE_VIEW_TYPE_2D, m_colorFormat, imageSubresourceRange);
MovePtr<tcu::Texture2DArray> referenceImage1 = MovePtr<tcu::Texture2DArray>(new tcu::Texture2DArray(mapVkFormat(m_colorFormat), m_extent.width, m_extent.height, m_extent.depth));
MovePtr<tcu::Texture2DArray> referenceImage2 = MovePtr<tcu::Texture2DArray>(new tcu::Texture2DArray(mapVkFormat(m_colorFormat), m_extent.width, m_extent.height, m_extent.depth));
// Init host buffer data
VK_CHECK(vk.bindBufferMemory(vkDevice, *vertexBuffer, allocationVertex->getMemory(), allocationVertex->getOffset()));
deMemcpy(allocationVertex->getHostPtr(), m_data.data(), static_cast<size_t>(vertexDataSize));
flushAlloc(vk, vkDevice, *allocationVertex);
Move<VkRenderPass> renderPass = makeRenderPass (vk, vkDevice, m_colorFormat);
Move<VkFramebuffer> frameBuffer = makeFramebuffer (vk, vkDevice, *renderPass, *colorAttachmentView, m_extent.width, m_extent.height);
Move<VkPipelineLayout> pipelineLayout = makePipelineLayout (vk, vkDevice);
Move<VkCommandPool> cmdPool;
Move<VkCommandBuffer> cmdBuffer;
// cmdPool
{
const VkCommandPoolCreateInfo cmdPoolParams =
{
VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCmdPoolCreateFlags flags;
m_context.getUniversalQueueFamilyIndex(), // deUint32 queueFamilyIndex;
};
cmdPool = createCommandPool(vk, vkDevice, &cmdPoolParams);
}
// cmdBuffer
{
const VkCommandBufferAllocateInfo cmdBufferAllocateInfo =
{
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*cmdPool, // VkCommandPool commandPool;
VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level;
1u, // deUint32 bufferCount;
};
cmdBuffer = allocateCommandBuffer(vk, vkDevice, &cmdBufferAllocateInfo);
}
if (!supportsTessellation)
m_context.getTestContext().getLog() << tcu::TestLog::Message << "Tessellation not supported" << tcu::TestLog::EndMessage;
if (!supportsGeometry)
m_context.getTestContext().getLog() << tcu::TestLog::Message << "Geometry not supported" << tcu::TestLog::EndMessage;
vector<deUint32> shadersStagesFlagsBits;
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
if (supportsTessellation)
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
if (supportsGeometry)
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
if (supportsTessellation && supportsGeometry)
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
referenceImage1->allocLevel(0);
referenceImage2->allocLevel(0);
switch(m_parameters.qualifier)
{
case TEST_TYPE_FLAT:
interpolationFill(*referenceImage1);
redFill(*referenceImage2);
break;
case TEST_TYPE_NOPERSPECTIVE:
perspectiveFill(*referenceImage1);
interpolationFill(*referenceImage2);
break;
case TEST_TYPE_RELAXEDPRECISION:
interpolationFill(*referenceImage1);
interpolationFill(*referenceImage2);
break;
default:
DE_ASSERT(0);
}
for (deUint32 optionNdx = 0; optionNdx < m_parameters.testOptions.size(); optionNdx++)
for (size_t stagesNdx = 0ull; stagesNdx < shadersStagesFlagsBits.size(); stagesNdx++)
{
map<VkShaderStageFlagBits, ShaderModuleSP> shaderModule;
string imageDescription;
const VkClearValue renderPassClearValue = makeClearValueColor(tcu::Vec4(0.0f));
makeShaderModule(shaderModule, (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx], optionNdx);
Move<VkPipeline> graphicsPipeline = makeGraphicsPipeline (*renderPass, *pipelineLayout, (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx], shaderModule, ((VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx] & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) ? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST : VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP);
const VkDeviceSize vertexBufferOffset = 0u;
beginCommandBuffer(vk, *cmdBuffer);
imageBarrier(vk, *cmdBuffer, *colorAttachmentImage, imageSubresourceRange,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
0u, 0u,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
vk.cmdClearColorImage(*cmdBuffer, *colorAttachmentImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &renderPassClearValue.color, 1, &imageSubresourceRange);
imageBarrier(vk, *cmdBuffer, *colorAttachmentImage, imageSubresourceRange,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
beginRenderPass(vk, *cmdBuffer, *renderPass, *frameBuffer, makeRect2D(0, 0, m_extent.width, m_extent.height), tcu::Vec4(0.0f));
vk.cmdBindVertexBuffers(*cmdBuffer, 0u, 1u, &(*vertexBuffer), &vertexBufferOffset);
vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *graphicsPipeline);
vk.cmdDraw(*cmdBuffer, m_verticesCount, 1u, 0u, 0u);
endRenderPass(vk, *cmdBuffer);
endCommandBuffer(vk, *cmdBuffer);
submitCommandsAndWait(vk, vkDevice, m_context.getUniversalQueue(), *cmdBuffer);
{
const string geometry = (VK_SHADER_STAGE_GEOMETRY_BIT & (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx]) ? "Geometry->" : "";
const string tessellation = ( VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT & (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx]) ? "Tessellation->" : "";
imageDescription = "Pipeline: Vertex->" + tessellation + geometry + "Fragment | ";
}
if (DECORATION_IN_VERTEX == m_parameters.testOptions[optionNdx])
imageDescription+= "decoration in vertex | ";
if (DECORATION_IN_FRAGMENT == m_parameters.testOptions[optionNdx])
imageDescription+= "decoration in fragment | ";
if (DECORATION_IN_ALL_SHADERS == m_parameters.testOptions[optionNdx])
imageDescription+= "decoration in all shaders | ";
{
bool resultComparison = false;
if (TEST_TYPE_RELAXEDPRECISION == m_parameters.qualifier)
{
resultComparison = checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Pass", *referenceImage1);
}
else
{
if (DECORATION_IN_VERTEX == m_parameters.testOptions[optionNdx])
resultComparison = checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Pass", *referenceImage1);
else if ((VkShaderStageFlagBits)(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT) == (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx])
resultComparison = checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Pass", *referenceImage2);
else
resultComparison = !checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Fail", *referenceImage1);
}
if(!resultComparison)
return tcu::TestStatus::fail("Fail");
}
}
return tcu::TestStatus::pass("Pass");
}
void CrossStageTestInstance::createVertexData (void)
{
int ndx = -1;
if (TEST_TYPE_NOPERSPECTIVE == m_parameters.qualifier)
m_data[++ndx] = Vec4(-2.0f,-2.0f, 1.0f, 2.0f); //position
else
m_data[++ndx] = Vec4(-1.0f,-1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorRed;
if (TEST_TYPE_NOPERSPECTIVE == m_parameters.qualifier)
m_data[++ndx] = Vec4(-2.0f, 2.0f, 1.0f, 2.0f); //position
else
m_data[++ndx] = Vec4(-1.0f, 1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorRed;
m_data[++ndx] = Vec4( 1.0f,-1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorGreen;
m_data[++ndx] = Vec4( 1.0f, 1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorGreen;
}
void CrossStageTestInstance::makeShaderModule (map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModule,
const VkShaderStageFlagBits stageFlag,
const int optionNdx)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
std::ostringstream vertex;
vertex<<"vertex"<<optionNdx;
std::ostringstream fragment;
fragment<<"fragment"<<optionNdx;
if (stageFlag & VK_SHADER_STAGE_VERTEX_BIT)
shaderModule[VK_SHADER_STAGE_VERTEX_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get(vertex.str()), 0))));
if (stageFlag & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT)
shaderModule[VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("tessellation_control"), 0))));
if (stageFlag & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
shaderModule[VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("tessellation_evaluation"), 0))));
if (stageFlag & VK_SHADER_STAGE_GEOMETRY_BIT)
shaderModule[VK_SHADER_STAGE_GEOMETRY_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("geometry"), 0))));
if (stageFlag & VK_SHADER_STAGE_FRAGMENT_BIT)
shaderModule[VK_SHADER_STAGE_FRAGMENT_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get(fragment.str()), 0))));
}
Move<VkPipeline> CrossStageTestInstance::makeGraphicsPipeline (const VkRenderPass renderPass,
const VkPipelineLayout pipelineLayout,
const VkShaderStageFlagBits shaderFlags,
map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModules,
const VkPrimitiveTopology primitiveTopology)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const VkVertexInputBindingDescription vertexInputBindingDescription =
{
0u, // binding;
static_cast<deUint32>(2u*sizeof(Vec4)), // stride;
VK_VERTEX_INPUT_RATE_VERTEX // inputRate
};
const VkVertexInputAttributeDescription vertexInputAttributeDescriptions[] =
{
{
0u,
0u,
VK_FORMAT_R32G32B32A32_SFLOAT,
0u
}, // VertexElementData::position
{
1u,
0u,
VK_FORMAT_R32G32B32A32_SFLOAT,
static_cast<deUint32>(sizeof(tcu::Vec4))
}, // VertexElementData::color
};
const VkPipelineVertexInputStateCreateInfo vertexInputStateParams =
{ // sType;
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // pNext;
NULL, // flags;
0u, // vertexBindingDescriptionCount;
1u, // pVertexBindingDescriptions;
&vertexInputBindingDescription, // vertexAttributeDescriptionCount;
2u, // pVertexAttributeDescriptions;
vertexInputAttributeDescriptions
};
const std::vector<VkViewport> viewports (1, makeViewport(m_extent));
const std::vector<VkRect2D> scissors (1, makeRect2D(m_extent));
VkPipelineDepthStencilStateCreateInfo depthStencilStateParams =
{
VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkPipelineDepthStencilStateCreateFlags flags;
VK_TRUE, // VkBool32 depthTestEnable;
VK_TRUE, // VkBool32 depthWriteEnable;
VK_COMPARE_OP_LESS_OR_EQUAL, // VkCompareOp depthCompareOp;
VK_FALSE, // VkBool32 depthBoundsTestEnable;
VK_FALSE, // VkBool32 stencilTestEnable;
// VkStencilOpState front;
{
VK_STENCIL_OP_KEEP, // VkStencilOp failOp;
VK_STENCIL_OP_KEEP, // VkStencilOp passOp;
VK_STENCIL_OP_KEEP, // VkStencilOp depthFailOp;
VK_COMPARE_OP_NEVER, // VkCompareOp compareOp;
0u, // deUint32 compareMask;
0u, // deUint32 writeMask;
0u, // deUint32 reference;
},
// VkStencilOpState back;
{
VK_STENCIL_OP_KEEP, // VkStencilOp failOp;
VK_STENCIL_OP_KEEP, // VkStencilOp passOp;
VK_STENCIL_OP_KEEP, // VkStencilOp depthFailOp;
VK_COMPARE_OP_NEVER, // VkCompareOp compareOp;
0u, // deUint32 compareMask;
0u, // deUint32 writeMask;
0u, // deUint32 reference;
},
0.0f, // float minDepthBounds;
1.0f, // float maxDepthBounds;
};
const VkShaderModule vertShader = shaderFlags & VK_SHADER_STAGE_VERTEX_BIT ? **shaderModules[VK_SHADER_STAGE_VERTEX_BIT] : DE_NULL;
const VkShaderModule tessControlShader = shaderFlags & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ? **shaderModules[VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT] : DE_NULL;
const VkShaderModule tessEvalShader = shaderFlags & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT ? **shaderModules[VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT] : DE_NULL;
const VkShaderModule geomShader = shaderFlags & VK_SHADER_STAGE_GEOMETRY_BIT ? **shaderModules[VK_SHADER_STAGE_GEOMETRY_BIT] : DE_NULL;
const VkShaderModule fragShader = shaderFlags & VK_SHADER_STAGE_FRAGMENT_BIT ? **shaderModules[VK_SHADER_STAGE_FRAGMENT_BIT] : DE_NULL;
return vk::makeGraphicsPipeline(vk, // const DeviceInterface& vk
vkDevice, // const VkDevice device
pipelineLayout, // const VkPipelineLayout pipelineLayout
vertShader, // const VkShaderModule vertexShaderModule
tessControlShader, // const VkShaderModule tessellationControlShaderModule
tessEvalShader, // const VkShaderModule tessellationEvalShaderModule
geomShader, // const VkShaderModule geometryShaderModule
fragShader, // const VkShaderModule fragmentShaderModule
renderPass, // const VkRenderPass renderPass
viewports, // const std::vector<VkViewport>& viewports
scissors, // const std::vector<VkRect2D>& scissors
primitiveTopology, // const VkPrimitiveTopology topology
0u, // const deUint32 subpass
4u, // const deUint32 patchControlPoints
&vertexInputStateParams, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo
DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo
DE_NULL, // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo
&depthStencilStateParams); // const VkPipelineDepthStencilStateCreateInfo* depthStencilStateCreateInfo
}
bool CrossStageTestInstance::checkImage (VkImage image, VkCommandBuffer cmdBuffer, const string& description, const tcu::Texture2DArray& referenceFrame)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const int pixelSize = referenceFrame.getFormat().getPixelSize();
Move<VkBuffer> buffer;
MovePtr<Allocation> bufferAlloc;
vector<deUint8> pixelAccessData (m_extent.width * m_extent.height * m_extent.depth * pixelSize);
tcu::PixelBufferAccess dst (referenceFrame.getFormat(), m_extent.width, m_extent.height, m_extent.depth, pixelAccessData.data());
const VkDeviceSize pixelDataSize = dst.getWidth() * dst.getHeight() * dst.getDepth() * pixelSize;
// Create destination buffer
{
const VkBufferCreateInfo bufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
pixelDataSize, // VkDeviceSize size;
VK_BUFFER_USAGE_TRANSFER_DST_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
0u, // deUint32 queueFamilyIndexCount;
DE_NULL, // const deUint32* pQueueFamilyIndices;
};
buffer = createBuffer(vk, vkDevice, &bufferParams);
bufferAlloc = m_context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *buffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(vkDevice, *buffer, bufferAlloc->getMemory(), bufferAlloc->getOffset()));
deMemset(bufferAlloc->getHostPtr(), 0, static_cast<size_t>(pixelDataSize));
flushAlloc(vk, vkDevice, *bufferAlloc);
}
beginCommandBuffer (vk, cmdBuffer);
copyImageToBuffer(vk, cmdBuffer, image, *buffer, tcu::IVec2(m_extent.width, m_extent.height), 0u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, m_extent.depth);
endCommandBuffer(vk, cmdBuffer);
submitCommandsAndWait(vk, vkDevice, m_context.getUniversalQueue(), cmdBuffer);
// Read buffer data
invalidateAlloc(vk, vkDevice, *bufferAlloc);
tcu::copy(dst, tcu::ConstPixelBufferAccess(dst.getFormat(), dst.getSize(), bufferAlloc->getHostPtr()));
if (tcu::floatThresholdCompare(m_context.getTestContext().getLog(), "Result", description.c_str(), referenceFrame.getLevel(0), dst, tcu::Vec4(0.05f), tcu::COMPARE_LOG_EVERYTHING))
return true;
return false;
}
void CrossStageTestInstance::interpolationFill (tcu::Texture2DArray& referenceFrame)
{
for (deUint32 x = 0u; x < m_extent.width; ++x)
{
float u = static_cast<float>(x)/static_cast<float>(m_extent.width - 1);
const Vec4 resultColor (m_colorRed.x() * (1.0f - u) + m_colorGreen.x() * u,
m_colorRed.y() * (1.0f - u) + m_colorGreen.y() * u,
m_colorRed.z() * (1.0f - u) + m_colorGreen.z() * u,
m_colorRed.w() * (1.0f - u) + m_colorGreen.w() * u);
referenceFrame.getLevel(0).setPixel(resultColor,x,0);
}
for (deUint32 y = 0u; y < m_extent.height; ++y)
{
deMemcpy (referenceFrame.getLevel(0).getPixelPtr(0,y), referenceFrame.getLevel(0).getPixelPtr(0,0), m_extent.width * m_extent.depth* referenceFrame.getFormat().getPixelSize());
}
}
void CrossStageTestInstance::perspectiveFill (tcu::Texture2DArray& referenceFrame)
{
float dynamics = 1.732f;
float dynamicChange = 0.732f / static_cast<float>(m_extent.width);
for (deUint32 x = 0u; x < m_extent.width; ++x)
{
float u = static_cast<float>(x)/static_cast<float>(m_extent.width - 1);
const Vec4 resultColor (m_colorRed.x() * (1.0f - dynamics * u) + m_colorGreen.x() * u* dynamics,
m_colorRed.y() * (1.0f - dynamics * u) + m_colorGreen.y() * u* dynamics,
m_colorRed.z() * (1.0f - dynamics * u) + m_colorGreen.z() * u* dynamics,
m_colorRed.w() * (1.0f - dynamics * u) + m_colorGreen.w() * u* dynamics);
dynamics -= dynamicChange;
if (dynamics < 1.0f)
dynamics = 1.0f;
referenceFrame.getLevel(0).setPixel(resultColor,x,0);
}
for (deUint32 y = 0u; y < m_extent.height; ++y)
{
deMemcpy (referenceFrame.getLevel(0).getPixelPtr(0,y), referenceFrame.getLevel(0).getPixelPtr(0,0), m_extent.width * m_extent.depth* referenceFrame.getFormat().getPixelSize());
}
}
void CrossStageTestInstance::redFill (tcu::Texture2DArray& referenceFrame)
{
for (deUint32 x = 0u; x < m_extent.width; ++x)
referenceFrame.getLevel(0).setPixel(m_colorRed,x,0);
for (deUint32 y = 0u; y < m_extent.height; ++y)
deMemcpy (referenceFrame.getLevel(0).getPixelPtr(0,y), referenceFrame.getLevel(0).getPixelPtr(0,0), m_extent.width * m_extent.depth* referenceFrame.getFormat().getPixelSize());
}
struct Decorations
{
Decorations()
{};
Decorations(const string& f, const string& v, const string& o)
: fragment (f)
, vertex (v)
, others (o)
{};
string fragment;
string vertex;
string others;
};
class CrossStageBasicTestsCase : public vkt::TestCase
{
public:
CrossStageBasicTestsCase (tcu::TestContext &context, const char *name, const char *description, const TestParameters& parameters)
: TestCase (context, name, description)
, m_parameters (parameters)
{
}
private:
vkt::TestInstance* createInstance (vkt::Context& context) const;
void initPrograms (SourceCollections& programCollection) const;
const TestParameters m_parameters;
};
vkt::TestInstance* CrossStageBasicTestsCase::createInstance (vkt::Context& context) const
{
return new CrossStageTestInstance(context, m_parameters);
}
void CrossStageBasicTestsCase::initPrograms (SourceCollections& programCollection) const
{
vector<Decorations> decorations;
string epsilon = "6e-8";
switch(m_parameters.qualifier)
{
case TEST_TYPE_FLAT:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_out Flat\n"
"OpDecorate %rg_float_out Flat\n"
"OpDecorate %rgb_float_out Flat\n"
"OpDecorate %rgba_float_out Flat\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_in Flat\n"
"OpDecorate %rg_float_in Flat\n"
"OpDecorate %rgb_float_in Flat\n"
"OpDecorate %rgba_float_in Flat\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_in Flat\n"
"OpDecorate %rg_float_in Flat\n"
"OpDecorate %rgb_float_in Flat\n"
"OpDecorate %rgba_float_in Flat\n",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_out Flat\n"
"OpDecorate %rg_float_out Flat\n"
"OpDecorate %rgb_float_out Flat\n"
"OpDecorate %rgba_float_out Flat\n",
""));
epsilon = "0.0";
break;
case TEST_TYPE_NOPERSPECTIVE:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_out NoPerspective\n"
"OpDecorate %rg_float_out NoPerspective\n"
"OpDecorate %rgb_float_out NoPerspective\n"
"OpDecorate %rgba_float_out NoPerspective\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_in NoPerspective\n"
"OpDecorate %rg_float_in NoPerspective\n"
"OpDecorate %rgb_float_in NoPerspective\n"
"OpDecorate %rgba_float_in NoPerspective\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_in NoPerspective\n"
"OpDecorate %rg_float_in NoPerspective\n"
"OpDecorate %rgb_float_in NoPerspective\n"
"OpDecorate %rgba_float_in NoPerspective\n",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_out NoPerspective\n"
"OpDecorate %rg_float_out NoPerspective\n"
"OpDecorate %rgb_float_out NoPerspective\n"
"OpDecorate %rgba_float_out NoPerspective\n",
//Others
""));
break;
case TEST_TYPE_RELAXEDPRECISION:
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %r_float_in RelaxedPrecision\n"
"OpDecorate %rg_float_in RelaxedPrecision\n"
"OpDecorate %rgb_float_in RelaxedPrecision\n"
"OpDecorate %rgba_float_in RelaxedPrecision\n",
//Vertex
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %r_float_out RelaxedPrecision\n"
"OpDecorate %rg_float_out RelaxedPrecision\n"
"OpDecorate %rgb_float_out RelaxedPrecision\n"
"OpDecorate %rgba_float_out RelaxedPrecision\n",
//Others
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %r_float_out RelaxedPrecision\n"
"OpDecorate %rg_float_out RelaxedPrecision\n"
"OpDecorate %rgb_float_out RelaxedPrecision\n"
"OpDecorate %rgba_float_out RelaxedPrecision\n"
"OpDecorate %r_float_in RelaxedPrecision\n"
"OpDecorate %rg_float_in RelaxedPrecision\n"
"OpDecorate %rgb_float_in RelaxedPrecision\n"
"OpDecorate %rgba_float_in RelaxedPrecision\n"));
break;
default:
DE_ASSERT(0);
}
//Spir-v spec: decoration flat can be used only in Shader (fragment or vertex)
for (deUint32 ndx = 0; ndx < decorations.size(); ++ndx)
{
/*#version 450
layout(location = 0) in highp vec4 in_position;
layout(location = 1) in vec4 in_color;
layout(location = 0) out vec4 out_color;
layout(location = 1) out float r_float_out;
layout(location = 2) out vec2 rg_float_out;
layout(location = 3) out vec3 rgb_float_out;
layout(location = 4) out vec4 rgba_float_out;
void main (void)
{
gl_Position = in_position;
out_color = in_color;
r_float_out = in_color.r;
rg_float_out = vec2(in_color.r, in_color.g);
rgb_float_out = vec3(in_color.r, in_color.g,in_color.b);
rgba_float_out = vec4(in_color.r, in_color.g, in_color.b, in_color.a);
}
*/
const string vertexShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 60\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Vertex %4 \"main\" %13 %17 %color_out %color_in %r_float_out %rg_float_out %rgb_float_out %rgba_float_out\n"
"OpMemberDecorate %11 0 BuiltIn Position\n"
"OpMemberDecorate %11 1 BuiltIn PointSize\n"
"OpMemberDecorate %11 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %11 3 BuiltIn CullDistance\n"
"OpDecorate %11 Block\n"
"OpDecorate %17 Location 0\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 1\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
+decorations[ndx].vertex+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypeInt 32 0\n"
"%9 = OpConstant %8 1\n"
"%10 = OpTypeArray %6 %9\n"
"%11 = OpTypeStruct %7 %6 %10 %10\n"
"%12 = OpTypePointer Output %11\n"
"%13 = OpVariable %12 Output\n"
"%14 = OpTypeInt 32 1\n"
"%15 = OpConstant %14 0\n"
"%16 = OpTypePointer Input %7\n"
"%17 = OpVariable %16 Input\n"
"%19 = OpTypePointer Output %7\n"
"%color_out = OpVariable %19 Output\n"
"%color_in = OpVariable %16 Input\n"
"%24 = OpTypePointer Output %6\n"
"%r_float_out = OpVariable %24 Output\n"
"%26 = OpConstant %8 0\n"
"%27 = OpTypePointer Input %6\n"
"%30 = OpTypeVector %6 2\n"
"%31 = OpTypePointer Output %30\n"
"%rg_float_out = OpVariable %31 Output\n"
"%38 = OpTypeVector %6 3\n"
"%39 = OpTypePointer Output %38\n"
"%rgb_float_out = OpVariable %39 Output\n"
"%45 = OpConstant %8 2\n"
"%rgba_float_out = OpVariable %19 Output\n"
"%56 = OpConstant %8 3\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpLoad %7 %17\n"
"%20 = OpAccessChain %19 %13 %15\n"
"OpStore %20 %18\n"
"%23 = OpLoad %7 %color_in\n"
"OpStore %color_out %23\n"
"%28 = OpAccessChain %27 %color_in %26\n"
"%29 = OpLoad %6 %28\n"
"OpStore %r_float_out %29\n"
"%33 = OpAccessChain %27 %color_in %26\n"
"%34 = OpLoad %6 %33\n"
"%35 = OpAccessChain %27 %color_in %9\n"
"%36 = OpLoad %6 %35\n"
"%37 = OpCompositeConstruct %30 %34 %36\n"
"OpStore %rg_float_out %37\n"
"%41 = OpAccessChain %27 %color_in %26\n"
"%42 = OpLoad %6 %41\n"
"%43 = OpAccessChain %27 %color_in %9\n"
"%44 = OpLoad %6 %43\n"
"%46 = OpAccessChain %27 %color_in %45\n"
"%47 = OpLoad %6 %46\n"
"%48 = OpCompositeConstruct %38 %42 %44 %47\n"
"OpStore %rgb_float_out %48\n"
"%50 = OpAccessChain %27 %color_in %26\n"
"%51 = OpLoad %6 %50\n"
"%52 = OpAccessChain %27 %color_in %9\n"
"%53 = OpLoad %6 %52\n"
"%54 = OpAccessChain %27 %color_in %45\n"
"%55 = OpLoad %6 %54\n"
"%57 = OpAccessChain %27 %color_in %56\n"
"%58 = OpLoad %6 %57\n"
"%59 = OpCompositeConstruct %7 %51 %53 %55 %58\n"
"OpStore %rgba_float_out %59\n"
"OpReturn\n"
"OpFunctionEnd\n";
/* #version 450
layout(location = 0) out vec4 out_color;
layout(location = 0) in vec4 in_color;
layout(location = 1) in float r_float_in;
layout(location = 2) in vec2 rg_float_in;
layout(location = 3) in vec3 rgb_float_in;
layout(location = 4) in vec4 rgba_float_in;
void main()
{
float epsilon = 6e-8; // or 0.0 for flat
out_color = in_color;
if(abs(r_float_in - in_color.r) > epsilon)
out_color.r = 1.0f;
if(any(greaterThan(abs(rg_float_in - in_color.rg), vec2(epsilon))))
out_color.rg = vec2(1.0f);
if(any(greaterThan(abs(rgb_float_in - in_color.rgb), vec3(epsilon))))
out_color.rgb = vec3(1.0f);
if(any(greaterThan(abs(rgba_float_in - in_color.rgba), vec4(epsilon))))
out_color.rgba = vec4(1.0f);
}
*/
const string fragmentShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 64\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Fragment %4 \"main\" %color_out %color_in %r_float_in %rg_float_in %rgb_float_in %rgba_float_in\n"
"OpExecutionMode %4 OriginUpperLeft\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[ndx].fragment+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypePointer Input %7\n"
"%color_in = OpVariable %10 Input\n"
"%13 = OpTypePointer Input %6\n"
"%r_float_in = OpVariable %13 Input\n"
"%16 = OpTypeInt 32 0\n"
"%17 = OpConstant %16 0\n"
"%20 = OpTypeBool\n"
"%ep = OpConstant %6 " + epsilon + "\n"
"%24 = OpConstant %6 1\n"
"%25 = OpTypePointer Output %6\n"
"%27 = OpTypeVector %6 2\n"
"%28 = OpTypePointer Input %27\n"
"%rg_float_in = OpVariable %28 Input\n"
"%ep2 = OpConstantComposite %27 %ep %ep\n"
"%33 = OpTypeVector %20 2\n"
"%38 = OpConstantComposite %27 %24 %24\n"
"%41 = OpTypeVector %6 3\n"
"%42 = OpTypePointer Input %41\n"
"%rgb_float_in = OpVariable %42 Input\n"
"%ep3 = OpConstantComposite %41 %ep %ep %ep\n"
"%47 = OpTypeVector %20 3\n"
"%52 = OpConstantComposite %41 %24 %24 %24\n"
"%rgba_float_in = OpVariable %10 Input\n"
"%ep4 = OpConstantComposite %7 %ep %ep %ep %ep\n"
"%58 = OpTypeVector %20 4\n"
"%63 = OpConstantComposite %7 %24 %24 %24 %24\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%12 = OpLoad %7 %color_in\n"
"OpStore %color_out %12\n"
"%15 = OpLoad %6 %r_float_in\n"
"%18 = OpAccessChain %13 %color_in %17\n"
"%19 = OpLoad %6 %18\n"
"%sub = OpFSub %6 %15 %19\n"
"%abs = OpExtInst %6 %1 FAbs %sub\n"
"%cmp = OpFOrdGreaterThan %20 %abs %ep\n"
"OpSelectionMerge %23 None\n"
"OpBranchConditional %cmp %22 %23\n"
"%22 = OpLabel\n"
"%26 = OpAccessChain %25 %color_out %17\n"
"OpStore %26 %24\n"
"OpBranch %23\n"
"%23 = OpLabel\n"
"%30 = OpLoad %27 %rg_float_in\n"
"%31 = OpLoad %7 %color_in\n"
"%32 = OpVectorShuffle %27 %31 %31 0 1\n"
"%sub2 = OpFSub %27 %30 %32\n"
"%abs2 = OpExtInst %27 %1 FAbs %sub2\n"
"%cmp2 = OpFOrdGreaterThan %33 %abs2 %ep2\n"
"%35 = OpAny %20 %cmp2\n"
"OpSelectionMerge %37 None\n"
"OpBranchConditional %35 %36 %37\n"
"%36 = OpLabel\n"
"%39 = OpLoad %7 %color_out\n"
"%40 = OpVectorShuffle %7 %39 %38 4 5 2 3\n"
"OpStore %color_out %40\n"
"OpBranch %37\n"
"%37 = OpLabel\n"
"%44 = OpLoad %41 %rgb_float_in\n"
"%45 = OpLoad %7 %color_in\n"
"%46 = OpVectorShuffle %41 %45 %45 0 1 2\n"
"%sub3 = OpFSub %41 %44 %46\n"
"%abs3 = OpExtInst %41 %1 FAbs %sub3\n"
"%cmp3 = OpFOrdGreaterThan %47 %abs3 %ep3\n"
"%49 = OpAny %20 %cmp3\n"
"OpSelectionMerge %51 None\n"
"OpBranchConditional %49 %50 %51\n"
"%50 = OpLabel\n"
"%53 = OpLoad %7 %color_out\n"
"%54 = OpVectorShuffle %7 %53 %52 4 5 6 3\n"
"OpStore %color_out %54\n"
"OpBranch %51\n"
"%51 = OpLabel\n"
"%56 = OpLoad %7 %rgba_float_in\n"
"%57 = OpLoad %7 %color_in\n"
"%sub4 = OpFSub %7 %56 %57\n"
"%abs4 = OpExtInst %7 %1 FAbs %sub4\n"
"%cmp4 = OpFOrdGreaterThan %58 %abs4 %ep4\n"
"%60 = OpAny %20 %cmp4\n"
"OpSelectionMerge %62 None\n"
"OpBranchConditional %60 %61 %62\n"
"%61 = OpLabel\n"
"OpStore %color_out %63\n"
"OpBranch %62\n"
"%62 = OpLabel\n"
"OpReturn\n"
"OpFunctionEnd\n";
std::ostringstream vertex;
vertex << "vertex" << ndx;
std::ostringstream fragment;
fragment << "fragment" << ndx;
programCollection.spirvAsmSources.add(vertex.str()) << vertexShaderSource;
programCollection.spirvAsmSources.add(fragment.str()) << fragmentShaderSource;
}
{
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout(vertices = 4) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in float r_float_in[];
layout(location = 2) in vec2 rg_float_in[];
layout(location = 3) in vec3 rgb_float_in[];
layout(location = 4) in vec4 rgba_float_in[];
layout(location = 0) out vec4 out_color[];
layout(location = 1) out float r_float_out[];
layout(location = 2) out vec2 rg_float_out[];
layout(location = 3) out vec3 rgb_float_out[];
layout(location = 4) out vec4 rgba_float_out[];
void main (void)
{
if ( gl_InvocationID == 0 )
{
gl_TessLevelInner[0] = 4.0f;
gl_TessLevelInner[1] = 4.0f;
gl_TessLevelOuter[0] = 4.0f;
gl_TessLevelOuter[1] = 4.0f;
gl_TessLevelOuter[2] = 4.0f;
gl_TessLevelOuter[3] = 4.0f;
}
out_color[gl_InvocationID] = in_color[gl_InvocationID];
r_float_out[gl_InvocationID] = r_float_in[gl_InvocationID];
rg_float_out[gl_InvocationID] = rg_float_in[gl_InvocationID];
rgb_float_out[gl_InvocationID] = rgb_float_in[gl_InvocationID];
rgba_float_out[gl_InvocationID] = rgba_float_in[gl_InvocationID];
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}*/
const string tessellationControlSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 111\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationControl %4 \"main\" %8 %20 %29 %color_out %color_in %r_float_out %r_float_in %rg_float_out %rg_float_in %rgb_float_out %rgb_float_in %rgba_float_out %rgba_float_in %101 %106\n"
"OpExecutionMode %4 OutputVertices 4\n"
"OpDecorate %8 BuiltIn InvocationId\n"
"OpDecorate %20 Patch\n"
"OpDecorate %20 BuiltIn TessLevelInner\n"
"OpDecorate %29 Patch\n"
"OpDecorate %29 BuiltIn TessLevelOuter\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[0].others+
"OpMemberDecorate %98 0 BuiltIn Position\n"
"OpMemberDecorate %98 1 BuiltIn PointSize\n"
"OpMemberDecorate %98 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %98 3 BuiltIn CullDistance\n"
"OpDecorate %98 Block\n"
"OpMemberDecorate %103 0 BuiltIn Position\n"
"OpMemberDecorate %103 1 BuiltIn PointSize\n"
"OpMemberDecorate %103 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %103 3 BuiltIn CullDistance\n"
"OpDecorate %103 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeInt 32 1\n"
"%7 = OpTypePointer Input %6\n"
"%8 = OpVariable %7 Input\n"
"%10 = OpConstant %6 0\n"
"%11 = OpTypeBool\n"
"%15 = OpTypeFloat 32\n"
"%16 = OpTypeInt 32 0\n"
"%17 = OpConstant %16 2\n"
"%18 = OpTypeArray %15 %17\n"
"%19 = OpTypePointer Output %18\n"
"%20 = OpVariable %19 Output\n"
"%21 = OpConstant %15 4\n"
"%22 = OpTypePointer Output %15\n"
"%24 = OpConstant %6 1\n"
"%26 = OpConstant %16 4\n"
"%27 = OpTypeArray %15 %26\n"
"%28 = OpTypePointer Output %27\n"
"%29 = OpVariable %28 Output\n"
"%32 = OpConstant %6 2\n"
"%34 = OpConstant %6 3\n"
"%36 = OpTypeVector %15 4\n"
"%37 = OpTypeArray %36 %26\n"
"%38 = OpTypePointer Output %37\n"
"%color_out = OpVariable %38 Output\n"
"%41 = OpConstant %16 32\n"
"%42 = OpTypeArray %36 %41\n"
"%43 = OpTypePointer Input %42\n"
"%color_in = OpVariable %43 Input\n"
"%46 = OpTypePointer Input %36\n"
"%49 = OpTypePointer Output %36\n"
"%r_float_out = OpVariable %28 Output\n"
"%53 = OpTypeArray %15 %41\n"
"%54 = OpTypePointer Input %53\n"
"%r_float_in = OpVariable %54 Input\n"
"%57 = OpTypePointer Input %15\n"
"%61 = OpTypeVector %15 2\n"
"%62 = OpTypeArray %61 %26\n"
"%63 = OpTypePointer Output %62\n"
"%rg_float_out = OpVariable %63 Output\n"
"%66 = OpTypeArray %61 %41\n"
"%67 = OpTypePointer Input %66\n"
"%rg_float_in = OpVariable %67 Input\n"
"%70 = OpTypePointer Input %61\n"
"%73 = OpTypePointer Output %61\n"
"%75 = OpTypeVector %15 3\n"
"%76 = OpTypeArray %75 %26\n"
"%77 = OpTypePointer Output %76\n"
"%rgb_float_out = OpVariable %77 Output\n"
"%80 = OpTypeArray %75 %41\n"
"%81 = OpTypePointer Input %80\n"
"%rgb_float_in = OpVariable %81 Input\n"
"%84 = OpTypePointer Input %75\n"
"%87 = OpTypePointer Output %75\n"
"%rgba_float_out = OpVariable %38 Output\n"
"%rgba_float_in = OpVariable %43 Input\n"
"%96 = OpConstant %16 1\n"
"%97 = OpTypeArray %15 %96\n"
"%98 = OpTypeStruct %36 %15 %97 %97\n"
"%99 = OpTypeArray %98 %26\n"
"%100 = OpTypePointer Output %99\n"
"%101 = OpVariable %100 Output\n"
"%103 = OpTypeStruct %36 %15 %97 %97\n"
"%104 = OpTypeArray %103 %41\n"
"%105 = OpTypePointer Input %104\n"
"%106 = OpVariable %105 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%9 = OpLoad %6 %8\n"
"%12 = OpIEqual %11 %9 %10\n"
"OpSelectionMerge %14 None\n"
"OpBranchConditional %12 %13 %14\n"
"%13 = OpLabel\n"
"%23 = OpAccessChain %22 %20 %10\n"
"OpStore %23 %21\n"
"%25 = OpAccessChain %22 %20 %24\n"
"OpStore %25 %21\n"
"%30 = OpAccessChain %22 %29 %10\n"
"OpStore %30 %21\n"
"%31 = OpAccessChain %22 %29 %24\n"
"OpStore %31 %21\n"
"%33 = OpAccessChain %22 %29 %32\n"
"OpStore %33 %21\n"
"%35 = OpAccessChain %22 %29 %34\n"
"OpStore %35 %21\n"
"OpBranch %14\n"
"%14 = OpLabel\n"
"%40 = OpLoad %6 %8\n"
"%45 = OpLoad %6 %8\n"
"%47 = OpAccessChain %46 %color_in %45\n"
"%48 = OpLoad %36 %47\n"
"%50 = OpAccessChain %49 %color_out %40\n"
"OpStore %50 %48\n"
"%52 = OpLoad %6 %8\n"
"%56 = OpLoad %6 %8\n"
"%58 = OpAccessChain %57 %r_float_in %56\n"
"%59 = OpLoad %15 %58\n"
"%60 = OpAccessChain %22 %r_float_out %52\n"
"OpStore %60 %59\n"
"%65 = OpLoad %6 %8\n"
"%69 = OpLoad %6 %8\n"
"%71 = OpAccessChain %70 %rg_float_in %69\n"
"%72 = OpLoad %61 %71\n"
"%74 = OpAccessChain %73 %rg_float_out %65\n"
"OpStore %74 %72\n"
"%79 = OpLoad %6 %8\n"
"%83 = OpLoad %6 %8\n"
"%85 = OpAccessChain %84 %rgb_float_in %83\n"
"%86 = OpLoad %75 %85\n"
"%88 = OpAccessChain %87 %rgb_float_out %79\n"
"OpStore %88 %86\n"
"%90 = OpLoad %6 %8\n"
"%92 = OpLoad %6 %8\n"
"%93 = OpAccessChain %46 %rgba_float_in %92\n"
"%94 = OpLoad %36 %93\n"
"%95 = OpAccessChain %49 %rgba_float_out %90\n"
"OpStore %95 %94\n"
"%102 = OpLoad %6 %8\n"
"%107 = OpLoad %6 %8\n"
"%108 = OpAccessChain %46 %106 %107 %10\n"
"%109 = OpLoad %36 %108\n"
"%110 = OpAccessChain %49 %101 %102 %10\n"
"OpStore %110 %109\n"
"OpReturn\n"
"OpFunctionEnd\n";
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout( quads, equal_spacing, ccw ) in;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in float r_float_in[];
layout(location = 2) in vec2 rg_float_in[];
layout(location = 3) in vec3 rgb_float_in[];
layout(location = 4) in vec4 rgba_float_in[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out float r_float_out;
layout(location = 2) out vec2 rg_float_out;
layout(location = 3) out vec3 rgb_float_out;
layout(location = 4) out vec4 rgba_float_out;
void main (void)
{
const float u = gl_TessCoord.x;
const float v = gl_TessCoord.y;
const float w = gl_TessCoord.z;
out_color = (1 - u) * (1 - v) * in_color[0] +(1 - u) * v * in_color[1] + u * (1 - v) * in_color[2] + u * v * in_color[3];
r_float_out = (1 - u) * (1 - v) * r_float_in[0] +(1 - u) * v * r_float_in[1] + u * (1 - v) * r_float_in[2] + u * v * r_float_in[3];
rg_float_out = (1 - u) * (1 - v) * rg_float_in[0] +(1 - u) * v * rg_float_in[1] + u * (1 - v) * rg_float_in[2] + u * v * rg_float_in[3];
rgb_float_out = (1 - u) * (1 - v) * rgb_float_in[0] +(1 - u) * v * rgb_float_in[1] + u * (1 - v) * rgb_float_in[2] + u * v * rgb_float_in[3];
rgba_float_out = (1 - u) * (1 - v) * rgba_float_in[0] +(1 - u) * v * rgba_float_in[1] + u * (1 - v) * rgba_float_in[2] + u * v * rgba_float_in[3];
gl_Position = (1 - u) * (1 - v) * gl_in[0].gl_Position +(1 - u) * v * gl_in[1].gl_Position + u * (1 - v) * gl_in[2].gl_Position + u * v * gl_in[3].gl_Position;
}*/
const string tessellationEvaluationSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 253\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationEvaluation %4 \"main\" %11 %color_out %color_in %r_float_out %r_float_in %rg_float_out %rg_float_in %rgb_float_out %rgb_float_in %rgba_float_out %rgba_float_in %216 %225\n"
"OpExecutionMode %4 Quads\n"
"OpExecutionMode %4 SpacingEqual\n"
"OpExecutionMode %4 VertexOrderCcw\n"
"OpDecorate %11 BuiltIn TessCoord\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[0].others+
"OpMemberDecorate %214 0 BuiltIn Position\n"
"OpMemberDecorate %214 1 BuiltIn PointSize\n"
"OpMemberDecorate %214 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %214 3 BuiltIn CullDistance\n"
"OpDecorate %214 Block\n"
"OpMemberDecorate %222 0 BuiltIn Position\n"
"OpMemberDecorate %222 1 BuiltIn PointSize\n"
"OpMemberDecorate %222 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %222 3 BuiltIn CullDistance\n"
"OpDecorate %222 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypePointer Function %6\n"
"%9 = OpTypeVector %6 3\n"
"%10 = OpTypePointer Input %9\n"
"%11 = OpVariable %10 Input\n"
"%12 = OpTypeInt 32 0\n"
"%13 = OpConstant %12 0\n"
"%14 = OpTypePointer Input %6\n"
"%18 = OpConstant %12 1\n"
"%22 = OpConstant %12 2\n"
"%25 = OpTypeVector %6 4\n"
"%26 = OpTypePointer Output %25\n"
"%color_out = OpVariable %26 Output\n"
"%28 = OpConstant %6 1\n"
"%34 = OpConstant %12 32\n"
"%35 = OpTypeArray %25 %34\n"
"%36 = OpTypePointer Input %35\n"
"%color_in = OpVariable %36 Input\n"
"%38 = OpTypeInt 32 1\n"
"%39 = OpConstant %38 0\n"
"%40 = OpTypePointer Input %25\n"
"%48 = OpConstant %38 1\n"
"%57 = OpConstant %38 2\n"
"%65 = OpConstant %38 3\n"
"%70 = OpTypePointer Output %6\n"
"%r_float_out = OpVariable %70 Output\n"
"%77 = OpTypeArray %6 %34\n"
"%78 = OpTypePointer Input %77\n"
"%r_float_in = OpVariable %78 Input\n"
"%106 = OpTypeVector %6 2\n"
"%107 = OpTypePointer Output %106\n"
"%rg_float_out = OpVariable %107 Output\n"
"%114 = OpTypeArray %106 %34\n"
"%115 = OpTypePointer Input %114\n"
"%rg_float_in = OpVariable %115 Input\n"
"%117 = OpTypePointer Input %106\n"
"%144 = OpTypePointer Output %9\n"
"%rgb_float_out = OpVariable %144 Output\n"
"%151 = OpTypeArray %9 %34\n"
"%152 = OpTypePointer Input %151\n"
"%rgb_float_in = OpVariable %152 Input\n"
"%rgba_float_out = OpVariable %26 Output\n"
"%rgba_float_in = OpVariable %36 Input\n"
"%213 = OpTypeArray %6 %18\n"
"%214 = OpTypeStruct %25 %6 %213 %213\n"
"%215 = OpTypePointer Output %214\n"
"%216 = OpVariable %215 Output\n"
"%222 = OpTypeStruct %25 %6 %213 %213\n"
"%223 = OpTypeArray %222 %34\n"
"%224 = OpTypePointer Input %223\n"
"%225 = OpVariable %224 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%8 = OpVariable %7 Function\n"
"%17 = OpVariable %7 Function\n"
"%21 = OpVariable %7 Function\n"
"%15 = OpAccessChain %14 %11 %13\n"
"%16 = OpLoad %6 %15\n"
"OpStore %8 %16\n"
"%19 = OpAccessChain %14 %11 %18\n"
"%20 = OpLoad %6 %19\n"
"OpStore %17 %20\n"
"%23 = OpAccessChain %14 %11 %22\n"
"%24 = OpLoad %6 %23\n"
"OpStore %21 %24\n"
"%29 = OpLoad %6 %8\n"
"%30 = OpFSub %6 %28 %29\n"
"%31 = OpLoad %6 %17\n"
"%32 = OpFSub %6 %28 %31\n"
"%33 = OpFMul %6 %30 %32\n"
"%41 = OpAccessChain %40 %color_in %39\n"
"%42 = OpLoad %25 %41\n"
"%43 = OpVectorTimesScalar %25 %42 %33\n"
"%44 = OpLoad %6 %8\n"
"%45 = OpFSub %6 %28 %44\n"
"%46 = OpLoad %6 %17\n"
"%47 = OpFMul %6 %45 %46\n"
"%49 = OpAccessChain %40 %color_in %48\n"
"%50 = OpLoad %25 %49\n"
"%51 = OpVectorTimesScalar %25 %50 %47\n"
"%52 = OpFAdd %25 %43 %51\n"
"%53 = OpLoad %6 %8\n"
"%54 = OpLoad %6 %17\n"
"%55 = OpFSub %6 %28 %54\n"
"%56 = OpFMul %6 %53 %55\n"
"%58 = OpAccessChain %40 %color_in %57\n"
"%59 = OpLoad %25 %58\n"
"%60 = OpVectorTimesScalar %25 %59 %56\n"
"%61 = OpFAdd %25 %52 %60\n"
"%62 = OpLoad %6 %8\n"
"%63 = OpLoad %6 %17\n"
"%64 = OpFMul %6 %62 %63\n"
"%66 = OpAccessChain %40 %color_in %65\n"
"%67 = OpLoad %25 %66\n"
"%68 = OpVectorTimesScalar %25 %67 %64\n"
"%69 = OpFAdd %25 %61 %68\n"
"OpStore %color_out %69\n"
"%72 = OpLoad %6 %8\n"
"%73 = OpFSub %6 %28 %72\n"
"%74 = OpLoad %6 %17\n"
"%75 = OpFSub %6 %28 %74\n"
"%76 = OpFMul %6 %73 %75\n"
"%80 = OpAccessChain %14 %r_float_in %39\n"
"%81 = OpLoad %6 %80\n"
"%82 = OpFMul %6 %76 %81\n"
"%83 = OpLoad %6 %8\n"
"%84 = OpFSub %6 %28 %83\n"
"%85 = OpLoad %6 %17\n"
"%86 = OpFMul %6 %84 %85\n"
"%87 = OpAccessChain %14 %r_float_in %48\n"
"%88 = OpLoad %6 %87\n"
"%89 = OpFMul %6 %86 %88\n"
"%90 = OpFAdd %6 %82 %89\n"
"%91 = OpLoad %6 %8\n"
"%92 = OpLoad %6 %17\n"
"%93 = OpFSub %6 %28 %92\n"
"%94 = OpFMul %6 %91 %93\n"
"%95 = OpAccessChain %14 %r_float_in %57\n"
"%96 = OpLoad %6 %95\n"
"%97 = OpFMul %6 %94 %96\n"
"%98 = OpFAdd %6 %90 %97\n"
"%99 = OpLoad %6 %8\n"
"%100 = OpLoad %6 %17\n"
"%101 = OpFMul %6 %99 %100\n"
"%102 = OpAccessChain %14 %r_float_in %65\n"
"%103 = OpLoad %6 %102\n"
"%104 = OpFMul %6 %101 %103\n"
"%105 = OpFAdd %6 %98 %104\n"
"OpStore %r_float_out %105\n"
"%109 = OpLoad %6 %8\n"
"%110 = OpFSub %6 %28 %109\n"
"%111 = OpLoad %6 %17\n"
"%112 = OpFSub %6 %28 %111\n"
"%113 = OpFMul %6 %110 %112\n"
"%118 = OpAccessChain %117 %rg_float_in %39\n"
"%119 = OpLoad %106 %118\n"
"%120 = OpVectorTimesScalar %106 %119 %113\n"
"%121 = OpLoad %6 %8\n"
"%122 = OpFSub %6 %28 %121\n"
"%123 = OpLoad %6 %17\n"
"%124 = OpFMul %6 %122 %123\n"
"%125 = OpAccessChain %117 %rg_float_in %48\n"
"%126 = OpLoad %106 %125\n"
"%127 = OpVectorTimesScalar %106 %126 %124\n"
"%128 = OpFAdd %106 %120 %127\n"
"%129 = OpLoad %6 %8\n"
"%130 = OpLoad %6 %17\n"
"%131 = OpFSub %6 %28 %130\n"
"%132 = OpFMul %6 %129 %131\n"
"%133 = OpAccessChain %117 %rg_float_in %57\n"
"%134 = OpLoad %106 %133\n"
"%135 = OpVectorTimesScalar %106 %134 %132\n"
"%136 = OpFAdd %106 %128 %135\n"
"%137 = OpLoad %6 %8\n"
"%138 = OpLoad %6 %17\n"
"%139 = OpFMul %6 %137 %138\n"
"%140 = OpAccessChain %117 %rg_float_in %65\n"
"%141 = OpLoad %106 %140\n"
"%142 = OpVectorTimesScalar %106 %141 %139\n"
"%143 = OpFAdd %106 %136 %142\n"
"OpStore %rg_float_out %143\n"
"%146 = OpLoad %6 %8\n"
"%147 = OpFSub %6 %28 %146\n"
"%148 = OpLoad %6 %17\n"
"%149 = OpFSub %6 %28 %148\n"
"%150 = OpFMul %6 %147 %149\n"
"%154 = OpAccessChain %10 %rgb_float_in %39\n"
"%155 = OpLoad %9 %154\n"
"%156 = OpVectorTimesScalar %9 %155 %150\n"
"%157 = OpLoad %6 %8\n"
"%158 = OpFSub %6 %28 %157\n"
"%159 = OpLoad %6 %17\n"
"%160 = OpFMul %6 %158 %159\n"
"%161 = OpAccessChain %10 %rgb_float_in %48\n"
"%162 = OpLoad %9 %161\n"
"%163 = OpVectorTimesScalar %9 %162 %160\n"
"%164 = OpFAdd %9 %156 %163\n"
"%165 = OpLoad %6 %8\n"
"%166 = OpLoad %6 %17\n"
"%167 = OpFSub %6 %28 %166\n"
"%168 = OpFMul %6 %165 %167\n"
"%169 = OpAccessChain %10 %rgb_float_in %57\n"
"%170 = OpLoad %9 %169\n"
"%171 = OpVectorTimesScalar %9 %170 %168\n"
"%172 = OpFAdd %9 %164 %171\n"
"%173 = OpLoad %6 %8\n"
"%174 = OpLoad %6 %17\n"
"%175 = OpFMul %6 %173 %174\n"
"%176 = OpAccessChain %10 %rgb_float_in %65\n"
"%177 = OpLoad %9 %176\n"
"%178 = OpVectorTimesScalar %9 %177 %175\n"
"%179 = OpFAdd %9 %172 %178\n"
"OpStore %rgb_float_out %179\n"
"%181 = OpLoad %6 %8\n"
"%182 = OpFSub %6 %28 %181\n"
"%183 = OpLoad %6 %17\n"
"%184 = OpFSub %6 %28 %183\n"
"%185 = OpFMul %6 %182 %184\n"
"%187 = OpAccessChain %40 %rgba_float_in %39\n"
"%188 = OpLoad %25 %187\n"
"%189 = OpVectorTimesScalar %25 %188 %185\n"
"%190 = OpLoad %6 %8\n"
"%191 = OpFSub %6 %28 %190\n"
"%192 = OpLoad %6 %17\n"
"%193 = OpFMul %6 %191 %192\n"
"%194 = OpAccessChain %40 %rgba_float_in %48\n"
"%195 = OpLoad %25 %194\n"
"%196 = OpVectorTimesScalar %25 %195 %193\n"
"%197 = OpFAdd %25 %189 %196\n"
"%198 = OpLoad %6 %8\n"
"%199 = OpLoad %6 %17\n"
"%200 = OpFSub %6 %28 %199\n"
"%201 = OpFMul %6 %198 %200\n"
"%202 = OpAccessChain %40 %rgba_float_in %57\n"
"%203 = OpLoad %25 %202\n"
"%204 = OpVectorTimesScalar %25 %203 %201\n"
"%205 = OpFAdd %25 %197 %204\n"
"%206 = OpLoad %6 %8\n"
"%207 = OpLoad %6 %17\n"
"%208 = OpFMul %6 %206 %207\n"
"%209 = OpAccessChain %40 %rgba_float_in %65\n"
"%210 = OpLoad %25 %209\n"
"%211 = OpVectorTimesScalar %25 %210 %208\n"
"%212 = OpFAdd %25 %205 %211\n"
"OpStore %rgba_float_out %212\n"
"%217 = OpLoad %6 %8\n"
"%218 = OpFSub %6 %28 %217\n"
"%219 = OpLoad %6 %17\n"
"%220 = OpFSub %6 %28 %219\n"
"%221 = OpFMul %6 %218 %220\n"
"%226 = OpAccessChain %40 %225 %39 %39\n"
"%227 = OpLoad %25 %226\n"
"%228 = OpVectorTimesScalar %25 %227 %221\n"
"%229 = OpLoad %6 %8\n"
"%230 = OpFSub %6 %28 %229\n"
"%231 = OpLoad %6 %17\n"
"%232 = OpFMul %6 %230 %231\n"
"%233 = OpAccessChain %40 %225 %48 %39\n"
"%234 = OpLoad %25 %233\n"
"%235 = OpVectorTimesScalar %25 %234 %232\n"
"%236 = OpFAdd %25 %228 %235\n"
"%237 = OpLoad %6 %8\n"
"%238 = OpLoad %6 %17\n"
"%239 = OpFSub %6 %28 %238\n"
"%240 = OpFMul %6 %237 %239\n"
"%241 = OpAccessChain %40 %225 %57 %39\n"
"%242 = OpLoad %25 %241\n"
"%243 = OpVectorTimesScalar %25 %242 %240\n"
"%244 = OpFAdd %25 %236 %243\n"
"%245 = OpLoad %6 %8\n"
"%246 = OpLoad %6 %17\n"
"%247 = OpFMul %6 %245 %246\n"
"%248 = OpAccessChain %40 %225 %65 %39\n"
"%249 = OpLoad %25 %248\n"
"%250 = OpVectorTimesScalar %25 %249 %247\n"
"%251 = OpFAdd %25 %244 %250\n"
"%252 = OpAccessChain %26 %216 %39\n"
"OpStore %252 %251\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("tessellation_control") << tessellationControlSource;
programCollection.spirvAsmSources.add("tessellation_evaluation") << tessellationEvaluationSource;
}
{
/*#version 450
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in float r_float_in[];
layout(location = 2) in vec2 rg_float_in[];
layout(location = 3) in vec3 rgb_float_in[];
layout(location = 4) in vec4 rgba_float_in[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out float r_float_out;
layout(location = 2) out vec2 rg_float_out;
layout(location = 3) out vec3 rgb_float_out;
layout(location = 4) out vec4 rgba_float_out;
void main (void)
{
out_color = in_color[0];
r_float_out = r_float_in[0];
rg_float_out = rg_float_in[0];
rgb_float_out = rgb_float_in[0];
rgba_float_out = rgba_float_in[0];
gl_Position = gl_in[0].gl_Position;
EmitVertex();
out_color = in_color[1];
r_float_out = r_float_in[1];
rg_float_out = rg_float_in[1];
rgb_float_out = rgb_float_in[1];
rgba_float_out = rgba_float_in[1];
gl_Position = gl_in[1].gl_Position;
EmitVertex();
out_color = in_color[2];
r_float_out = r_float_in[2];
rg_float_out = rg_float_in[2];
rgb_float_out = rgb_float_in[2];
rgba_float_out = rgba_float_in[2];
gl_Position = gl_in[2].gl_Position;
EmitVertex();
EndPrimitive();
}
*/
const string geometrySource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 90\n"
"; Schema: 0\n"
"OpCapability Geometry\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Geometry %4 \"main\" %color_out %color_in %r_float_out %r_float_in %rg_float_out %rg_float_in %rgb_float_out %rgb_float_in %rgba_float_out %rgba_float_in %54 %58\n"
"OpExecutionMode %4 Triangles\n"
"OpExecutionMode %4 Invocations 1\n"
"OpExecutionMode %4 OutputTriangleStrip\n"
"OpExecutionMode %4 OutputVertices 3\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[0].others+
"OpMemberDecorate %52 0 BuiltIn Position\n"
"OpMemberDecorate %52 1 BuiltIn PointSize\n"
"OpMemberDecorate %52 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %52 3 BuiltIn CullDistance\n"
"OpDecorate %52 Block\n"
"OpMemberDecorate %55 0 BuiltIn Position\n"
"OpMemberDecorate %55 1 BuiltIn PointSize\n"
"OpMemberDecorate %55 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %55 3 BuiltIn CullDistance\n"
"OpDecorate %55 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypeInt 32 0\n"
"%11 = OpConstant %10 3\n"
"%12 = OpTypeArray %7 %11\n"
"%13 = OpTypePointer Input %12\n"
"%color_in = OpVariable %13 Input\n"
"%15 = OpTypeInt 32 1\n"
"%16 = OpConstant %15 0\n"
"%17 = OpTypePointer Input %7\n"
"%20 = OpTypePointer Output %6\n"
"%r_float_out = OpVariable %20 Output\n"
"%22 = OpTypeArray %6 %11\n"
"%23 = OpTypePointer Input %22\n"
"%r_float_in = OpVariable %23 Input\n"
"%25 = OpTypePointer Input %6\n"
"%28 = OpTypeVector %6 2\n"
"%29 = OpTypePointer Output %28\n"
"%rg_float_out = OpVariable %29 Output\n"
"%31 = OpTypeArray %28 %11\n"
"%32 = OpTypePointer Input %31\n"
"%rg_float_in = OpVariable %32 Input\n"
"%34 = OpTypePointer Input %28\n"
"%37 = OpTypeVector %6 3\n"
"%38 = OpTypePointer Output %37\n"
"%rgb_float_out = OpVariable %38 Output\n"
"%40 = OpTypeArray %37 %11\n"
"%41 = OpTypePointer Input %40\n"
"%rgb_float_in = OpVariable %41 Input\n"
"%43 = OpTypePointer Input %37\n"
"%rgba_float_out = OpVariable %8 Output\n"
"%rgba_float_in = OpVariable %13 Input\n"
"%50 = OpConstant %10 1\n"
"%51 = OpTypeArray %6 %50\n"
"%52 = OpTypeStruct %7 %6 %51 %51\n"
"%53 = OpTypePointer Output %52\n"
"%54 = OpVariable %53 Output\n"
"%55 = OpTypeStruct %7 %6 %51 %51\n"
"%56 = OpTypeArray %55 %11\n"
"%57 = OpTypePointer Input %56\n"
"%58 = OpVariable %57 Input\n"
"%62 = OpConstant %15 1\n"
"%76 = OpConstant %15 2\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpAccessChain %17 %color_in %16\n"
"%19 = OpLoad %7 %18\n"
"OpStore %color_out %19\n"
"%26 = OpAccessChain %25 %r_float_in %16\n"
"%27 = OpLoad %6 %26\n"
"OpStore %r_float_out %27\n"
"%35 = OpAccessChain %34 %rg_float_in %16\n"
"%36 = OpLoad %28 %35\n"
"OpStore %rg_float_out %36\n"
"%44 = OpAccessChain %43 %rgb_float_in %16\n"
"%45 = OpLoad %37 %44\n"
"OpStore %rgb_float_out %45\n"
"%48 = OpAccessChain %17 %rgba_float_in %16\n"
"%49 = OpLoad %7 %48\n"
"OpStore %rgba_float_out %49\n"
"%59 = OpAccessChain %17 %58 %16 %16\n"
"%60 = OpLoad %7 %59\n"
"%61 = OpAccessChain %8 %54 %16\n"
"OpStore %61 %60\n"
"OpEmitVertex\n"
"%63 = OpAccessChain %17 %color_in %62\n"
"%64 = OpLoad %7 %63\n"
"OpStore %color_out %64\n"
"%65 = OpAccessChain %25 %r_float_in %62\n"
"%66 = OpLoad %6 %65\n"
"OpStore %r_float_out %66\n"
"%67 = OpAccessChain %34 %rg_float_in %62\n"
"%68 = OpLoad %28 %67\n"
"OpStore %rg_float_out %68\n"
"%69 = OpAccessChain %43 %rgb_float_in %62\n"
"%70 = OpLoad %37 %69\n"
"OpStore %rgb_float_out %70\n"
"%71 = OpAccessChain %17 %rgba_float_in %62\n"
"%72 = OpLoad %7 %71\n"
"OpStore %rgba_float_out %72\n"
"%73 = OpAccessChain %17 %58 %62 %16\n"
"%74 = OpLoad %7 %73\n"
"%75 = OpAccessChain %8 %54 %16\n"
"OpStore %75 %74\n"
"OpEmitVertex\n"
"%77 = OpAccessChain %17 %color_in %76\n"
"%78 = OpLoad %7 %77\n"
"OpStore %color_out %78\n"
"%79 = OpAccessChain %25 %r_float_in %76\n"
"%80 = OpLoad %6 %79\n"
"OpStore %r_float_out %80\n"
"%81 = OpAccessChain %34 %rg_float_in %76\n"
"%82 = OpLoad %28 %81\n"
"OpStore %rg_float_out %82\n"
"%83 = OpAccessChain %43 %rgb_float_in %76\n"
"%84 = OpLoad %37 %83\n"
"OpStore %rgb_float_out %84\n"
"%85 = OpAccessChain %17 %rgba_float_in %76\n"
"%86 = OpLoad %7 %85\n"
"OpStore %rgba_float_out %86\n"
"%87 = OpAccessChain %17 %58 %76 %16\n"
"%88 = OpLoad %7 %87\n"
"%89 = OpAccessChain %8 %54 %16\n"
"OpStore %89 %88\n"
"OpEmitVertex\n"
"OpEndPrimitive\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("geometry") << geometrySource;
}
}
class CrossStageInterfaceTestsCase : public vkt::TestCase
{
public:
CrossStageInterfaceTestsCase (tcu::TestContext &context, const char *name, const char *description, const TestParameters& parameters)
: TestCase (context, name, description)
, m_parameters (parameters)
{
}
private:
vkt::TestInstance* createInstance (vkt::Context& context) const;
void initPrograms (SourceCollections& programCollection) const;
const TestParameters m_parameters;
};
vkt::TestInstance* CrossStageInterfaceTestsCase::createInstance (vkt::Context& context) const
{
return new CrossStageTestInstance(context, m_parameters);
}
void CrossStageInterfaceTestsCase::initPrograms (SourceCollections& programCollection) const
{
vector<Decorations> decorations;
string epsilon = "6e-8";
switch(m_parameters.qualifier)
{
case TEST_TYPE_FLAT:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_out 0 Flat\n"
"OpMemberDecorate %block_out 1 Flat\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_in 0 Flat\n"
"OpMemberDecorate %block_in 1 Flat\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_in 0 Flat\n"
"OpMemberDecorate %block_in 1 Flat\n",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_out 0 Flat\n"
"OpMemberDecorate %block_out 1 Flat\n",
""));
epsilon = "0.0";
break;
case TEST_TYPE_NOPERSPECTIVE:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_out 0 NoPerspective\n"
"OpMemberDecorate %block_out 1 NoPerspective\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_in 0 NoPerspective\n"
"OpMemberDecorate %block_in 1 NoPerspective\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_in 0 NoPerspective\n"
"OpMemberDecorate %block_in 1 NoPerspective\n",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_out 0 NoPerspective\n"
"OpMemberDecorate %block_out 1 NoPerspective\n",
""));
break;
case TEST_TYPE_RELAXEDPRECISION:
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %color_out RelaxedPrecision\n"
"OpMemberDecorate %block_in 0 RelaxedPrecision\n"
"OpMemberDecorate %block_in 1 RelaxedPrecision\n",
//Vertex
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpMemberDecorate %block_out 0 RelaxedPrecision\n"
"OpMemberDecorate %block_out 1 RelaxedPrecision\n",
//Others
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpMemberDecorate %block_out 0 RelaxedPrecision\n"
"OpMemberDecorate %block_out 1 RelaxedPrecision\n"
"OpMemberDecorate %block_in 0 RelaxedPrecision\n"
"OpMemberDecorate %block_in 1 RelaxedPrecision\n"));
break;
default:
DE_ASSERT(0);
}
//Spir-v spec: decoration flat can be used only in Shader (fragment or vertex)
for (deUint32 ndx = 0; ndx < decorations.size(); ++ndx)
{
/*#version 450
#version 450
layout(location = 0) in highp vec4 in_position;
layout(location = 1) in vec4 in_color;
layout(location = 0) out vec4 out_color;
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData;
void main (void)
{
gl_Position = in_position;
out_color = in_color;
outData.colorVec = in_color;
outData.colorMat = mat2(in_color.r, in_color.g, in_color.b, in_color.a);
}
*/
const string vertexShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 51\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Vertex %4 \"main\" %13 %17 %color_out %color_in %28\n"
"OpMemberDecorate %11 0 BuiltIn Position\n"
"OpMemberDecorate %11 1 BuiltIn PointSize\n"
"OpMemberDecorate %11 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %11 3 BuiltIn CullDistance\n"
"OpDecorate %11 Block\n"
"OpDecorate %17 Location 0\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 1\n"
"OpDecorate %block_out Block\n"
"OpDecorate %28 Location 1\n"
+decorations[ndx].vertex+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypeInt 32 0\n"
"%9 = OpConstant %8 1\n"
"%10 = OpTypeArray %6 %9\n"
"%11 = OpTypeStruct %7 %6 %10 %10\n"
"%12 = OpTypePointer Output %11\n"
"%13 = OpVariable %12 Output\n"
"%14 = OpTypeInt 32 1\n"
"%15 = OpConstant %14 0\n"
"%16 = OpTypePointer Input %7\n"
"%17 = OpVariable %16 Input\n"
"%19 = OpTypePointer Output %7\n"
"%color_out = OpVariable %19 Output\n"
"%color_in = OpVariable %16 Input\n"
"%24 = OpTypeVector %6 2\n"
"%25 = OpTypeMatrix %24 2\n"
"%block_out = OpTypeStruct %7 %25\n"
"%27 = OpTypePointer Output %block_out\n"
"%28 = OpVariable %27 Output\n"
"%31 = OpConstant %14 1\n"
"%32 = OpConstant %8 0\n"
"%33 = OpTypePointer Input %6\n"
"%38 = OpConstant %8 2\n"
"%41 = OpConstant %8 3\n"
"%44 = OpConstant %6 1\n"
"%45 = OpConstant %6 0\n"
"%49 = OpTypePointer Output %25\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpLoad %7 %17\n"
"%20 = OpAccessChain %19 %13 %15\n"
"OpStore %20 %18\n"
"%23 = OpLoad %7 %color_in\n"
"OpStore %color_out %23\n"
"%29 = OpLoad %7 %color_in\n"
"%30 = OpAccessChain %19 %28 %15\n"
"OpStore %30 %29\n"
"%34 = OpAccessChain %33 %color_in %32\n"
"%35 = OpLoad %6 %34\n"
"%36 = OpAccessChain %33 %color_in %9\n"
"%37 = OpLoad %6 %36\n"
"%39 = OpAccessChain %33 %color_in %38\n"
"%40 = OpLoad %6 %39\n"
"%42 = OpAccessChain %33 %color_in %41\n"
"%43 = OpLoad %6 %42\n"
"%46 = OpCompositeConstruct %24 %35 %37\n"
"%47 = OpCompositeConstruct %24 %40 %43\n"
"%48 = OpCompositeConstruct %25 %46 %47\n"
"%50 = OpAccessChain %49 %28 %31\n"
"OpStore %50 %48\n"
"OpReturn\n"
"OpFunctionEnd\n";
/* #version 450
layout(location = 0) in vec4 in_color;
layout(location = 0) out vec4 out_color;
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData;
void main()
{
float epsilon = 6e-8; // or 0.0 for flat
out_color = in_color;
if(any(greaterThan(abs(inData.colorVec - in_color), vec4(epsilon))))
out_color.rgba = vec4(1.0f);
if(abs(inData.colorMat[0][0] - in_color.r) > epsilon)
out_color.rgba = vec4(1.0f);
if(abs(inData.colorMat[1][1] - in_color.a) > epsilon)
out_color.rgba = vec4(1.0f);
}
*/
const string fragmentShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 51\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Fragment %4 \"main\" %color_out %color_in %17\n"
"OpExecutionMode %4 OriginUpperLeft\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_in Block\n"
"OpDecorate %17 Location 1\n"
+decorations[ndx].fragment+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypePointer Input %7\n"
"%color_in = OpVariable %10 Input\n"
"%13 = OpTypeVector %6 2\n"
"%14 = OpTypeMatrix %13 2\n"
"%block_in = OpTypeStruct %7 %14\n"
"%16 = OpTypePointer Input %block_in\n"
"%17 = OpVariable %16 Input\n"
"%18 = OpTypeInt 32 1\n"
"%19 = OpConstant %18 0\n"
"%23 = OpTypeBool\n"
"%24 = OpTypeVector %23 4\n"
"%ep = OpConstant %6 " + epsilon + "\n"
"%ep4 = OpConstantComposite %7 %ep %ep %ep %ep\n"
"%29 = OpConstant %6 1\n"
"%30 = OpConstantComposite %7 %29 %29 %29 %29\n"
"%31 = OpConstant %18 1\n"
"%32 = OpTypeInt 32 0\n"
"%33 = OpConstant %32 0\n"
"%34 = OpTypePointer Input %6\n"
"%42 = OpConstant %32 1\n"
"%45 = OpConstant %32 3\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%12 = OpLoad %7 %color_in\n"
"OpStore %color_out %12\n"
"%20 = OpAccessChain %10 %17 %19\n"
"%21 = OpLoad %7 %20\n"
"%22 = OpLoad %7 %color_in\n"
"%sub4 = OpFSub %7 %21 %22\n"
"%abs4 = OpExtInst %7 %1 FAbs %sub4\n"
"%cmp4 = OpFOrdGreaterThan %24 %abs4 %ep4\n"
"%26 = OpAny %23 %cmp4\n"
"OpSelectionMerge %28 None\n"
"OpBranchConditional %26 %27 %28\n"
"%27 = OpLabel\n"
"OpStore %color_out %30\n"
"OpBranch %28\n"
"%28 = OpLabel\n"
"%35 = OpAccessChain %34 %17 %31 %19 %33\n"
"%36 = OpLoad %6 %35\n"
"%37 = OpAccessChain %34 %color_in %33\n"
"%38 = OpLoad %6 %37\n"
"%subr = OpFSub %6 %36 %38\n"
"%absr = OpExtInst %6 %1 FAbs %subr\n"
"%cmpr = OpFOrdGreaterThan %23 %absr %ep\n"
"OpSelectionMerge %41 None\n"
"OpBranchConditional %cmpr %40 %41\n"
"%40 = OpLabel\n"
"OpStore %color_out %30\n"
"OpBranch %41\n"
"%41 = OpLabel\n"
"%43 = OpAccessChain %34 %17 %31 %31 %42\n"
"%44 = OpLoad %6 %43\n"
"%46 = OpAccessChain %34 %color_in %45\n"
"%47 = OpLoad %6 %46\n"
"%suba = OpFSub %6 %44 %47\n"
"%absa = OpExtInst %6 %1 FAbs %suba\n"
"%cmpa = OpFOrdGreaterThan %23 %absa %ep\n"
"OpSelectionMerge %50 None\n"
"OpBranchConditional %cmpa %49 %50\n"
"%49 = OpLabel\n"
"OpStore %color_out %30\n"
"OpBranch %50\n"
"%50 = OpLabel\n"
"OpReturn\n"
"OpFunctionEnd\n";
std::ostringstream vertex;
vertex << "vertex" << ndx;
std::ostringstream fragment;
fragment << "fragment" << ndx;
programCollection.spirvAsmSources.add(vertex.str()) << vertexShaderSource;
programCollection.spirvAsmSources.add(fragment.str()) << fragmentShaderSource;
}
{
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout(vertices = 4) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData[];
layout(location = 0) out vec4 out_color[];
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData[];
void main (void)
{
if ( gl_InvocationID == 0 )
{
gl_TessLevelInner[0] = 4.0f;
gl_TessLevelInner[1] = 4.0f;
gl_TessLevelOuter[0] = 4.0f;
gl_TessLevelOuter[1] = 4.0f;
gl_TessLevelOuter[2] = 4.0f;
gl_TessLevelOuter[3] = 4.0f;
}
out_color[gl_InvocationID] = in_color[gl_InvocationID];
outData[gl_InvocationID].colorVec = inData[gl_InvocationID].colorVec;
outData[gl_InvocationID].colorMat = inData[gl_InvocationID].colorMat;
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}*/
const string tessellationControlSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 88\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationControl %4 \"main\" %8 %20 %29 %color_out %color_in %56 %61 %78 %83\n"
"OpExecutionMode %4 OutputVertices 4\n"
"OpDecorate %8 BuiltIn InvocationId\n"
"OpDecorate %20 Patch\n"
"OpDecorate %20 BuiltIn TessLevelInner\n"
"OpDecorate %29 Patch\n"
"OpDecorate %29 BuiltIn TessLevelOuter\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_out Block\n"
"OpDecorate %56 Location 1\n"
"OpDecorate %block_in Block\n"
"OpDecorate %61 Location 1\n"
+decorations[0].others+
"OpMemberDecorate %75 0 BuiltIn Position\n"
"OpMemberDecorate %75 1 BuiltIn PointSize\n"
"OpMemberDecorate %75 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %75 3 BuiltIn CullDistance\n"
"OpDecorate %75 Block\n"
"OpMemberDecorate %80 0 BuiltIn Position\n"
"OpMemberDecorate %80 1 BuiltIn PointSize\n"
"OpMemberDecorate %80 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %80 3 BuiltIn CullDistance\n"
"OpDecorate %80 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeInt 32 1\n"
"%7 = OpTypePointer Input %6\n"
"%8 = OpVariable %7 Input\n"
"%10 = OpConstant %6 0\n"
"%11 = OpTypeBool\n"
"%15 = OpTypeFloat 32\n"
"%16 = OpTypeInt 32 0\n"
"%17 = OpConstant %16 2\n"
"%18 = OpTypeArray %15 %17\n"
"%19 = OpTypePointer Output %18\n"
"%20 = OpVariable %19 Output\n"
"%21 = OpConstant %15 4\n"
"%22 = OpTypePointer Output %15\n"
"%24 = OpConstant %6 1\n"
"%26 = OpConstant %16 4\n"
"%27 = OpTypeArray %15 %26\n"
"%28 = OpTypePointer Output %27\n"
"%29 = OpVariable %28 Output\n"
"%32 = OpConstant %6 2\n"
"%34 = OpConstant %6 3\n"
"%36 = OpTypeVector %15 4\n"
"%37 = OpTypeArray %36 %26\n"
"%38 = OpTypePointer Output %37\n"
"%color_out = OpVariable %38 Output\n"
"%41 = OpConstant %16 32\n"
"%42 = OpTypeArray %36 %41\n"
"%43 = OpTypePointer Input %42\n"
"%color_in = OpVariable %43 Input\n"
"%46 = OpTypePointer Input %36\n"
"%49 = OpTypePointer Output %36\n"
"%51 = OpTypeVector %15 2\n"
"%52 = OpTypeMatrix %51 2\n"
"%block_out = OpTypeStruct %36 %52\n"
"%54 = OpTypeArray %block_out %26\n"
"%55 = OpTypePointer Output %54\n"
"%56 = OpVariable %55 Output\n"
"%block_in = OpTypeStruct %36 %52\n"
"%59 = OpTypeArray %block_in %41\n"
"%60 = OpTypePointer Input %59\n"
"%61 = OpVariable %60 Input\n"
"%68 = OpTypePointer Input %52\n"
"%71 = OpTypePointer Output %52\n"
"%73 = OpConstant %16 1\n"
"%74 = OpTypeArray %15 %73\n"
"%75 = OpTypeStruct %36 %15 %74 %74\n"
"%76 = OpTypeArray %75 %26\n"
"%77 = OpTypePointer Output %76\n"
"%78 = OpVariable %77 Output\n"
"%80 = OpTypeStruct %36 %15 %74 %74\n"
"%81 = OpTypeArray %80 %41\n"
"%82 = OpTypePointer Input %81\n"
"%83 = OpVariable %82 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%9 = OpLoad %6 %8\n"
"%12 = OpIEqual %11 %9 %10\n"
"OpSelectionMerge %14 None\n"
"OpBranchConditional %12 %13 %14\n"
"%13 = OpLabel\n"
"%23 = OpAccessChain %22 %20 %10\n"
"OpStore %23 %21\n"
"%25 = OpAccessChain %22 %20 %24\n"
"OpStore %25 %21\n"
"%30 = OpAccessChain %22 %29 %10\n"
"OpStore %30 %21\n"
"%31 = OpAccessChain %22 %29 %24\n"
"OpStore %31 %21\n"
"%33 = OpAccessChain %22 %29 %32\n"
"OpStore %33 %21\n"
"%35 = OpAccessChain %22 %29 %34\n"
"OpStore %35 %21\n"
"OpBranch %14\n"
"%14 = OpLabel\n"
"%40 = OpLoad %6 %8\n"
"%45 = OpLoad %6 %8\n"
"%47 = OpAccessChain %46 %color_in %45\n"
"%48 = OpLoad %36 %47\n"
"%50 = OpAccessChain %49 %color_out %40\n"
"OpStore %50 %48\n"
"%57 = OpLoad %6 %8\n"
"%62 = OpLoad %6 %8\n"
"%63 = OpAccessChain %46 %61 %62 %10\n"
"%64 = OpLoad %36 %63\n"
"%65 = OpAccessChain %49 %56 %57 %10\n"
"OpStore %65 %64\n"
"%66 = OpLoad %6 %8\n"
"%67 = OpLoad %6 %8\n"
"%69 = OpAccessChain %68 %61 %67 %24\n"
"%70 = OpLoad %52 %69\n"
"%72 = OpAccessChain %71 %56 %66 %24\n"
"OpStore %72 %70\n"
"%79 = OpLoad %6 %8\n"
"%84 = OpLoad %6 %8\n"
"%85 = OpAccessChain %46 %83 %84 %10\n"
"%86 = OpLoad %36 %85\n"
"%87 = OpAccessChain %49 %78 %79 %10\n"
"OpStore %87 %86\n"
"OpReturn\n"
"OpFunctionEnd\n";
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout( quads, equal_spacing, ccw ) in;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData;
void main (void)
{
const float u = gl_TessCoord.x;
const float v = gl_TessCoord.y;
const float w = gl_TessCoord.z;
out_color = (1 - u) * (1 - v) * in_color[0] +(1 - u) * v * in_color[1] + u * (1 - v) * in_color[2] + u * v * in_color[3];
outData.colorVec = (1 - u) * (1 - v) * inData[0].colorVec +(1 - u) * v * inData[1].colorVec + u * (1 - v) * inData[2].colorVec + u * v * inData[3].colorVec;
outData.colorMat = (1 - u) * (1 - v) * inData[0].colorMat +(1 - u) * v * inData[1].colorMat + u * (1 - v) * inData[2].colorMat + u * v * inData[3].colorMat;
gl_Position = (1 - u) * (1 - v) * gl_in[0].gl_Position +(1 - u) * v * gl_in[1].gl_Position + u * (1 - v) * gl_in[2].gl_Position + u * v * gl_in[3].gl_Position;
}*/
const string tessellationEvaluationSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 203\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationEvaluation %4 \"main\" %11 %color_out %color_in %74 %83 %166 %175\n"
"OpExecutionMode %4 Quads\n"
"OpExecutionMode %4 SpacingEqual\n"
"OpExecutionMode %4 VertexOrderCcw\n"
"OpDecorate %11 BuiltIn TessCoord\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_out Block\n"
"OpDecorate %74 Location 1\n"
"OpDecorate %block_in Block\n"
"OpDecorate %83 Location 1\n"
+decorations[0].others+
"OpMemberDecorate %164 0 BuiltIn Position\n"
"OpMemberDecorate %164 1 BuiltIn PointSize\n"
"OpMemberDecorate %164 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %164 3 BuiltIn CullDistance\n"
"OpDecorate %164 Block\n"
"OpMemberDecorate %172 0 BuiltIn Position\n"
"OpMemberDecorate %172 1 BuiltIn PointSize\n"
"OpMemberDecorate %172 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %172 3 BuiltIn CullDistance\n"
"OpDecorate %172 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypePointer Function %6\n"
"%9 = OpTypeVector %6 3\n"
"%10 = OpTypePointer Input %9\n"
"%11 = OpVariable %10 Input\n"
"%12 = OpTypeInt 32 0\n"
"%13 = OpConstant %12 0\n"
"%14 = OpTypePointer Input %6\n"
"%18 = OpConstant %12 1\n"
"%22 = OpConstant %12 2\n"
"%25 = OpTypeVector %6 4\n"
"%26 = OpTypePointer Output %25\n"
"%color_out = OpVariable %26 Output\n"
"%28 = OpConstant %6 1\n"
"%34 = OpConstant %12 32\n"
"%35 = OpTypeArray %25 %34\n"
"%36 = OpTypePointer Input %35\n"
"%color_in = OpVariable %36 Input\n"
"%38 = OpTypeInt 32 1\n"
"%39 = OpConstant %38 0\n"
"%40 = OpTypePointer Input %25\n"
"%48 = OpConstant %38 1\n"
"%57 = OpConstant %38 2\n"
"%65 = OpConstant %38 3\n"
"%70 = OpTypeVector %6 2\n"
"%71 = OpTypeMatrix %70 2\n"
"%block_out = OpTypeStruct %25 %71\n"
"%73 = OpTypePointer Output %block_out\n"
"%74 = OpVariable %73 Output\n"
"%block_in = OpTypeStruct %25 %71\n"
"%81 = OpTypeArray %block_in %34\n"
"%82 = OpTypePointer Input %81\n"
"%83 = OpVariable %82 Input\n"
"%116 = OpTypePointer Input %71\n"
"%161 = OpTypePointer Output %71\n"
"%163 = OpTypeArray %6 %18\n"
"%164 = OpTypeStruct %25 %6 %163 %163\n"
"%165 = OpTypePointer Output %164\n"
"%166 = OpVariable %165 Output\n"
"%172 = OpTypeStruct %25 %6 %163 %163\n"
"%173 = OpTypeArray %172 %34\n"
"%174 = OpTypePointer Input %173\n"
"%175 = OpVariable %174 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%8 = OpVariable %7 Function\n"
"%17 = OpVariable %7 Function\n"
"%21 = OpVariable %7 Function\n"
"%15 = OpAccessChain %14 %11 %13\n"
"%16 = OpLoad %6 %15\n"
"OpStore %8 %16\n"
"%19 = OpAccessChain %14 %11 %18\n"
"%20 = OpLoad %6 %19\n"
"OpStore %17 %20\n"
"%23 = OpAccessChain %14 %11 %22\n"
"%24 = OpLoad %6 %23\n"
"OpStore %21 %24\n"
"%29 = OpLoad %6 %8\n"
"%30 = OpFSub %6 %28 %29\n"
"%31 = OpLoad %6 %17\n"
"%32 = OpFSub %6 %28 %31\n"
"%33 = OpFMul %6 %30 %32\n"
"%41 = OpAccessChain %40 %color_in %39\n"
"%42 = OpLoad %25 %41\n"
"%43 = OpVectorTimesScalar %25 %42 %33\n"
"%44 = OpLoad %6 %8\n"
"%45 = OpFSub %6 %28 %44\n"
"%46 = OpLoad %6 %17\n"
"%47 = OpFMul %6 %45 %46\n"
"%49 = OpAccessChain %40 %color_in %48\n"
"%50 = OpLoad %25 %49\n"
"%51 = OpVectorTimesScalar %25 %50 %47\n"
"%52 = OpFAdd %25 %43 %51\n"
"%53 = OpLoad %6 %8\n"
"%54 = OpLoad %6 %17\n"
"%55 = OpFSub %6 %28 %54\n"
"%56 = OpFMul %6 %53 %55\n"
"%58 = OpAccessChain %40 %color_in %57\n"
"%59 = OpLoad %25 %58\n"
"%60 = OpVectorTimesScalar %25 %59 %56\n"
"%61 = OpFAdd %25 %52 %60\n"
"%62 = OpLoad %6 %8\n"
"%63 = OpLoad %6 %17\n"
"%64 = OpFMul %6 %62 %63\n"
"%66 = OpAccessChain %40 %color_in %65\n"
"%67 = OpLoad %25 %66\n"
"%68 = OpVectorTimesScalar %25 %67 %64\n"
"%69 = OpFAdd %25 %61 %68\n"
"OpStore %color_out %69\n"
"%75 = OpLoad %6 %8\n"
"%76 = OpFSub %6 %28 %75\n"
"%77 = OpLoad %6 %17\n"
"%78 = OpFSub %6 %28 %77\n"
"%79 = OpFMul %6 %76 %78\n"
"%84 = OpAccessChain %40 %83 %39 %39\n"
"%85 = OpLoad %25 %84\n"
"%86 = OpVectorTimesScalar %25 %85 %79\n"
"%87 = OpLoad %6 %8\n"
"%88 = OpFSub %6 %28 %87\n"
"%89 = OpLoad %6 %17\n"
"%90 = OpFMul %6 %88 %89\n"
"%91 = OpAccessChain %40 %83 %48 %39\n"
"%92 = OpLoad %25 %91\n"
"%93 = OpVectorTimesScalar %25 %92 %90\n"
"%94 = OpFAdd %25 %86 %93\n"
"%95 = OpLoad %6 %8\n"
"%96 = OpLoad %6 %17\n"
"%97 = OpFSub %6 %28 %96\n"
"%98 = OpFMul %6 %95 %97\n"
"%99 = OpAccessChain %40 %83 %57 %39\n"
"%100 = OpLoad %25 %99\n"
"%101 = OpVectorTimesScalar %25 %100 %98\n"
"%102 = OpFAdd %25 %94 %101\n"
"%103 = OpLoad %6 %8\n"
"%104 = OpLoad %6 %17\n"
"%105 = OpFMul %6 %103 %104\n"
"%106 = OpAccessChain %40 %83 %65 %39\n"
"%107 = OpLoad %25 %106\n"
"%108 = OpVectorTimesScalar %25 %107 %105\n"
"%109 = OpFAdd %25 %102 %108\n"
"%110 = OpAccessChain %26 %74 %39\n"
"OpStore %110 %109\n"
"%111 = OpLoad %6 %8\n"
"%112 = OpFSub %6 %28 %111\n"
"%113 = OpLoad %6 %17\n"
"%114 = OpFSub %6 %28 %113\n"
"%115 = OpFMul %6 %112 %114\n"
"%117 = OpAccessChain %116 %83 %39 %48\n"
"%118 = OpLoad %71 %117\n"
"%119 = OpMatrixTimesScalar %71 %118 %115\n"
"%120 = OpLoad %6 %8\n"
"%121 = OpFSub %6 %28 %120\n"
"%122 = OpLoad %6 %17\n"
"%123 = OpFMul %6 %121 %122\n"
"%124 = OpAccessChain %116 %83 %48 %48\n"
"%125 = OpLoad %71 %124\n"
"%126 = OpMatrixTimesScalar %71 %125 %123\n"
"%127 = OpCompositeExtract %70 %119 0\n"
"%128 = OpCompositeExtract %70 %126 0\n"
"%129 = OpFAdd %70 %127 %128\n"
"%130 = OpCompositeExtract %70 %119 1\n"
"%131 = OpCompositeExtract %70 %126 1\n"
"%132 = OpFAdd %70 %130 %131\n"
"%133 = OpCompositeConstruct %71 %129 %132\n"
"%134 = OpLoad %6 %8\n"
"%135 = OpLoad %6 %17\n"
"%136 = OpFSub %6 %28 %135\n"
"%137 = OpFMul %6 %134 %136\n"
"%138 = OpAccessChain %116 %83 %57 %48\n"
"%139 = OpLoad %71 %138\n"
"%140 = OpMatrixTimesScalar %71 %139 %137\n"
"%141 = OpCompositeExtract %70 %133 0\n"
"%142 = OpCompositeExtract %70 %140 0\n"
"%143 = OpFAdd %70 %141 %142\n"
"%144 = OpCompositeExtract %70 %133 1\n"
"%145 = OpCompositeExtract %70 %140 1\n"
"%146 = OpFAdd %70 %144 %145\n"
"%147 = OpCompositeConstruct %71 %143 %146\n"
"%148 = OpLoad %6 %8\n"
"%149 = OpLoad %6 %17\n"
"%150 = OpFMul %6 %148 %149\n"
"%151 = OpAccessChain %116 %83 %65 %48\n"
"%152 = OpLoad %71 %151\n"
"%153 = OpMatrixTimesScalar %71 %152 %150\n"
"%154 = OpCompositeExtract %70 %147 0\n"
"%155 = OpCompositeExtract %70 %153 0\n"
"%156 = OpFAdd %70 %154 %155\n"
"%157 = OpCompositeExtract %70 %147 1\n"
"%158 = OpCompositeExtract %70 %153 1\n"
"%159 = OpFAdd %70 %157 %158\n"
"%160 = OpCompositeConstruct %71 %156 %159\n"
"%162 = OpAccessChain %161 %74 %48\n"
"OpStore %162 %160\n"
"%167 = OpLoad %6 %8\n"
"%168 = OpFSub %6 %28 %167\n"
"%169 = OpLoad %6 %17\n"
"%170 = OpFSub %6 %28 %169\n"
"%171 = OpFMul %6 %168 %170\n"
"%176 = OpAccessChain %40 %175 %39 %39\n"
"%177 = OpLoad %25 %176\n"
"%178 = OpVectorTimesScalar %25 %177 %171\n"
"%179 = OpLoad %6 %8\n"
"%180 = OpFSub %6 %28 %179\n"
"%181 = OpLoad %6 %17\n"
"%182 = OpFMul %6 %180 %181\n"
"%183 = OpAccessChain %40 %175 %48 %39\n"
"%184 = OpLoad %25 %183\n"
"%185 = OpVectorTimesScalar %25 %184 %182\n"
"%186 = OpFAdd %25 %178 %185\n"
"%187 = OpLoad %6 %8\n"
"%188 = OpLoad %6 %17\n"
"%189 = OpFSub %6 %28 %188\n"
"%190 = OpFMul %6 %187 %189\n"
"%191 = OpAccessChain %40 %175 %57 %39\n"
"%192 = OpLoad %25 %191\n"
"%193 = OpVectorTimesScalar %25 %192 %190\n"
"%194 = OpFAdd %25 %186 %193\n"
"%195 = OpLoad %6 %8\n"
"%196 = OpLoad %6 %17\n"
"%197 = OpFMul %6 %195 %196\n"
"%198 = OpAccessChain %40 %175 %65 %39\n"
"%199 = OpLoad %25 %198\n"
"%200 = OpVectorTimesScalar %25 %199 %197\n"
"%201 = OpFAdd %25 %194 %200\n"
"%202 = OpAccessChain %26 %166 %39\n"
"OpStore %202 %201\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("tessellation_control") << tessellationControlSource;
programCollection.spirvAsmSources.add("tessellation_evaluation") << tessellationEvaluationSource;
}
{
/*#version 450
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData;
void main (void)
{
out_color = in_color[0];
outData.colorVec = inData[0].colorVec;
outData.colorMat = inData[0].colorMat;
gl_Position = gl_in[0].gl_Position;
EmitVertex();
out_color = in_color[1];
outData.colorVec = inData[1].colorVec;
outData.colorMat = inData[1].colorMat;
gl_Position = gl_in[1].gl_Position;
EmitVertex();
out_color = in_color[2];
outData.colorVec = inData[2].colorVec;
outData.colorMat = inData[2].colorMat;
gl_Position = gl_in[2].gl_Position;
EmitVertex();
EndPrimitive();
}*/
const string geometrySource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 73\n"
"; Schema: 0\n"
"OpCapability Geometry\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Geometry %4 \"main\" %color_out %color_in %24 %28 %42 %46\n"
"OpExecutionMode %4 Triangles\n"
"OpExecutionMode %4 Invocations 1\n"
"OpExecutionMode %4 OutputTriangleStrip\n"
"OpExecutionMode %4 OutputVertices 3\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_out Block\n"
"OpDecorate %24 Location 1\n"
"OpDecorate %block_in Block\n"
"OpDecorate %28 Location 1\n"
+decorations[0].others+
"OpMemberDecorate %40 0 BuiltIn Position\n"
"OpMemberDecorate %40 1 BuiltIn PointSize\n"
"OpMemberDecorate %40 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %40 3 BuiltIn CullDistance\n"
"OpDecorate %40 Block\n"
"OpMemberDecorate %43 0 BuiltIn Position\n"
"OpMemberDecorate %43 1 BuiltIn PointSize\n"
"OpMemberDecorate %43 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %43 3 BuiltIn CullDistance\n"
"OpDecorate %43 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypeInt 32 0\n"
"%11 = OpConstant %10 3\n"
"%12 = OpTypeArray %7 %11\n"
"%13 = OpTypePointer Input %12\n"
"%color_in = OpVariable %13 Input\n"
"%15 = OpTypeInt 32 1\n"
"%16 = OpConstant %15 0\n"
"%17 = OpTypePointer Input %7\n"
"%20 = OpTypeVector %6 2\n"
"%21 = OpTypeMatrix %20 2\n"
"%block_out = OpTypeStruct %7 %21\n"
"%23 = OpTypePointer Output %block_out\n"
"%24 = OpVariable %23 Output\n"
"%block_in = OpTypeStruct %7 %21\n"
"%26 = OpTypeArray %block_in %11\n"
"%27 = OpTypePointer Input %26\n"
"%28 = OpVariable %27 Input\n"
"%32 = OpConstant %15 1\n"
"%33 = OpTypePointer Input %21\n"
"%36 = OpTypePointer Output %21\n"
"%38 = OpConstant %10 1\n"
"%39 = OpTypeArray %6 %38\n"
"%40 = OpTypeStruct %7 %6 %39 %39\n"
"%41 = OpTypePointer Output %40\n"
"%42 = OpVariable %41 Output\n"
"%43 = OpTypeStruct %7 %6 %39 %39\n"
"%44 = OpTypeArray %43 %11\n"
"%45 = OpTypePointer Input %44\n"
"%46 = OpVariable %45 Input\n"
"%61 = OpConstant %15 2\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpAccessChain %17 %color_in %16\n"
"%19 = OpLoad %7 %18\n"
"OpStore %color_out %19\n"
"%29 = OpAccessChain %17 %28 %16 %16\n"
"%30 = OpLoad %7 %29\n"
"%31 = OpAccessChain %8 %24 %16\n"
"OpStore %31 %30\n"
"%34 = OpAccessChain %33 %28 %16 %32\n"
"%35 = OpLoad %21 %34\n"
"%37 = OpAccessChain %36 %24 %32\n"
"OpStore %37 %35\n"
"%47 = OpAccessChain %17 %46 %16 %16\n"
"%48 = OpLoad %7 %47\n"
"%49 = OpAccessChain %8 %42 %16\n"
"OpStore %49 %48\n"
"OpEmitVertex\n"
"%50 = OpAccessChain %17 %color_in %32\n"
"%51 = OpLoad %7 %50\n"
"OpStore %color_out %51\n"
"%52 = OpAccessChain %17 %28 %32 %16\n"
"%53 = OpLoad %7 %52\n"
"%54 = OpAccessChain %8 %24 %16\n"
"OpStore %54 %53\n"
"%55 = OpAccessChain %33 %28 %32 %32\n"
"%56 = OpLoad %21 %55\n"
"%57 = OpAccessChain %36 %24 %32\n"
"OpStore %57 %56\n"
"%58 = OpAccessChain %17 %46 %32 %16\n"
"%59 = OpLoad %7 %58\n"
"%60 = OpAccessChain %8 %42 %16\n"
"OpStore %60 %59\n"
"OpEmitVertex\n"
"%62 = OpAccessChain %17 %color_in %61\n"
"%63 = OpLoad %7 %62\n"
"OpStore %color_out %63\n"
"%64 = OpAccessChain %17 %28 %61 %16\n"
"%65 = OpLoad %7 %64\n"
"%66 = OpAccessChain %8 %24 %16\n"
"OpStore %66 %65\n"
"%67 = OpAccessChain %33 %28 %61 %32\n"
"%68 = OpLoad %21 %67\n"
"%69 = OpAccessChain %36 %24 %32\n"
"OpStore %69 %68\n"
"%70 = OpAccessChain %17 %46 %61 %16\n"
"%71 = OpLoad %7 %70\n"
"%72 = OpAccessChain %8 %42 %16\n"
"OpStore %72 %71\n"
"OpEmitVertex\n"
"OpEndPrimitive\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("geometry") << geometrySource;
}
}
} // anonymous
tcu::TestCaseGroup* createCrossStageInterfaceTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "cross_stage", ""));
{
de::MovePtr<tcu::TestCaseGroup> basicGroup(new tcu::TestCaseGroup(testCtx, "basic_type", ""));
de::MovePtr<tcu::TestCaseGroup> interfaceGroup(new tcu::TestCaseGroup(testCtx, "interface_blocks", ""));
{
TestParameters parm(TEST_TYPE_FLAT,3);
for (int ndx = 0; ndx < CrossStageTestInstance::DECORATION_LAST; ++ndx)
parm.testOptions[ndx] = ndx;
basicGroup->addChild(new CrossStageBasicTestsCase(testCtx, "flat", "", parm));
interfaceGroup->addChild(new CrossStageInterfaceTestsCase(testCtx, "flat", "", parm));
parm.qualifier = TEST_TYPE_NOPERSPECTIVE;
basicGroup->addChild(new CrossStageBasicTestsCase(testCtx, "no_perspective", "", parm));
interfaceGroup->addChild(new CrossStageInterfaceTestsCase(testCtx, "no_perspective", "", parm));
}
{
TestParameters parm(TEST_TYPE_RELAXEDPRECISION,1);
parm.testOptions[0] = CrossStageTestInstance::DECORATION_IN_ALL_SHADERS;
basicGroup->addChild(new CrossStageBasicTestsCase(testCtx, "relaxedprecision", "", parm));
interfaceGroup->addChild(new CrossStageInterfaceTestsCase(testCtx, "relaxedprecision", "", parm));
}
testGroup->addChild(basicGroup.release());
testGroup->addChild(interfaceGroup.release());
}
return testGroup.release();
}
} // SpirVAssembly
} // vkt
| 102,010
| 52,416
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2009, Farhad Dadgostar
// Intel Corporation and third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
CvFuzzyPoint::CvFuzzyPoint(double _x, double _y)
{
x = _x;
y = _y;
}
bool CvFuzzyCurve::between(double x, double x1, double x2)
{
if ((x >= x1) && (x <= x2))
return true;
else if ((x >= x2) && (x <= x1))
return true;
return false;
}
CvFuzzyCurve::CvFuzzyCurve()
{
value = 0;
}
CvFuzzyCurve::~CvFuzzyCurve()
{
// nothing to do
}
void CvFuzzyCurve::setCentre(double _centre)
{
centre = _centre;
}
double CvFuzzyCurve::getCentre()
{
return centre;
}
void CvFuzzyCurve::clear()
{
points.clear();
}
void CvFuzzyCurve::addPoint(double x, double y)
{
points.push_back(CvFuzzyPoint(x, y));
}
double CvFuzzyCurve::calcValue(double param)
{
int size = (int)points.size();
double x1, y1, x2, y2, m, y;
for (int i = 1; i < size; i++)
{
x1 = points[i-1].x;
x2 = points[i].x;
if (between(param, x1, x2)) {
y1 = points[i-1].y;
y2 = points[i].y;
if (x2 == x1)
return y2;
m = (y2-y1)/(x2-x1);
y = m*(param-x1)+y1;
return y;
}
}
return 0;
}
double CvFuzzyCurve::getValue()
{
return value;
}
void CvFuzzyCurve::setValue(double _value)
{
value = _value;
}
CvFuzzyFunction::CvFuzzyFunction()
{
// nothing to do
}
CvFuzzyFunction::~CvFuzzyFunction()
{
curves.clear();
}
void CvFuzzyFunction::addCurve(CvFuzzyCurve *curve, double value)
{
curves.push_back(*curve);
curve->setValue(value);
}
void CvFuzzyFunction::resetValues()
{
int numCurves = (int)curves.size();
for (int i = 0; i < numCurves; i++)
curves[i].setValue(0);
}
double CvFuzzyFunction::calcValue()
{
double s1 = 0, s2 = 0, v;
int numCurves = (int)curves.size();
for (int i = 0; i < numCurves; i++)
{
v = curves[i].getValue();
s1 += curves[i].getCentre() * v;
s2 += v;
}
if (s2 != 0)
return s1/s2;
else
return 0;
}
CvFuzzyCurve *CvFuzzyFunction::newCurve()
{
CvFuzzyCurve *c;
c = new CvFuzzyCurve();
addCurve(c);
return c;
}
CvFuzzyRule::CvFuzzyRule()
{
fuzzyInput1 = NULL;
fuzzyInput2 = NULL;
fuzzyOutput = NULL;
}
CvFuzzyRule::~CvFuzzyRule()
{
if (fuzzyInput1 != NULL)
delete fuzzyInput1;
if (fuzzyInput2 != NULL)
delete fuzzyInput2;
if (fuzzyOutput != NULL)
delete fuzzyOutput;
}
void CvFuzzyRule::setRule(CvFuzzyCurve *c1, CvFuzzyCurve *c2, CvFuzzyCurve *o1)
{
fuzzyInput1 = c1;
fuzzyInput2 = c2;
fuzzyOutput = o1;
}
double CvFuzzyRule::calcValue(double param1, double param2)
{
double v1, v2;
v1 = fuzzyInput1->calcValue(param1);
if (fuzzyInput2 != NULL)
{
v2 = fuzzyInput2->calcValue(param2);
if (v1 < v2)
return v1;
else
return v2;
}
else
return v1;
}
CvFuzzyCurve *CvFuzzyRule::getOutputCurve()
{
return fuzzyOutput;
}
CvFuzzyController::CvFuzzyController()
{
// nothing to do
}
CvFuzzyController::~CvFuzzyController()
{
int size = (int)rules.size();
for(int i = 0; i < size; i++)
delete rules[i];
}
void CvFuzzyController::addRule(CvFuzzyCurve *c1, CvFuzzyCurve *c2, CvFuzzyCurve *o1)
{
CvFuzzyRule *f = new CvFuzzyRule();
rules.push_back(f);
f->setRule(c1, c2, o1);
}
double CvFuzzyController::calcOutput(double param1, double param2)
{
double v;
CvFuzzyFunction list;
int size = (int)rules.size();
for(int i = 0; i < size; i++)
{
v = rules[i]->calcValue(param1, param2);
if (v != 0)
list.addCurve(rules[i]->getOutputCurve(), v);
}
v = list.calcValue();
return v;
}
CvFuzzyMeanShiftTracker::FuzzyResizer::FuzzyResizer()
{
CvFuzzyCurve *i1L, *i1M, *i1H;
CvFuzzyCurve *oS, *oZE, *oE;
CvFuzzyCurve *c;
double MedStart = 0.1, MedWidth = 0.15;
c = iInput.newCurve();
c->addPoint(0, 1);
c->addPoint(0.1, 0);
c->setCentre(0);
i1L = c;
c = iInput.newCurve();
c->addPoint(0.05, 0);
c->addPoint(MedStart, 1);
c->addPoint(MedStart+MedWidth, 1);
c->addPoint(MedStart+MedWidth+0.05, 0);
c->setCentre(MedStart+(MedWidth/2));
i1M = c;
c = iInput.newCurve();
c->addPoint(MedStart+MedWidth, 0);
c->addPoint(1, 1);
c->addPoint(1000, 1);
c->setCentre(1);
i1H = c;
c = iOutput.newCurve();
c->addPoint(-10000, 1);
c->addPoint(-5, 1);
c->addPoint(-0.5, 0);
c->setCentre(-5);
oS = c;
c = iOutput.newCurve();
c->addPoint(-1, 0);
c->addPoint(-0.05, 1);
c->addPoint(0.05, 1);
c->addPoint(1, 0);
c->setCentre(0);
oZE = c;
c = iOutput.newCurve();
c->addPoint(-0.5, 0);
c->addPoint(5, 1);
c->addPoint(1000, 1);
c->setCentre(5);
oE = c;
fuzzyController.addRule(i1L, NULL, oS);
fuzzyController.addRule(i1M, NULL, oZE);
fuzzyController.addRule(i1H, NULL, oE);
}
int CvFuzzyMeanShiftTracker::FuzzyResizer::calcOutput(double edgeDensity, double density)
{
return (int)fuzzyController.calcOutput(edgeDensity, density);
}
CvFuzzyMeanShiftTracker::SearchWindow::SearchWindow()
{
x = 0;
y = 0;
width = 0;
height = 0;
maxWidth = 0;
maxHeight = 0;
xGc = 0;
yGc = 0;
m00 = 0;
m01 = 0;
m10 = 0;
m11 = 0;
m02 = 0;
m20 = 0;
ellipseHeight = 0;
ellipseWidth = 0;
ellipseAngle = 0;
density = 0;
depthLow = 0;
depthHigh = 0;
fuzzyResizer = NULL;
}
CvFuzzyMeanShiftTracker::SearchWindow::~SearchWindow()
{
if (fuzzyResizer != NULL)
delete fuzzyResizer;
}
void CvFuzzyMeanShiftTracker::SearchWindow::setSize(int _x, int _y, int _width, int _height)
{
x = _x;
y = _y;
width = _width;
height = _height;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x + width > maxWidth)
width = maxWidth - x;
if (y + height > maxHeight)
height = maxHeight - y;
}
void CvFuzzyMeanShiftTracker::SearchWindow::initDepthValues(IplImage *maskImage, IplImage *depthMap)
{
unsigned int d=0, mind = 0xFFFF, maxd = 0, m0 = 0, m1 = 0, mc, dd;
unsigned char *data = NULL;
unsigned short *depthData = NULL;
for (int j = 0; j < height; j++)
{
data = (unsigned char *)(maskImage->imageData + (maskImage->widthStep * (j + y)) + x);
if (depthMap)
depthData = (unsigned short *)(depthMap->imageData + (depthMap->widthStep * (j + y)) + x);
for (int i = 0; i < width; i++)
{
if (*data)
{
m0 += 1;
if (depthData)
{
if (*depthData)
{
d = *depthData;
m1 += d;
if (d < mind)
mind = d;
if (d > maxd)
maxd = d;
}
depthData++;
}
}
data++;
}
}
if (m0 > 0)
{
mc = m1/m0;
if ((mc - mind) > (maxd - mc))
dd = maxd - mc;
else
dd = mc - mind;
dd = dd - dd/10;
depthHigh = mc + dd;
depthLow = mc - dd;
}
else
{
depthHigh = 32000;
depthLow = 0;
}
}
bool CvFuzzyMeanShiftTracker::SearchWindow::shift()
{
if ((xGc != (width/2)) || (yGc != (height/2)))
{
setSize(x + (xGc-(width/2)), y + (yGc-(height/2)), width, height);
return true;
}
else
{
return false;
}
}
void CvFuzzyMeanShiftTracker::SearchWindow::extractInfo(IplImage *maskImage, IplImage *depthMap, bool initDepth)
{
m00 = 0;
m10 = 0;
m01 = 0;
m11 = 0;
density = 0;
m02 = 0;
m20 = 0;
ellipseHeight = 0;
ellipseWidth = 0;
maxWidth = maskImage->width;
maxHeight = maskImage->height;
if (initDepth)
initDepthValues(maskImage, depthMap);
unsigned char *maskData = NULL;
unsigned short *depthData = NULL, depth;
bool isOk;
unsigned long count;
verticalEdgeLeft = 0;
verticalEdgeRight = 0;
horizontalEdgeTop = 0;
horizontalEdgeBottom = 0;
for (int j = 0; j < height; j++)
{
maskData = (unsigned char *)(maskImage->imageData + (maskImage->widthStep * (j + y)) + x);
if (depthMap)
depthData = (unsigned short *)(depthMap->imageData + (depthMap->widthStep * (j + y)) + x);
count = 0;
for (int i = 0; i < width; i++)
{
if (*maskData)
{
isOk = true;
if (depthData)
{
depth = (*depthData);
if ((depth > depthHigh) || (depth < depthLow))
isOk = false;
depthData++;
}
if (isOk)
{
m00++;
m01 += j;
m10 += i;
m02 += (j * j);
m20 += (i * i);
m11 += (j * i);
if (i == 0)
verticalEdgeLeft++;
else if (i == width-1)
verticalEdgeRight++;
else if (j == 0)
horizontalEdgeTop++;
else if (j == height-1)
horizontalEdgeBottom++;
count++;
}
}
maskData++;
}
}
if (m00 > 0)
{
xGc = (int)(m10 / m00);
yGc = (int)(m01 / m00);
double a, b, c, e1, e2, e3;
a = ((double)m20/(double)m00)-(xGc * xGc);
b = 2*(((double)m11/(double)m00)-(xGc * yGc));
c = ((double)m02/(double)m00)-(yGc * yGc);
e1 = a+c;
e3 = a-c;
e2 = sqrt((b*b)+(e3*e3));
ellipseHeight = int(sqrt(0.5*(e1+e2)));
ellipseWidth = int(sqrt(0.5*(e1-e2)));
if (e3 == 0)
ellipseAngle = 0;
else
ellipseAngle = 0.5*atan(b/e3);
density = (double)m00/(double)(width * height);
}
else
{
xGc = width / 2;
yGc = height / 2;
ellipseHeight = 0;
ellipseWidth = 0;
ellipseAngle = 0;
density = 0;
}
}
void CvFuzzyMeanShiftTracker::SearchWindow::getResizeAttribsEdgeDensityLinear(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh) {
int x1 = horizontalEdgeTop;
int x2 = horizontalEdgeBottom;
int y1 = verticalEdgeLeft;
int y2 = verticalEdgeRight;
int gx = (width*2)/5;
int gy = (height*2)/5;
int lx = width/10;
int ly = height/10;
resizeDy = 0;
resizeDh = 0;
resizeDx = 0;
resizeDw = 0;
if (x1 > gx) {
resizeDy = -1;
} else if (x1 < lx) {
resizeDy = +1;
}
if (x2 > gx) {
resizeDh = resizeDy + 1;
} else if (x2 < lx) {
resizeDh = - (resizeDy + 1);
} else {
resizeDh = - resizeDy;
}
if (y1 > gy) {
resizeDx = -1;
} else if (y1 < ly) {
resizeDx = +1;
}
if (y2 > gy) {
resizeDw = resizeDx + 1;
} else if (y2 < ly) {
resizeDw = - (resizeDx + 1);
} else {
resizeDw = - resizeDx;
}
}
void CvFuzzyMeanShiftTracker::SearchWindow::getResizeAttribsInnerDensity(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh)
{
int newWidth, newHeight, dx, dy;
double px, py;
newWidth = int(sqrt(double(m00)*1.3));
newHeight = int(newWidth*1.2);
dx = (newWidth - width);
dy = (newHeight - height);
px = (double)xGc/(double)width;
py = (double)yGc/(double)height;
resizeDx = (int)(px*dx);
resizeDy = (int)(py*dy);
resizeDw = (int)((1-px)*dx);
resizeDh = (int)((1-py)*dy);
}
void CvFuzzyMeanShiftTracker::SearchWindow::getResizeAttribsEdgeDensityFuzzy(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh)
{
double dx1=0, dx2, dy1, dy2;
resizeDy = 0;
resizeDh = 0;
resizeDx = 0;
resizeDw = 0;
if (fuzzyResizer == NULL)
fuzzyResizer = new FuzzyResizer();
dx2 = fuzzyResizer->calcOutput(double(verticalEdgeRight)/double(height), density);
if (dx1 == dx2)
{
resizeDx = int(-dx1);
resizeDw = int(dx1+dx2);
}
dy1 = fuzzyResizer->calcOutput(double(horizontalEdgeTop)/double(width), density);
dy2 = fuzzyResizer->calcOutput(double(horizontalEdgeBottom)/double(width), density);
dx1 = fuzzyResizer->calcOutput(double(verticalEdgeLeft)/double(height), density);
dx2 = fuzzyResizer->calcOutput(double(verticalEdgeRight)/double(height), density);
//if (dx1 == dx2)
{
resizeDx = int(-dx1);
resizeDw = int(dx1+dx2);
}
dy1 = fuzzyResizer->calcOutput(double(horizontalEdgeTop)/double(width), density);
dy2 = fuzzyResizer->calcOutput(double(horizontalEdgeBottom)/double(width), density);
//if (dy1 == dy2)
{
resizeDy = int(-dy1);
resizeDh = int(dy1+dy2);
}
}
bool CvFuzzyMeanShiftTracker::SearchWindow::meanShift(IplImage *maskImage, IplImage *depthMap, int maxIteration, bool initDepth)
{
numShifts = 0;
do
{
extractInfo(maskImage, depthMap, initDepth);
if (! shift())
return true;
} while (++numShifts < maxIteration);
return false;
}
void CvFuzzyMeanShiftTracker::findOptimumSearchWindow(SearchWindow &searchWindow, IplImage *maskImage, IplImage *depthMap, int maxIteration, int resizeMethod, bool initDepth)
{
int resizeDx, resizeDy, resizeDw, resizeDh;
resizeDx = 0;
resizeDy = 0;
resizeDw = 0;
resizeDh = 0;
searchWindow.numIters = 0;
for (int i = 0; i < maxIteration; i++)
{
searchWindow.numIters++;
searchWindow.meanShift(maskImage, depthMap, MaxMeanShiftIteration, initDepth);
switch (resizeMethod)
{
case rmEdgeDensityLinear :
searchWindow.getResizeAttribsEdgeDensityLinear(resizeDx, resizeDy, resizeDw, resizeDh);
break;
case rmEdgeDensityFuzzy :
//searchWindow.getResizeAttribsEdgeDensityLinear(resizeDx, resizeDy, resizeDw, resizeDh);
searchWindow.getResizeAttribsEdgeDensityFuzzy(resizeDx, resizeDy, resizeDw, resizeDh);
break;
case rmInnerDensity :
searchWindow.getResizeAttribsInnerDensity(resizeDx, resizeDy, resizeDw, resizeDh);
break;
default:
searchWindow.getResizeAttribsEdgeDensityLinear(resizeDx, resizeDy, resizeDw, resizeDh);
}
searchWindow.ldx = resizeDx;
searchWindow.ldy = resizeDy;
searchWindow.ldw = resizeDw;
searchWindow.ldh = resizeDh;
if ((resizeDx == 0) && (resizeDy == 0) && (resizeDw == 0) && (resizeDh == 0))
break;
searchWindow.setSize(searchWindow.x + resizeDx, searchWindow.y + resizeDy, searchWindow.width + resizeDw, searchWindow.height + resizeDh);
}
}
CvFuzzyMeanShiftTracker::CvFuzzyMeanShiftTracker()
{
searchMode = tsSetWindow;
}
CvFuzzyMeanShiftTracker::~CvFuzzyMeanShiftTracker()
{
// nothing to do
}
void CvFuzzyMeanShiftTracker::track(IplImage *maskImage, IplImage *depthMap, int resizeMethod, bool resetSearch, int minKernelMass)
{
bool initDepth = false;
if (resetSearch)
searchMode = tsSetWindow;
switch (searchMode)
{
case tsDisabled:
return;
case tsSearching:
return;
case tsSetWindow:
kernel.maxWidth = maskImage->width;
kernel.maxHeight = maskImage->height;
kernel.setSize(0, 0, maskImage->width, maskImage->height);
initDepth = true;
case tsTracking:
searchMode = tsSearching;
findOptimumSearchWindow(kernel, maskImage, depthMap, MaxSetSizeIteration, resizeMethod, initDepth);
if ((kernel.density == 0) || (kernel.m00 < minKernelMass))
searchMode = tsSetWindow;
else
searchMode = tsTracking;
}
}
| 18,919
| 6,899
|
#define NCPP_EXCEPTIONS_PLEASE
//
// This is a **build** test - it does nothing else except ensure that all the C++ wrapper classes are included and that
// the program builds.
//
// Once there are demos which exercise all the C++ classes this "test" can be removed
//
#include <cstdlib>
#include <clocale>
#include <iostream>
#include <ncpp/NotCurses.hh>
#include <ncpp/Menu.hh>
#include <ncpp/Plane.hh>
#include <ncpp/Reel.hh>
#include <ncpp/MultiSelector.hh>
#include <ncpp/Selector.hh>
#include <ncpp/Visual.hh>
#include <ncpp/Direct.hh>
#include <ncpp/Plot.hh>
#include <ncpp/FDPlane.hh>
#include <ncpp/Subproc.hh>
using namespace ncpp;
int run ()
{
NotCurses nc;
const char *ncver = nc.version ();
{
Plane p1 (1, 1, 0, 0);
Plot plot1 (p1);
Plane p2 (1, 1, 0, 0);
PlotU plot2 (p2);
Plane p3 (1, 1, 0, 0);
PlotD plot3 (p3);
}
nc.stop ();
Direct direct (getenv ("TERM"));
direct.set_fg_rgb (0xb5, 0x0d, 0xff);
std::cout << "notcurses version: ";
direct.set_bg_rgb (0x05, 0x6e, 0xee);
direct.set_fg_rgb (0xe2, 0xbf, 0x00);
std::cout << ncver << std::endl;
return 0;
}
int main ()
{
if (!setlocale (LC_ALL, "")){
std::cerr << "Couldn't set locale based on user preferences" << std::endl;
return EXIT_FAILURE;
}
try {
return run ();
} catch (ncpp::init_error &e) {
std::cerr << "Initialization error: " << e.what () << std::endl;
} catch (ncpp::invalid_state_error &e) {
std::cerr << "Invalid state error: " << e.what () << std::endl;
} catch (ncpp::invalid_argument &e) {
std::cerr << "Invalid argument error: " << e.what () << std::endl;
}
return 1;
}
| 1,608
| 694
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <string>
#include <sstream>
#include <fstream>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "boost/filesystem.hpp"
#include "json2pb/json_to_pb.h"
#include "util/logging.h"
#include "util/file_utils.h"
#include "olap/olap_meta.h"
#include "olap/tablet_meta.h"
#include "olap/rowset/rowset_writer.h"
#include "olap/rowset/rowset_writer_context.h"
#include "olap/rowset/rowset_reader_context.h"
#include "olap/rowset/rowset_factory.h"
#include "olap/rowset/rowset_reader.h"
#include "olap/rowset/rowset_converter.h"
#include "olap/data_dir.h"
#include "olap/storage_engine.h"
#include "olap/olap_cond.h"
#ifndef BE_TEST
#define BE_TEST
#endif
using ::testing::_;
using ::testing::Return;
using ::testing::SetArgPointee;
using std::string;
namespace doris {
static const uint32_t MAX_PATH_LEN = 1024;
void create_rowset_writer_context(TabletSchema* tablet_schema, RowsetTypePB dst_type,
RowsetWriterContext* rowset_writer_context) {
RowsetId rowset_id;
rowset_id.init(10000);
rowset_writer_context->rowset_id = rowset_id;
rowset_writer_context->tablet_id = 12345;
rowset_writer_context->tablet_schema_hash = 1111;
rowset_writer_context->partition_id = 10;
rowset_writer_context->rowset_type = dst_type;
rowset_writer_context->rowset_path_prefix = config::storage_root_path + "/data/0/12345/1111";
rowset_writer_context->rowset_state = VISIBLE;
rowset_writer_context->tablet_schema = tablet_schema;
rowset_writer_context->version.first = 0;
rowset_writer_context->version.second = 1;
rowset_writer_context->version_hash = 110;
}
void create_rowset_reader_context(TabletSchema* tablet_schema, const std::vector<uint32_t>* return_columns,
const DeleteHandler* delete_handler, std::vector<ColumnPredicate*>* predicates,
std::set<uint32_t>* load_bf_columns, Conditions* conditions, RowsetReaderContext* rowset_reader_context) {
rowset_reader_context->reader_type = READER_ALTER_TABLE;
rowset_reader_context->tablet_schema = tablet_schema;
rowset_reader_context->need_ordered_result = true;
rowset_reader_context->return_columns = return_columns;
rowset_reader_context->seek_columns = return_columns;
rowset_reader_context->delete_handler = delete_handler;
rowset_reader_context->lower_bound_keys = nullptr;
rowset_reader_context->is_lower_keys_included = nullptr;
rowset_reader_context->upper_bound_keys = nullptr;
rowset_reader_context->is_upper_keys_included = nullptr;
rowset_reader_context->predicates = predicates;
rowset_reader_context->load_bf_columns = load_bf_columns;
rowset_reader_context->conditions = conditions;
}
void create_tablet_schema(KeysType keys_type, TabletSchema* tablet_schema) {
TabletSchemaPB tablet_schema_pb;
tablet_schema_pb.set_keys_type(keys_type);
tablet_schema_pb.set_num_short_key_columns(2);
tablet_schema_pb.set_num_rows_per_row_block(1024);
tablet_schema_pb.set_compress_kind(COMPRESS_NONE);
tablet_schema_pb.set_next_column_unique_id(4);
ColumnPB* column_1 = tablet_schema_pb.add_column();
column_1->set_unique_id(1);
column_1->set_name("k1");
column_1->set_type("INT");
column_1->set_is_key(true);
column_1->set_length(4);
column_1->set_index_length(4);
column_1->set_is_nullable(false);
column_1->set_is_bf_column(false);
ColumnPB* column_2 = tablet_schema_pb.add_column();
column_2->set_unique_id(2);
column_2->set_name("k2");
column_2->set_type("VARCHAR");
column_2->set_length(20);
column_2->set_index_length(20);
column_2->set_is_key(true);
column_2->set_is_nullable(false);
column_2->set_is_bf_column(false);
ColumnPB* column_3 = tablet_schema_pb.add_column();
column_3->set_unique_id(3);
column_3->set_name("v1");
column_3->set_type("INT");
column_3->set_length(4);
column_3->set_is_key(false);
column_3->set_is_nullable(false);
column_3->set_is_bf_column(false);
column_3->set_aggregation("SUM");
tablet_schema->init_from_pb(tablet_schema_pb);
}
void create_tablet_meta(TabletSchema* tablet_schema, TabletMeta* tablet_meta) {
TabletMetaPB tablet_meta_pb;
tablet_meta_pb.set_table_id(10000);
tablet_meta_pb.set_tablet_id(12345);
tablet_meta_pb.set_schema_hash(1111);
tablet_meta_pb.set_partition_id(10);
tablet_meta_pb.set_shard_id(0);
tablet_meta_pb.set_creation_time(1575020449);
tablet_meta_pb.set_tablet_state(PB_RUNNING);
PUniqueId* tablet_uid = tablet_meta_pb.mutable_tablet_uid();
tablet_uid->set_hi(10);
tablet_uid->set_lo(10);
TabletSchemaPB* tablet_schema_pb = tablet_meta_pb.mutable_schema();
tablet_schema->to_schema_pb(tablet_schema_pb);
tablet_meta->init_from_pb(tablet_meta_pb);
}
class RowsetConverterTest : public testing::Test {
public:
virtual void SetUp() {
config::path_gc_check = false;
char buffer[MAX_PATH_LEN];
getcwd(buffer, MAX_PATH_LEN);
config::storage_root_path = std::string(buffer) + "/data_test";
FileUtils::remove_all(config::storage_root_path);
ASSERT_TRUE(FileUtils::create_dir(config::storage_root_path).ok());
std::vector<StorePath> paths;
paths.emplace_back(config::storage_root_path, -1);
std::string data_path = config::storage_root_path + "/data";
ASSERT_TRUE(FileUtils::create_dir(data_path).ok());
std::string shard_path = data_path + "/0";
ASSERT_TRUE(FileUtils::create_dir(shard_path).ok());
std::string tablet_path = shard_path + "/12345";
ASSERT_TRUE(FileUtils::create_dir(tablet_path).ok());
_schema_hash_path = tablet_path + "/1111";
ASSERT_TRUE(FileUtils::create_dir(_schema_hash_path).ok());
_mem_tracker.reset(new MemTracker(-1));
_mem_pool.reset(new MemPool(_mem_tracker.get()));
}
virtual void TearDown() {
FileUtils::remove_all(config::storage_root_path);
}
void process(RowsetTypePB src_type, RowsetTypePB dst_type);
private:
std::string _schema_hash_path;
std::unique_ptr<MemTracker> _mem_tracker;
std::unique_ptr<MemPool> _mem_pool;
};
void RowsetConverterTest::process(RowsetTypePB src_type, RowsetTypePB dst_type) {
// write
TabletSchema tablet_schema;
create_tablet_schema(AGG_KEYS, &tablet_schema);
RowsetWriterContext rowset_writer_context;
create_rowset_writer_context(&tablet_schema, src_type, &rowset_writer_context);
std::unique_ptr<RowsetWriter> _rowset_writer;
ASSERT_EQ(OLAP_SUCCESS, RowsetFactory::create_rowset_writer(rowset_writer_context, &_rowset_writer));
RowCursor row;
OLAPStatus res = row.init(tablet_schema);
ASSERT_EQ(OLAP_SUCCESS, res);
for (int i = 0; i < 1024; ++i) {
int32_t field_0 = i;
row.set_field_content(0, reinterpret_cast<char*>(&field_0), _mem_pool.get());
Slice field_1("well" + std::to_string(i));
row.set_field_content(1, reinterpret_cast<char*>(&field_1), _mem_pool.get());
int32_t field_2 = 10000 + i;
row.set_field_content(2, reinterpret_cast<char*>(&field_2), _mem_pool.get());
_rowset_writer->add_row(row);
}
_rowset_writer->flush();
auto cache = new_lru_cache(config::file_descriptor_cache_capacity);
FileHandler::set_fd_cache(cache);
RowsetSharedPtr src_rowset = _rowset_writer->build();
ASSERT_TRUE(src_rowset != nullptr);
RowsetId src_rowset_id;
src_rowset_id.init(10000);
ASSERT_EQ(src_rowset_id, src_rowset->rowset_id());
ASSERT_EQ(1024, src_rowset->num_rows());
// convert
TabletMetaSharedPtr tablet_meta(new TabletMeta());
create_tablet_meta(&tablet_schema, tablet_meta.get());
RowsetConverter rowset_converter(tablet_meta);
RowsetMetaPB dst_rowset_meta_pb;
if (dst_type == BETA_ROWSET) {
ASSERT_EQ(OLAP_SUCCESS, rowset_converter.convert_alpha_to_beta(
src_rowset->rowset_meta(), _schema_hash_path, &dst_rowset_meta_pb));
} else {
ASSERT_EQ(OLAP_SUCCESS, rowset_converter.convert_beta_to_alpha(
src_rowset->rowset_meta(), _schema_hash_path, &dst_rowset_meta_pb));
}
ASSERT_EQ(dst_type, dst_rowset_meta_pb.rowset_type());
ASSERT_EQ(12345, dst_rowset_meta_pb.tablet_id());
ASSERT_EQ(1024, dst_rowset_meta_pb.num_rows());
// read
RowsetMetaSharedPtr dst_rowset_meta(new RowsetMeta());
ASSERT_TRUE(dst_rowset_meta->init_from_pb(dst_rowset_meta_pb));
RowsetSharedPtr dst_rowset;
ASSERT_EQ(OLAP_SUCCESS, RowsetFactory::create_rowset(&tablet_schema,
_schema_hash_path, dst_rowset_meta, &dst_rowset));
RowsetReaderSharedPtr dst_rowset_reader;
ASSERT_EQ(OLAP_SUCCESS, dst_rowset->create_reader(&dst_rowset_reader));
RowsetReaderContext rowset_reader_context;
std::set<uint32_t> load_bf_columns;
std::vector<ColumnPredicate*> predicates;
Conditions conditions;
std::vector<uint32_t> return_columns;
for (int i = 0; i < tablet_schema.num_columns(); ++i) {
return_columns.push_back(i);
}
DeleteHandler delete_handler;
create_rowset_reader_context(&tablet_schema, &return_columns, &delete_handler,
&predicates, &load_bf_columns, &conditions, &rowset_reader_context);
res = dst_rowset_reader->init(&rowset_reader_context);
ASSERT_EQ(OLAP_SUCCESS, res);
RowBlock* row_block = nullptr;
res = dst_rowset_reader->next_block(&row_block);
ASSERT_EQ(OLAP_SUCCESS, res);
ASSERT_EQ(1024, row_block->remaining());
RowCursor row_cursor;
row_cursor.init(tablet_schema);
for (int i = 0; i < 1024; ++i) {
row_block->get_row(i, &row_cursor);
ASSERT_EQ(i, *(uint32_t*)row_cursor.cell_ptr(0));
ASSERT_EQ("well" + std::to_string(i), (*(Slice*)row_cursor.cell_ptr(1)).to_string());
ASSERT_EQ(10000 + i, *(uint32_t*)row_cursor.cell_ptr(2));
}
}
TEST_F(RowsetConverterTest, TestConvertAlphaRowsetToBeta) {
process(ALPHA_ROWSET, BETA_ROWSET);
}
TEST_F(RowsetConverterTest, TestConvertBetaRowsetToAlpha) {
process(ALPHA_ROWSET, BETA_ROWSET);
}
} // namespace doris
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 11,047
| 4,128
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkCurvatureNDAnisotropicDiffusionFunction_hxx
#define itkCurvatureNDAnisotropicDiffusionFunction_hxx
#include "itkCurvatureNDAnisotropicDiffusionFunction.h"
namespace itk
{
template <typename TImage>
double CurvatureNDAnisotropicDiffusionFunction<TImage>::m_MIN_NORM = 1.0e-10;
template <typename TImage>
CurvatureNDAnisotropicDiffusionFunction<TImage>::CurvatureNDAnisotropicDiffusionFunction()
: m_K(0.0)
{
unsigned int i, j;
RadiusType r;
for (i = 0; i < ImageDimension; ++i)
{
r[i] = 1;
}
this->SetRadius(r);
// Dummy neighborhood used to set up the slices.
Neighborhood<PixelType, ImageDimension> it;
it.SetRadius(r);
// Slice the neighborhood
m_Center = it.Size() / 2;
for (i = 0; i < ImageDimension; ++i)
{
m_Stride[i] = it.GetStride(i);
x_slice[i] = std::slice(m_Center - m_Stride[i], 3, m_Stride[i]);
}
for (i = 0; i < ImageDimension; ++i)
{
for (j = 0; j < ImageDimension; ++j)
{
// For taking derivatives in the i direction that are offset one
// pixel in the j direction.
xa_slice[i][j] = std::slice((m_Center + m_Stride[j]) - m_Stride[i], 3, m_Stride[i]);
xd_slice[i][j] = std::slice((m_Center - m_Stride[j]) - m_Stride[i], 3, m_Stride[i]);
}
}
// Allocate the derivative operator.
m_DerivativeOperator.SetDirection(0); // Not relevant, will be applied in a slice-based
// fashion.
m_DerivativeOperator.SetOrder(1);
m_DerivativeOperator.CreateDirectional();
}
template <typename TImage>
typename CurvatureNDAnisotropicDiffusionFunction<TImage>::PixelType
CurvatureNDAnisotropicDiffusionFunction<TImage>::ComputeUpdate(const NeighborhoodType & it,
void * itkNotUsed(globalData),
const FloatOffsetType & itkNotUsed(offset))
{
unsigned int i, j;
double speed, dx_forward_Cn, dx_backward_Cn, propagation_gradient;
double grad_mag_sq, grad_mag_sq_d, grad_mag, grad_mag_d;
double Cx, Cxd;
double dx_forward[ImageDimension];
double dx_backward[ImageDimension];
double dx[ImageDimension];
double dx_aug;
double dx_dim;
// Calculate the partial derivatives for each dimension
for (i = 0; i < ImageDimension; i++)
{
// "Half" derivatives
dx_forward[i] = it.GetPixel(m_Center + m_Stride[i]) - it.GetPixel(m_Center);
dx_forward[i] *= this->m_ScaleCoefficients[i];
dx_backward[i] = it.GetPixel(m_Center) - it.GetPixel(m_Center - m_Stride[i]);
dx_backward[i] *= this->m_ScaleCoefficients[i];
// Centralized differences
dx[i] = m_InnerProduct(x_slice[i], it, m_DerivativeOperator);
dx[i] *= this->m_ScaleCoefficients[i];
}
speed = 0.0;
for (i = 0; i < ImageDimension; i++)
{
// Gradient magnitude approximations
grad_mag_sq = dx_forward[i] * dx_forward[i];
grad_mag_sq_d = dx_backward[i] * dx_backward[i];
for (j = 0; j < ImageDimension; j++)
{
if (j != i)
{
dx_aug = m_InnerProduct(xa_slice[j][i], it, m_DerivativeOperator);
dx_aug *= this->m_ScaleCoefficients[j];
dx_dim = m_InnerProduct(xd_slice[j][i], it, m_DerivativeOperator);
dx_dim *= this->m_ScaleCoefficients[j];
grad_mag_sq += 0.25f * (dx[j] + dx_aug) * (dx[j] + dx_aug);
grad_mag_sq_d += 0.25f * (dx[j] + dx_dim) * (dx[j] + dx_dim);
}
}
grad_mag = std::sqrt(m_MIN_NORM + grad_mag_sq);
grad_mag_d = std::sqrt(m_MIN_NORM + grad_mag_sq_d);
// Conductance Terms
if (m_K == 0.0)
{
Cx = 0.0;
Cxd = 0.0;
}
else
{
Cx = std::exp(grad_mag_sq / m_K);
Cxd = std::exp(grad_mag_sq_d / m_K);
}
// First order normalized finite-difference conductance products
dx_forward_Cn = (dx_forward[i] / grad_mag) * Cx;
dx_backward_Cn = (dx_backward[i] / grad_mag_d) * Cxd;
// Second order conductance-modified curvature
speed += (dx_forward_Cn - dx_backward_Cn);
}
// "Upwind" gradient magnitude term
propagation_gradient = 0.0;
if (speed > 0)
{
for (i = 0; i < ImageDimension; i++)
{
propagation_gradient +=
itk::Math::sqr(std::min(dx_backward[i], 0.0)) + itk::Math::sqr(std::max(dx_forward[i], 0.0));
}
}
else
{
for (i = 0; i < ImageDimension; i++)
{
propagation_gradient +=
itk::Math::sqr(std::max(dx_backward[i], 0.0)) + itk::Math::sqr(std::min(dx_forward[i], 0.0));
}
}
return static_cast<PixelType>(std::sqrt(propagation_gradient) * speed);
}
} // end namespace itk
#endif
| 5,429
| 2,006
|
/*****************************************************************************
* \file
* \brief This header defines the type 'monotype'
*****************************************************************************/
/*
The MIT License (MIT)
Bit Standard Template Library.
https://github.com/bitwizeshift/bit-stl
Copyright (c) 2018 Matthew Rodusek
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.
*/
#ifndef BIT_STL_UTILITIES_MONOSTATE_HPP
#define BIT_STL_UTILITIES_MONOSTATE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "hash.hpp" // hash_t
#include <cstddef> // std::size_t
namespace bit {
namespace stl {
//=========================================================================
// 23.7.8, class monostate
//=========================================================================
///////////////////////////////////////////////////////////////////////////
/// \brief Unit type intended for use as a well-behaved empty alternative
/// in \c variant.
///
/// In particular, a variant of non-default-constructible types may list
/// monostate as its first alternative: this makes the variant itself
/// default-constructible.
///////////////////////////////////////////////////////////////////////////
struct monostate{};
//-------------------------------------------------------------------------
// Comparison
//-------------------------------------------------------------------------
constexpr bool operator<(monostate, monostate) noexcept;
constexpr bool operator>(monostate, monostate) noexcept;
constexpr bool operator<=(monostate, monostate) noexcept;
constexpr bool operator>=(monostate, monostate) noexcept;
constexpr bool operator==(monostate, monostate) noexcept;
constexpr bool operator!=(monostate, monostate) noexcept;
//-------------------------------------------------------------------------
// Utilities
//-------------------------------------------------------------------------
/// \brief Hashes the monostate
///
/// \return 0
constexpr hash_t hash_value( const monostate& );
} // namespace stl
} // namespace bit
#include "detail/monostate.inl"
#endif /* BIT_STL_UTILITIES_MONOSTATE_HPP */
| 3,346
| 953
|
/*** Copyright (c), The Unregents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* rsQuerySpecColl.c
*/
#include "querySpecColl.h"
#include "rcMisc.h"
#include "fileOpendir.h"
#include "fileReaddir.h"
#include "fileClosedir.h"
#include "objMetaOpr.hpp"
#include "specColl.hpp"
#include "dataObjClose.h"
#include "subStructFileOpendir.h"
#include "subStructFileReaddir.h"
#include "subStructFileClosedir.h"
#include "fileStat.h"
#include "genQuery.h"
#include "rsGlobalExtern.hpp"
#include "rcGlobalExtern.h"
#include "rsQuerySpecColl.hpp"
#include "rsSubStructFileReaddir.hpp"
#include "rsDataObjClose.hpp"
#include "rsFileReaddir.hpp"
#include "rsSubStructFileClosedir.hpp"
#include "rsFileClosedir.hpp"
#include "rsSubStructFileOpendir.hpp"
#include "rsFileOpendir.hpp"
#include "rsObjStat.hpp"
#include "irods_resource_backport.hpp"
#include "irods_resource_redirect.hpp"
#include "irods_stacktrace.hpp"
#include "irods_hierarchy_parser.hpp"
int
rsQuerySpecColl( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
genQueryOut_t **genQueryOut ) {
int specCollInx;
int status;
int continueFlag; /* continue query */
int remoteFlag;
rodsServerHost_t *rodsServerHost;
remoteFlag = getAndConnRcatHost(
rsComm,
SLAVE_RCAT,
( const char* )dataObjInp->objPath,
&rodsServerHost );
if ( remoteFlag < 0 ) {
return remoteFlag;
}
else if ( remoteFlag == REMOTE_HOST ) {
status = rcQuerySpecColl( rodsServerHost->conn, dataObjInp,
genQueryOut );
return status;
}
// =-=-=-=-=-=-=-
// working on the "home zone", determine if we need to redirect to a different
// server in this zone for this operation. if there is a RESC_HIER_STR_KW then
// we know that the redirection decision has already been made
char* hier_kw = getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW );
if (!hier_kw) {
try {
auto result = irods::resolve_resource_hierarchy(irods::OPEN_OPERATION, rsComm, *dataObjInp);
const auto& hier = std::get<std::string>(result);
addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() );
}
catch (const irods::exception& e ) {
irods::log(e);
return e.code();
}
}
if ( ( specCollInx = dataObjInp->openFlags ) <= 0 ) {
specCollInx = openSpecColl( rsComm, dataObjInp, -1 );
if ( specCollInx < 0 ) {
rodsLog( LOG_NOTICE,
"rsQuerySpecColl: openSpecColl error for %s, status = %d",
dataObjInp->objPath, specCollInx );
return specCollInx;
}
continueFlag = 0;
}
else {
continueFlag = 1;
}
initOutForQuerySpecColl( genQueryOut );
status = _rsQuerySpecColl( rsComm, specCollInx, dataObjInp,
*genQueryOut, continueFlag );
if ( status < 0 ) {
freeGenQueryOut( genQueryOut );
}
return status;
}
int
openSpecColl( rsComm_t *rsComm, dataObjInp_t *dataObjInp, int parentInx ) {
int specCollInx;
dataObjInfo_t *dataObjInfo = NULL;
int status;
int l3descInx;
status = resolvePathInSpecColl( rsComm, dataObjInp->objPath,
//READ_COLL_PERM, 0, &dataObjInfo);
UNKNOWN_COLL_PERM, 0, &dataObjInfo );
if ( status < 0 || NULL == dataObjInfo ) { // JMC cppcheck - nullptr
rodsLog( LOG_NOTICE,
"rsQuerySpecColl: resolveSpecColl error for %s, status = %d",
dataObjInp->objPath, status );
return status;
}
if ( dataObjInfo->specColl->collClass == LINKED_COLL ) {
rodsLog( LOG_ERROR,
"rsQuerySpecColl: %s is a linked collection",
dataObjInp->objPath );
return SYS_UNKNOWN_SPEC_COLL_CLASS;
}
char* resc_hier = getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW );
if ( resc_hier ) {
strncpy( dataObjInfo->rescHier, resc_hier, MAX_NAME_LEN );
irods::error ret = resc_mgr.hier_to_leaf_id(resc_hier,dataObjInfo->rescId);
if( !ret.ok() ) {
irods::log(PASS(ret));
}
}
l3descInx = l3Opendir( rsComm, dataObjInfo );
if ( l3descInx < 0 ) {
rodsLog( LOG_NOTICE,
"openSpecColl: specCollOpendir error for %s, status = %d",
dataObjInp->objPath, l3descInx );
return l3descInx;
}
specCollInx = allocSpecCollDesc();
if ( specCollInx < 0 ) {
freeDataObjInfo( dataObjInfo );
return specCollInx;
}
SpecCollDesc[specCollInx].l3descInx = l3descInx;
SpecCollDesc[specCollInx].dataObjInfo = dataObjInfo;
SpecCollDesc[specCollInx].parentInx = parentInx;
return specCollInx;
}
int
initOutForQuerySpecColl( genQueryOut_t **genQueryOut ) {
genQueryOut_t *myGenQueryOut;
/* will do collection, dataName, createTime, modifyTime, objSize */
myGenQueryOut = *genQueryOut =
( genQueryOut_t * ) malloc( sizeof( genQueryOut_t ) );
memset( myGenQueryOut, 0, sizeof( genQueryOut_t ) );
myGenQueryOut->attriCnt = 5;
myGenQueryOut->sqlResult[0].attriInx = COL_COLL_NAME;
myGenQueryOut->sqlResult[0].len = MAX_NAME_LEN;
myGenQueryOut->sqlResult[0].value =
( char* )malloc( MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[0].value, 0,
MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[1].attriInx = COL_DATA_NAME;
myGenQueryOut->sqlResult[1].len = MAX_NAME_LEN;
myGenQueryOut->sqlResult[1].value =
( char* )malloc( MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[1].value, 0,
MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[2].attriInx = COL_D_CREATE_TIME;
myGenQueryOut->sqlResult[2].len = NAME_LEN;
myGenQueryOut->sqlResult[2].value =
( char* )malloc( NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[2].value, 0,
NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[3].attriInx = COL_D_MODIFY_TIME;
myGenQueryOut->sqlResult[3].len = NAME_LEN;
myGenQueryOut->sqlResult[3].value =
( char* )malloc( NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[3].value, 0,
NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[4].attriInx = COL_DATA_SIZE;
myGenQueryOut->sqlResult[4].len = NAME_LEN;
myGenQueryOut->sqlResult[4].value =
( char* )malloc( NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[4].value, 0,
NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->continueInx = -1;
return 0;
}
int
_rsQuerySpecColl( rsComm_t *rsComm, int specCollInx,
dataObjInp_t *dataObjInp, genQueryOut_t *genQueryOut, int continueFlag ) {
int status = 0;
rodsDirent_t *rodsDirent = NULL;
dataObjInfo_t *dataObjInfo;
int rowCnt;
objType_t selObjType;
char *tmpStr;
dataObjInp_t newDataObjInp;
int recurFlag;
if ( SpecCollDesc[specCollInx].inuseFlag != FD_INUSE ) {
rodsLog( LOG_ERROR,
"_rsQuerySpecColl: Input specCollInx %d not active", specCollInx );
return BAD_INPUT_DESC_INDEX;
}
if ( ( tmpStr = getValByKey( &dataObjInp->condInput, SEL_OBJ_TYPE_KW ) ) !=
NULL ) {
if ( strcmp( tmpStr, "dataObj" ) == 0 ) {
selObjType = DATA_OBJ_T;
}
else {
selObjType = COLL_OBJ_T;
}
}
else {
selObjType = UNKNOWN_OBJ_T;
}
if ( getValByKey( &dataObjInp->condInput, RECURSIVE_OPR__KW ) != NULL ) {
recurFlag = 1;
}
else {
recurFlag = 0;
}
dataObjInfo = SpecCollDesc[specCollInx].dataObjInfo;
while ( genQueryOut->rowCnt < MAX_SPEC_COLL_ROW ) {
dataObjInfo_t myDataObjInfo;
rodsDirent_t myRodsDirent;
status = specCollReaddir( rsComm, specCollInx, &rodsDirent );
if ( status < 0 ) {
break;
}
myRodsDirent = *rodsDirent;
free( rodsDirent );
if ( strcmp( myRodsDirent.d_name, "." ) == 0 ||
strcmp( myRodsDirent.d_name, ".." ) == 0 ) {
continue;
}
myDataObjInfo = *dataObjInfo;
snprintf( myDataObjInfo.subPath, MAX_NAME_LEN, "%s/%s",
dataObjInfo->subPath, myRodsDirent.d_name );
snprintf( myDataObjInfo.filePath, MAX_NAME_LEN, "%s/%s",
dataObjInfo->filePath, myRodsDirent.d_name );
rodsStat_t *fileStatOut = NULL;
status = l3Stat( rsComm, &myDataObjInfo, &fileStatOut );
if ( status < 0 ) {
rodsLog( LOG_ERROR,
"_rsQuerySpecColl: l3Stat for %s error, status = %d",
myDataObjInfo.filePath, status );
/* XXXXX need clean up */
return status;
}
if ( ( fileStatOut->st_mode & S_IFREG ) != 0 ) { /* a file */
if ( selObjType == COLL_OBJ_T ) {
free( fileStatOut );
continue;
}
rowCnt = genQueryOut->rowCnt;
rstrcpy( &genQueryOut->sqlResult[0].value[MAX_NAME_LEN * rowCnt],
dataObjInfo->subPath, MAX_NAME_LEN );
rstrcpy( &genQueryOut->sqlResult[1].value[MAX_NAME_LEN * rowCnt],
myRodsDirent.d_name, MAX_NAME_LEN );
snprintf( &genQueryOut->sqlResult[2].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_ctim );
snprintf( &genQueryOut->sqlResult[3].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_mtim );
snprintf( &genQueryOut->sqlResult[4].value[NAME_LEN * rowCnt],
NAME_LEN, "%lld", fileStatOut->st_size );
free( fileStatOut );
genQueryOut->rowCnt++;
}
else {
if ( selObjType != DATA_OBJ_T ) {
rowCnt = genQueryOut->rowCnt;
rstrcpy( &genQueryOut->sqlResult[0].value[MAX_NAME_LEN * rowCnt],
myDataObjInfo.subPath, MAX_NAME_LEN );
snprintf( &genQueryOut->sqlResult[2].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_ctim );
snprintf( &genQueryOut->sqlResult[3].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_mtim );
snprintf( &genQueryOut->sqlResult[4].value[NAME_LEN * rowCnt],
NAME_LEN, "%lld", fileStatOut->st_size );
genQueryOut->rowCnt++;
}
free( fileStatOut );
if ( recurFlag > 0 ) {
/* need to drill down */
int newSpecCollInx;
newDataObjInp = *dataObjInp;
rstrcpy( newDataObjInp.objPath, dataObjInfo->subPath,
MAX_NAME_LEN );
newSpecCollInx =
openSpecColl( rsComm, &newDataObjInp, specCollInx );
if ( newSpecCollInx < 0 ) {
rodsLog( LOG_ERROR,
"_rsQuerySpecColl: openSpecColl err for %s, stat = %d",
newDataObjInp.objPath, newSpecCollInx );
status = newSpecCollInx;
break;
}
status = _rsQuerySpecColl( rsComm, newSpecCollInx,
&newDataObjInp, genQueryOut, 0 );
if ( status < 0 ) {
break;
}
}
}
} // while
if ( status == EOF || status == CAT_NO_ROWS_FOUND ) {
status = 0;
}
if ( genQueryOut->rowCnt < MAX_SPEC_COLL_ROW ) {
int parentInx;
/* get to the end or error */
specCollClosedir( rsComm, specCollInx );
parentInx = SpecCollDesc[specCollInx].parentInx;
freeSpecCollDesc( specCollInx );
if ( status >= 0 && recurFlag && continueFlag && parentInx > 0 ) {
newDataObjInp = *dataObjInp;
rstrcpy( newDataObjInp.objPath,
SpecCollDesc[parentInx].dataObjInfo->objPath, MAX_NAME_LEN );
status = _rsQuerySpecColl( rsComm, parentInx,
&newDataObjInp, genQueryOut, continueFlag );
}
else {
/* no more */
genQueryOut->continueInx = -1;
}
if ( status == EOF || status == CAT_NO_ROWS_FOUND ) {
status = 0;
}
}
else {
/* more to come */
if ( genQueryOut->continueInx < 0 ) {
/* if one does not already exist */
genQueryOut->continueInx = specCollInx;
}
}
if ( status >= 0 && genQueryOut->rowCnt == 0 ) {
status = CAT_NO_ROWS_FOUND;
}
return status;
}
int
specCollReaddir( rsComm_t *rsComm, int specCollInx, rodsDirent_t **rodsDirent ) {
fileReaddirInp_t fileReaddirInp;
specColl_t *specColl;
int status;
dataObjInfo_t *dataObjInfo = SpecCollDesc[specCollInx].dataObjInfo;
if ( dataObjInfo == NULL || ( specColl = dataObjInfo->specColl ) == NULL ) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// =-=-=-=-=-=-=-
// get the resc location of the hier leaf
std::string location;
irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location );
if ( !ret.ok() ) {
irods::log( PASSMSG( "specCollReaddir - failed in get_loc_for_hier_string", ret ) );
return -1;
}
if ( getStructFileType( dataObjInfo->specColl ) >= 0 ) {
subStructFileFdOprInp_t subStructFileReaddirInp;
memset( &subStructFileReaddirInp, 0, sizeof( subStructFileReaddirInp ) );
subStructFileReaddirInp.type = dataObjInfo->specColl->type;
subStructFileReaddirInp.fd = SpecCollDesc[specCollInx].l3descInx;
rstrcpy( subStructFileReaddirInp.addr.hostAddr,
location.c_str(), NAME_LEN );
rstrcpy( subStructFileReaddirInp.resc_hier,
dataObjInfo->rescHier,
MAX_NAME_LEN );
status = rsSubStructFileReaddir( rsComm, &subStructFileReaddirInp,
rodsDirent );
}
else if ( specColl->collClass == MOUNTED_COLL ) {
fileReaddirInp.fileInx = SpecCollDesc[specCollInx].l3descInx;
status = rsFileReaddir( rsComm, &fileReaddirInp, rodsDirent );
}
else {
rodsLog( LOG_ERROR,
"specCollReaddir: Unknown specColl collClass = %d",
specColl->collClass );
status = SYS_UNKNOWN_SPEC_COLL_CLASS;
}
return status;
}
int
specCollClosedir( rsComm_t *rsComm, int specCollInx ) {
fileClosedirInp_t fileClosedirInp;
specColl_t *specColl;
int status;
dataObjInfo_t *dataObjInfo = SpecCollDesc[specCollInx].dataObjInfo;
if ( dataObjInfo == NULL || ( specColl = dataObjInfo->specColl ) == NULL ) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// =-=-=-=-=-=-=-
// get the resc location of the hier leaf
std::string location;
irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location );
if ( !ret.ok() ) {
irods::log( PASSMSG( "specCollClosedir - failed in get_loc_for_hier_string", ret ) );
return -1;
}
if ( getStructFileType( dataObjInfo->specColl ) >= 0 ) {
subStructFileFdOprInp_t subStructFileClosedirInp;
memset( &subStructFileClosedirInp, 0, sizeof( subStructFileClosedirInp ) );
subStructFileClosedirInp.type = dataObjInfo->specColl->type;
subStructFileClosedirInp.fd = SpecCollDesc[specCollInx].l3descInx;
rstrcpy( subStructFileClosedirInp.addr.hostAddr,
location.c_str(),
NAME_LEN );
rstrcpy( subStructFileClosedirInp.resc_hier,
dataObjInfo->rescHier,
MAX_NAME_LEN );
status = rsSubStructFileClosedir( rsComm, &subStructFileClosedirInp );
}
else if ( specColl->collClass == MOUNTED_COLL ) {
fileClosedirInp.fileInx = SpecCollDesc[specCollInx].l3descInx;
status = rsFileClosedir( rsComm, &fileClosedirInp );
}
else {
rodsLog( LOG_ERROR,
"specCollClosedir: Unknown specColl collClass = %d",
specColl->collClass );
status = SYS_UNKNOWN_SPEC_COLL_CLASS;
}
return status;
}
int
l3Opendir( rsComm_t *rsComm, dataObjInfo_t *dataObjInfo ) {
fileOpendirInp_t fileOpendirInp;
int status;
if ( dataObjInfo == NULL ) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// =-=-=-=-=-=-=-
// get the resc location of the hier leaf
std::string location;
irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location );
if ( !ret.ok() ) {
irods::log( PASSMSG( "l3Opendir - failed in get_loc_for_hier_string", ret ) );
return -1;
}
if ( getStructFileType( dataObjInfo->specColl ) >= 0 ) {
subFile_t subStructFileOpendirInp;
memset( &subStructFileOpendirInp, 0, sizeof( subStructFileOpendirInp ) );
rstrcpy( subStructFileOpendirInp.subFilePath, dataObjInfo->subPath, MAX_NAME_LEN );
//rstrcpy( subStructFileOpendirInp.addr.hostAddr, dataObjInfo->rescInfo->rescLoc, NAME_LEN );
rstrcpy( subStructFileOpendirInp.addr.hostAddr, location.c_str(), NAME_LEN );
subStructFileOpendirInp.specColl = dataObjInfo->specColl;
status = rsSubStructFileOpendir( rsComm, &subStructFileOpendirInp );
}
else {
memset( &fileOpendirInp, 0, sizeof( fileOpendirInp ) );
rstrcpy( fileOpendirInp.dirName, dataObjInfo->filePath, MAX_NAME_LEN );
rstrcpy( fileOpendirInp.resc_name_, dataObjInfo->rescName, MAX_NAME_LEN );
rstrcpy( fileOpendirInp.resc_hier_, dataObjInfo->rescHier, MAX_NAME_LEN );
rstrcpy( fileOpendirInp.addr.hostAddr, location.c_str(), NAME_LEN );
status = rsFileOpendir( rsComm, &fileOpendirInp );
if ( status < 0 ) {
rodsLog( LOG_ERROR,
"l3Opendir: rsFileOpendir for %s error, status = %d",
dataObjInfo->filePath, status );
}
}
return status;
}
| 18,607
| 6,478
|
#include <iostream>
using namespace std;
int main()
{
long int decimalNumber, remainder, quotient;
int i = 1, j, temp;
char hexadecimalNumber[100];
cout << "Masukkan Bilangan Decimal : "; cin >> decimalNumber;
quotient = decimalNumber;
while (quotient != 0)
{
temp = quotient % 16;
if (temp < 10) {
temp = temp + 48;
}
else {
temp = temp + 55;
}
hexadecimalNumber[i++] = temp;
quotient = quotient / 16;
}
cout << "Bilangan Hexadecimalnya adalah : ";
for (j = i; j > 0; j--)
{
cout << hexadecimalNumber[j];
}
return 0;
}
//@wardiman_xixv
| 609
| 252
|
/*
** EPITECH PROJECT, 2019
** NewDimension
** File description:
** Logger
*/
#ifndef LOGGER_HPP_
# define LOGGER_HPP_
# include <ostream>
# include <iostream>
# include <array>
# include <ctime>
# include <functional>
# include "config/config.hpp"
namespace nd {
namespace engine {
class Logger {
public:
Logger() = delete;
static bool set_stream(const std::string_view filepath);
enum level {
DEBUG,
INFO,
NOTICE,
WARNING,
ERROR,
ALERT,
CRITIC,
EMERGENCY,
UNKNOWN,
};
inline static level get_current_level() noexcept
{ return s_current_level; }
inline static void set_current_level(level new_level) noexcept
{ s_current_level = new_level; }
struct data {
level msg_level;
const char *file;
int line;
const char *func;
std::time_t timestamp;
};
static std::ostream &dump_info(const data &data_info);
inline static void set_format(const std::string &new_format) noexcept
{ s_display_format = new_format; }
protected:
private:
static std::ostream *s_stream;
static level s_current_level;
static std::string s_display_format;
static constexpr std::ostream *DEFAULT_STREAM = &std::cerr;
static constexpr level DEFAULT_LEVEL = DEBUG;
static constexpr auto DEFAULT_DISPLAY_FORMAT =
"[${info:level}] id:${info:uid} at:${style:underline}${info:timestamp}${style:reset} "
"in file ${info:file} at line ${style:bold:underline}${info:line}${style:reset} "
"in function ${style:fg-blue:bold}${info:func}${style:reset}:\r\n";
using uid = std::size_t;
static uid s_current_msg_uid;
static constexpr std::array S_LEVEL_AS_STRING {
std::make_pair(DEBUG, "${style:fg-lightcyan}DEBUG${style:reset}"),
std::make_pair(INFO, "${style:fg-lightgreen}INFO${style:reset}"),
std::make_pair(NOTICE, "${style:fg-green}NOTICE${style:reset}"),
std::make_pair(WARNING, "${style:fg-lightyellow}WARNING${style:reset}"),
std::make_pair(ERROR, "${style:fg-red:bold}ERROR${style:reset}"),
std::make_pair(ALERT, "${style:fg-lightred:underline:bold}ALERT${style:reset}"),
std::make_pair(CRITIC, "${style:fg-black:blink:bg-yellow}CRITIC${style:reset}"),
std::make_pair(EMERGENCY, "${style:fg-black:blink:bold:underline:bg-lightred}EMERGENCY${style:reset}"),
};
static constexpr std::optional<const char *> level_as_string(level search);
using PairStyle = std::pair<const char *, const char *>;
static constexpr std::array<const PairStyle, 47> S_SUPPORTED_STYLE {
// Colors
std::make_pair("fg-red", "31"), std::make_pair("bg-red", "41"),
std::make_pair("fg-lightred", "91"), std::make_pair("bg-lightred", "101"),
std::make_pair("fg-green", "32"), std::make_pair("bg-green", "42"),
std::make_pair("fg-lightgreen", "92"), std::make_pair("bg-lightgreen", "102"),
std::make_pair("fg-blue", "34"), std::make_pair("bg-blue", "44"),
std::make_pair("fg-lightblue", "94"), std::make_pair("bg-lightblue", "104"),
std::make_pair("fg-yellow", "33"), std::make_pair("bg-yellow", "43"),
std::make_pair("fg-lightyellow", "93"), std::make_pair("bg-lightyellow", "103"),
std::make_pair("fg-magenta", "35"), std::make_pair("bg-magenta", "45"),
std::make_pair("fg-lightmagenta", "95"), std::make_pair("bg-lightmagenta", "105"),
std::make_pair("fg-cyan", "36"), std::make_pair("bg-cyan", "46"),
std::make_pair("fg-lightcyan", "96"), std::make_pair("bg-lightcyan", "106"),
std::make_pair("fg-white", "97"), std::make_pair("bg-white", "107"),
std::make_pair("fg-lightgrey", "37"), std::make_pair("bg-lightgrey", "47"),
std::make_pair("fg-darkgrey", "90"), std::make_pair("bg-drakgrey", "100"),
std::make_pair("fg-black", "30"), std::make_pair("bg-black", "40"),
std::make_pair("fg-default", "39"), std::make_pair("bg-default", "49"),
// ... complete me
// Styles / Effects
std::make_pair("bold", "1"), std::make_pair("bold-off", "21"),
std::make_pair("dim", "2"), std::make_pair("dim-off", "22"),
std::make_pair("underline", "4"), std::make_pair("underline-off", "24"),
std::make_pair("blink", "5"), std::make_pair("blink-off", "25"),
std::make_pair("inverse", "7"), std::make_pair("inverse-off", "27"),
std::make_pair("hidden", "8"), std::make_pair("hidden-off", "28"),
// ... complete me
std::make_pair("reset", "0"),
};
static constexpr std::optional<PairStyle> get_style_value(const char *search);
};
} // namespace engine
} // namespace new dimension
# define LOG(level, exp) do { \
if (nd::engine::Logger::get_current_level() <= level) \
nd::engine::Logger::dump_info({ level, __FILE__, __LINE__, __func__, std::time(nullptr) }) \
<< exp << std::endl; \
} while (false)
# if PROJECT_BUILD_TYPE == Debug
# define DEBUG(exp) LOG(nd::engine::Logger::DEBUG, exp)
# else
# define DEBUG(exp)
# endif
# define INFO(exp) LOG(nd::engine::Logger::INFO, exp)
# define NOTICE(exp) LOG(nd::engine::Logger::NOTICE, exp)
# define WARNING(exp) LOG(nd::engine::Logger::WARNING, exp)
# define ERROR(exp) LOG(nd::engine::Logger::ERROR, exp)
# define ALERT(exp) LOG(nd::engine::Logger::ALERT, exp)
# define CRITIC(exp) LOG(nd::engine::Logger::CRITIC, exp)
# define EMERGENCY(exp) LOG(nd::engine::Logger::EMERGENCY, exp)
#endif /* !LOGGER_HPP_ */
| 5,697
| 2,031
|
/**
BSD 2-Clause License
Copyright (c) 2019, SBcodework
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 <iostream>
#include "common.h"
#include "Parameter.h"
#include "Gridtype.h"
#include "Cordtype.h"
#include <string>
#include <typeinfo>
#include <algorithm>
#include <vector>
#include <bitset>
#include <random>
#include <time.h>
#include <cmath>
int extractDigitInt( int digits, std::string input )
{
int result = 0;
int length = input.length();
if ( length == 0 || digits < 0 )
{
return -1;
}
/// Find the furthest index of the string representing the smallest digit (under 10) as string length permits.
int digitsFirstGuess = digits; //(length > digits) ? length : digits;
int digitsSecondGuess = 0; /// Below: find the first digit.
for ( int i = 0; (i < digitsFirstGuess) && (isdigit(input[i])) && (i < length); i++ )
{
digitsSecondGuess++;
}
if ( digitsSecondGuess == 0 )
{
return -1;
}
//float digit = digitsSecondGuess;
for ( int i = (digitsSecondGuess - 1), magnitude = 0, inputDigit = 0, power = 0; i >= 0; i--, power++ ) /// Start backwards from the furthest index
{
inputDigit = (int)(input[i] - '0');
magnitude = (int)(std::pow(10.0, (float)power));
result += (inputDigit * magnitude);
}
return result;
}
void askXYMinesLoop(Parameter& out_param)
{
int x, y, mines, area; // Output containers
std::string strx;
std::string stry;
std::string strMines;
for (;;)
{
std::cout << "Grid Length? ";
std::cin >> strx;
std::cout << "Grid Height? ";
std::cin >> stry;
std::cout << "Number of mines? ";
std::cin >> strMines;
x = extractDigitInt(2, strx);
y = extractDigitInt(2, stry);
mines = extractDigitInt(4, strMines); //4 digits
if ( x < 1 || y < 1 || mines < 1 || x > 99 || y > 99 || mines > 9801 ||
( x < 4 && y < 4 ) || ( mines > ((x*y)-9) ) )
{
std::cout << "Invalid input! Try again.\n";
continue;
}
out_param.length = x;
out_param.height = y;
out_param.mines = mines;
out_param.init_dimensions();
return;
break;
}
}
void dispEmpty(Parameter& in_param)
{
int length = in_param.length;
int height = in_param.height;
std::cout << " "; // 5 spaces
for (int i=0; i<length; i++)
{
std::cout << "{" << (i/10) << (i%10) << "}";
}
std::cout << "\n";
for (int i=0; i<height; i++)
{
std::cout << "{" << (i/10) << (i%10) << "} ";
for (int n=0; n<length; n++)
{
std::cout << "[ ]";
}
std::cout << "\n";
}
return;
}
int askStartXYLoop(Parameter& out_param)
{
int error = 0, length = 0;
std::string line; // "cin.get()" Is not used, as it skips the first character of input.
for (int skip = 0; ;skip = 0)
{
line = ""; // Reset the line each loop
std::cout << "Enter X cord, followed by a comma, and Y cord. Like '13,8'. \n";
std::cin >> line;
length = line.length();
//std::getline(std::cin, line); Old method, above worked better
if ( (length < 3) || ((line[1] != ',') && (line[2] != ',')) || !isdigit(line[0]) ||
(!isdigit(line[1]) && (line[1] != ',')) || (!isdigit(line[2]) && (line[2] != ',')) ||
((length > 3) && (line[2] == ',') && !isdigit(line[3]) ) )
{
std::cout << "Invalid! Try again. Line: " << line << "\n";
continue;
}
error = h_extractCoords(line, out_param.xStart, out_param.yStart, nullptr, ',');
if ((out_param.xStart >= out_param.length) || (out_param.yStart >= out_param.height))
{
std::cout << "Coordinates out of range! Try again. Line: " << line << "\n";
continue;
}
switch (error)
{
case 0:
break;
case 1:
std::cout << "Error in askStartXYLoop! ";
std::cout << "x, y: " << out_param.xStart << " " << out_param.yStart << "\n";
return 1;
case 2:
std::cout << "Invalid! Try again. Line: " << line << "\n";
skip = 1;
}
if (skip)
{
continue;
}
out_param.init_start();
return 0;
}
}
int h_extractCoords(std::string in_line, int& out_x, int& out_y, char* out_sep, char sep)
{
int length = in_line.length();
if ( (length < 3) || (length > 5) )
{
return 2; // Too long or too short; for legacy reasons 2 is the error code for user errors
}
int x = extractDigitInt( 2, in_line );
int slicedStart = (x < 10) ? 2 : 3;
if ( (x == -1) || (slicedStart > length) )
{
return 2; // Invalid X or string is too short for a separator to fit
}
char separator = in_line[slicedStart - 1];
if ( ( (separator != sep) && sep != '\0' ) || ( (sep == '\0') && isdigit(separator) ) )
{
return 2; // An invalid separator is found when it is defined in the arguments, or if the separator is a digit when searching for one.
}
std::string slicedString = in_line.substr( slicedStart, length );
int y = extractDigitInt( 2, slicedString );
if ( y == -1 )
{
return 2; // Invalid y
}
if ( out_sep != nullptr )
{
*out_sep = separator;
}
out_x = x;
out_y = y;
return 0;
}
void gengrid(Gridtype& out_grid)
{ // Parameters are declared below
srand(time(0)); // Init randomizer
Parameter* params = out_grid.pParams;
int w = params->length;
int h = params->height;
int area = h*w;
int xstart = params->xStart;
int ystart = params->yStart;
int istart = params->iStart; //Unneeded at the moment
int mines = params->mines;
char* rawGrid = new char[area];
std::fill_n(rawGrid, area, '0'); // Fill with zeros
int startSquare[9] {0}; // Indexes of the start square
getSquare(xstart, ystart, w, h, startSquare);
int clearCounter = 0;
for (int i = 0, state = 0 ; i<9 ; i++) // Go through startSquare
{
state = startSquare[i]; /*
if (state > -1 && state < area)
{
continue;
}*/
if (state != -1 && state < area) // -1 means an invalid spot
{
rawGrid[state] = 'c';
clearCounter++; // Count the number of valid mine-less spots
}
}
int* mineList = new int[mines];
std::fill_n(mineList, mines, 0);
int mineLCounter = 0;
int mineCandidates[mines + 9] {0};
uniqueRand(mines+9, 0, area, mineCandidates); // mineCandidates now has a list of unique mines.
for (int i = 0; ((i < mines+9) && (mineLCounter < mines)) ; i++)
{
if ((rawGrid[mineCandidates[i]] != 'c') && mineLCounter < (mines))
{
mineList[mineLCounter] = mineCandidates[i];
rawGrid[mineList[mineLCounter]] = 'X';
mineLCounter++; /// This needs to be here, not in the above for() declaration.
}
}
for (int i = 0, state = 0 ; i<9 ; i++) // Go through startSquare, set back to 0's, we don't need 'c's anymore
{
state = startSquare[i];
if (state != -1 && state < area) // -1 means an invalid spot
{
rawGrid[state] = '0';
}
}
for (int i = 0, square[9] {0}, currentMine; i < mines; i++) // Count numbers and put them in
{
currentMine = mineList[i];
getSquare(currentMine % w, currentMine / w, w, h, square); ///Watch in case of bug
for (int n = 0, state = 0; n < 9; n++)
{
state = square[n];
if ( state != -1 && rawGrid[state] != 'X' && rawGrid[state] >= '0' && rawGrid[state] < '8' )
{
rawGrid[state]++; // '0' goes to '1' and so on
}
}
}
out_grid.set_grid(rawGrid); // Return
out_grid.set_minelist(mineList);
out_grid.action( istart, 's' );
return;
}
void getSquare(int centerX, int centerY, int w, int h, int out_square[9])
{
int xpart = 0;
int ypart = 0;
int startX = centerX - 1;
int startY = centerY - 1;
for (int iy = 0, counter = 0; iy < 3 ; iy++)
{
for (int ix = 0; ix < 3; ix++, counter++)
{
xpart = startX + ix;
ypart = startY + iy;
out_square[counter] = toIndexCheck(xpart, ypart, w, h);
}
}
return;
}
int toIndexCheck(int x, int y, int w, int h)
{
if (outOfBounds(x, y, w, h))
{
return -1;
}
return ((y*w) + x );
}
int outOfBounds(int x, int y, int w, int h)
{
if (x >= 0 && y >= 0 && x < w && y <h)
{
return 0;
}
return 1;
}
// Numlimit is exclusive. Output must be of size "size".
int uniqueRand(int size, int start, int numlimit, int* output)
{
/// init srand
std::vector<bool> bvector(numlimit, 0);
int currentStart = 0;
int currentEnd = 0; // Inclusive
int currentMiddle = 0; // Exclusive; the inclusive start of the second sequence.
int currentSize = 0;
for (int counter = 0; counter < size; counter++)
{
currentStart = start;
currentEnd = numlimit;
currentMiddle = (numlimit / 2); // Seperator at right. -1 used to be here
currentSize = numlimit - start; /// changed from numlimit
for (int state = 0, choice = 0 ; ; )
{
if (currentStart == (currentEnd-1))
{
if (bvector[currentStart] == 1)
{
std::cout << "Duplicate error!\n";
}
output[counter] = currentStart; // We have found our number
bvector[currentStart] = true;
break;
}
state = allCheck(currentStart, currentMiddle, currentEnd, bvector);
switch (state)
{
case 0: // Choose a random element. 0 = left, 1 = right.
choice = (rand() % 2);
break;
case 1: // Choose left
choice = 0;
break;
case 2: // Choose right
choice = 1;
break;
case 3:
std::cout << "Array full! Size: " << currentSize << " Start: " << currentStart << " Middle: " << currentMiddle << " End: " << currentEnd << "\n";
for ( int n=0; n<size; n++)
{
std::cout << output[n];
}
std::cout << "\n";
return 1;
}
switch (choice)
{
case 0:
currentEnd = currentMiddle;
currentSize = currentEnd - currentStart; // removed +1
currentMiddle = currentStart + (currentSize / 2); // removed -1, added currentstart
break;
case 1:
currentStart = currentMiddle; //removed +1
currentSize = currentEnd - currentStart; //removed +1
currentMiddle = currentStart + (currentSize / 2); //removed -1
break;
}
}
}
return 0;
}
// OLD documentation:
// Include start and end. Middle refers to the seperatation RIGHT of the index. It is added one locally, same with end.
// Return 0 if neither left or right is all 1's. 1 if only the left one has a zero in it, 2 if it's right, and 3 for both.
// New documentation: Include start, in_middle includes the start of the second sequence, in_end is exclusive.
int allCheck(int start, int middle, int end, std::vector<bool>& in_vector)
{
int allLeft = 1; // 1 meaning all ones are in the bit array.
int allRight = 1;
///int middle = in_middle + 1; // LEFT of index; testing
//int end = in_end + 1; // Exclusive
//int middle = (end - start) / 2;
for (int currentStart = start, currentEnd = middle, *flag = &allLeft, t = 0;
t < 2;
t++, currentStart = middle, currentEnd = end, flag = &allRight) // Two times, go through left and right
{
for (int i = currentStart , size = currentEnd - currentStart; i < currentEnd; i++ ) // Commented out portion was unused
{
if (in_vector[i] == false) // Remember to init the vector with zeroes, else seg fault here
{
*flag = 0; // There's a zero in the bit array.
break;
}
}
}
switch (allLeft + allRight)
{
case 0: // Neither are ones
return 0;
case 1:
if (allLeft) // Right only has no ones
{
return 2;
}
return 1; // Left has no ones
case 2:
std::cout << "Sub-array full! Dump: \n";
for ( int n=0; n<(end-start); n++)
{
std::cout << in_vector[n];
}
std::cout << "\n";
return 3; // Both have ones
}
std::cout << "Error in allCheck(...)!\n"; // Shouldn't reach here, added to avoid compiler warning
return 0;
}
void askSelectionXYTLoop( Cordtype& out_cord )
{
// Gather input (h_extract_cords)
// Output trimmed input to out_cord
// Find the seperator, then run h_extractcords
std::string line = "\0" ;
int x = 0, y = 0 ;
char sep = '1';
for (int error = 1, loopError = 1; loopError ;)
{
std::cout << "\nSelect a point and an action. 's' to uncover, 'm' to middle click, and 'f' to flag. Like '13f7'. \n";
std::cin >> line;
error = h_extractCoords( line, x, y, &sep ) ;
if ( error || (x < 0) || (y < 0) || (x > (out_cord.pParams->length)) || (y > (out_cord.pParams->height) ) )
{
std::cout << "Invalid input! Try again.\n";
continue;
}
switch (sep)
{
case 's':
case 'm':
case 'f':
loopError = 0;
break;
default:
std::cout << "AskXYT Error, sep is invalid! Sep: " << sep << ". Try again.\n";
}
}
out_cord.setter(x, y, sep) ;
return ;
}
| 16,032
| 5,403
|
//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
//
// 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 "llvm/MC/MCContext.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/BinaryFormat/Wasm.h"
#include "llvm/BinaryFormat/XCOFF.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeView.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFragment.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCLabel.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionGOFF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCSectionWasm.h"
#include "llvm/MC/MCSectionXCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCSymbolCOFF.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/MC/MCSymbolGOFF.h"
#include "llvm/MC/MCSymbolMachO.h"
#include "llvm/MC/MCSymbolWasm.h"
#include "llvm/MC/MCSymbolXCOFF.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdlib>
#include <tuple>
#include <utility>
using namespace llvm;
static cl::opt<char*>
AsSecureLogFileName("as-secure-log-file-name",
cl::desc("As secure log file name (initialized from "
"AS_SECURE_LOG_FILE env variable)"),
cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
std::vector<const MDNode *> &) {
SMD.print(nullptr, errs());
}
MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
bool DoAutoReset, StringRef Swift5ReflSegmentName)
: Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator), UsedNames(Allocator),
InlineAsmUsedLabelNames(Allocator),
CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
SecureLogFile = AsSecureLogFileName;
if (SrcMgr && SrcMgr->getNumBuffers())
MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
->getBufferIdentifier());
switch (TheTriple.getObjectFormat()) {
case Triple::MachO:
Env = IsMachO;
break;
case Triple::COFF:
if (!TheTriple.isOSWindows())
report_fatal_error(
"Cannot initialize MC for non-Windows COFF object files.");
Env = IsCOFF;
break;
case Triple::ELF:
Env = IsELF;
break;
case Triple::Wasm:
Env = IsWasm;
break;
case Triple::XCOFF:
Env = IsXCOFF;
break;
case Triple::GOFF:
Env = IsGOFF;
break;
case Triple::UnknownObjectFormat:
report_fatal_error("Cannot initialize MC for unknown object file format.");
break;
}
}
MCContext::~MCContext() {
if (AutoReset)
reset();
// NOTE: The symbols are all allocated out of a bump pointer allocator,
// we don't need to free them here.
}
void MCContext::initInlineSourceManager() {
if (!InlineSrcMgr)
InlineSrcMgr.reset(new SourceMgr());
}
//===----------------------------------------------------------------------===//
// Module Lifetime Management
//===----------------------------------------------------------------------===//
void MCContext::reset() {
SrcMgr = nullptr;
InlineSrcMgr.reset();
LocInfos.clear();
DiagHandler = defaultDiagHandler;
// Call the destructors so the fragments are freed
COFFAllocator.DestroyAll();
ELFAllocator.DestroyAll();
GOFFAllocator.DestroyAll();
MachOAllocator.DestroyAll();
WasmAllocator.DestroyAll();
XCOFFAllocator.DestroyAll();
MCInstAllocator.DestroyAll();
MCSubtargetAllocator.DestroyAll();
InlineAsmUsedLabelNames.clear();
UsedNames.clear();
Symbols.clear();
Allocator.Reset();
Instances.clear();
CompilationDir.clear();
MainFileName.clear();
MCDwarfLineTablesCUMap.clear();
SectionsForRanges.clear();
MCGenDwarfLabelEntries.clear();
DwarfDebugFlags = StringRef();
DwarfCompileUnitID = 0;
CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
CVContext.reset();
MachOUniquingMap.clear();
ELFUniquingMap.clear();
GOFFUniquingMap.clear();
COFFUniquingMap.clear();
WasmUniquingMap.clear();
XCOFFUniquingMap.clear();
ELFEntrySizeMap.clear();
ELFSeenGenericMergeableSections.clear();
NextID.clear();
AllowTemporaryLabels = true;
DwarfLocSeen = false;
GenDwarfForAssembly = false;
GenDwarfFileNumber = 0;
HadError = false;
}
//===----------------------------------------------------------------------===//
// MCInst Management
//===----------------------------------------------------------------------===//
MCInst *MCContext::createMCInst() {
return new (MCInstAllocator.Allocate()) MCInst;
}
//===----------------------------------------------------------------------===//
// Symbol Manipulation
//===----------------------------------------------------------------------===//
MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
SmallString<128> NameSV;
StringRef NameRef = Name.toStringRef(NameSV);
assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
MCSymbol *&Sym = Symbols[NameRef];
if (!Sym)
Sym = createSymbol(NameRef, false, false);
return Sym;
}
MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
unsigned Idx) {
return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
"$frame_escape_" + Twine(Idx));
}
MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
"$parent_frame_offset");
}
MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
FuncName);
}
MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
bool IsTemporary) {
static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolELF>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
"MCSymbol classes must be trivially destructible");
switch (getObjectFileType()) {
case MCContext::IsCOFF:
return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
case MCContext::IsELF:
return new (Name, *this) MCSymbolELF(Name, IsTemporary);
case MCContext::IsGOFF:
return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
case MCContext::IsMachO:
return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
case MCContext::IsWasm:
return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
case MCContext::IsXCOFF:
return createXCOFFSymbolImpl(Name, IsTemporary);
}
return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
IsTemporary);
}
MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
bool CanBeUnnamed) {
if (CanBeUnnamed && !UseNamesOnTempLabels)
return createSymbolImpl(nullptr, true);
// Determine whether this is a user written assembler temporary or normal
// label, if used.
bool IsTemporary = CanBeUnnamed;
if (AllowTemporaryLabels && !IsTemporary)
IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
SmallString<128> NewName = Name;
bool AddSuffix = AlwaysAddSuffix;
unsigned &NextUniqueID = NextID[Name];
while (true) {
if (AddSuffix) {
NewName.resize(Name.size());
raw_svector_ostream(NewName) << NextUniqueID++;
}
auto NameEntry = UsedNames.insert(std::make_pair(NewName.str(), true));
if (NameEntry.second || !NameEntry.first->second) {
// Ok, we found a name.
// Mark it as used for a non-section symbol.
NameEntry.first->second = true;
// Have the MCSymbol object itself refer to the copy of the string that is
// embedded in the UsedNames entry.
return createSymbolImpl(&*NameEntry.first, IsTemporary);
}
assert(IsTemporary && "Cannot rename non-temporary symbols");
AddSuffix = true;
}
llvm_unreachable("Infinite loop");
}
MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
SmallString<128> NameSV;
raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
return createSymbol(NameSV, AlwaysAddSuffix, true);
}
MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
SmallString<128> NameSV;
raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
return createSymbol(NameSV, true, false);
}
MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
SmallString<128> NameSV;
raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
return createSymbol(NameSV, true, false);
}
MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
MCSymbol *MCContext::createNamedTempSymbol() {
return createNamedTempSymbol("tmp");
}
unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->incInstance();
}
unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->getInstance();
}
MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
unsigned Instance) {
MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
if (!Sym)
Sym = createNamedTempSymbol();
return Sym;
}
MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
unsigned Instance = NextInstance(LocalLabelVal);
return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
}
MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
bool Before) {
unsigned Instance = GetInstance(LocalLabelVal);
if (!Before)
++Instance;
return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
}
MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
SmallString<128> NameSV;
StringRef NameRef = Name.toStringRef(NameSV);
return Symbols.lookup(NameRef);
}
void MCContext::setSymbolValue(MCStreamer &Streamer,
StringRef Sym,
uint64_t Val) {
auto Symbol = getOrCreateSymbol(Sym);
Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
}
void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
InlineAsmUsedLabelNames[Sym->getName()] = Sym;
}
MCSymbolXCOFF *
MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
bool IsTemporary) {
if (!Name)
return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
StringRef OriginalName = Name->first();
if (OriginalName.startswith("._Renamed..") ||
OriginalName.startswith("_Renamed.."))
reportError(SMLoc(), "invalid symbol name from source");
if (MAI->isValidUnquotedName(OriginalName))
return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
// Now we have a name that contains invalid character(s) for XCOFF symbol.
// Let's replace with something valid, but save the original name so that
// we could still use the original name in the symbol table.
SmallString<128> InvalidName(OriginalName);
// If it's an entry point symbol, we will keep the '.'
// in front for the convention purpose. Otherwise, add "_Renamed.."
// as prefix to signal this is an renamed symbol.
const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
SmallString<128> ValidName =
StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
// Append the hex values of '_' and invalid characters with "_Renamed..";
// at the same time replace invalid characters with '_'.
for (size_t I = 0; I < InvalidName.size(); ++I) {
if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
InvalidName[I] = '_';
}
}
// Skip entry point symbol's '.' as we already have a '.' in front of
// "_Renamed".
if (IsEntryPoint)
ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
else
ValidName.append(InvalidName);
auto NameEntry = UsedNames.insert(std::make_pair(ValidName.str(), true));
assert((NameEntry.second || !NameEntry.first->second) &&
"This name is used somewhere else.");
// Mark the name as used for a non-section symbol.
NameEntry.first->second = true;
// Have the MCSymbol object itself refer to the copy of the string
// that is embedded in the UsedNames entry.
MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
return XSym;
}
//===----------------------------------------------------------------------===//
// Section Management
//===----------------------------------------------------------------------===//
MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
unsigned TypeAndAttributes,
unsigned Reserved2, SectionKind Kind,
const char *BeginSymName) {
// We unique sections by their segment/section pair. The returned section
// may not have the same flags as the requested section, if so this should be
// diagnosed by the client as an error.
// Form the name to look up.
assert(Section.size() <= 16 && "section name is too long");
assert(!memchr(Section.data(), '\0', Section.size()) &&
"section name cannot contain NUL");
// Do the lookup, if we have a hit, return it.
auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
if (!R.second)
return R.first->second;
MCSymbol *Begin = nullptr;
if (BeginSymName)
Begin = createTempSymbol(BeginSymName, false);
// Otherwise, return a new section.
StringRef Name = R.first->first();
R.first->second = new (MachOAllocator.Allocate())
MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
TypeAndAttributes, Reserved2, Kind, Begin);
return R.first->second;
}
void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
StringRef GroupName;
if (const MCSymbol *Group = Section->getGroup())
GroupName = Group->getName();
// This function is only used by .debug*, which should not have the
// SHF_LINK_ORDER flag.
unsigned UniqueID = Section->getUniqueID();
ELFUniquingMap.erase(
ELFSectionKey{Section->getName(), GroupName, "", UniqueID});
auto I = ELFUniquingMap
.insert(std::make_pair(
ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
.first;
StringRef CachedName = I->first.SectionName;
const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
}
MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
unsigned Flags, SectionKind K,
unsigned EntrySize,
const MCSymbolELF *Group,
bool Comdat, unsigned UniqueID,
const MCSymbolELF *LinkedToSym) {
MCSymbolELF *R;
MCSymbol *&Sym = Symbols[Section];
// A section symbol can not redefine regular symbols. There may be multiple
// sections with the same name, in which case the first such section wins.
if (Sym && Sym->isDefined() &&
(!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
reportError(SMLoc(), "invalid symbol redefinition");
if (Sym && Sym->isUndefined()) {
R = cast<MCSymbolELF>(Sym);
} else {
auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
if (!Sym)
Sym = R;
}
R->setBinding(ELF::STB_LOCAL);
R->setType(ELF::STT_SECTION);
auto *Ret = new (ELFAllocator.Allocate())
MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
R, LinkedToSym);
auto *F = new MCDataFragment();
Ret->getFragmentList().insert(Ret->begin(), F);
F->setParent(Ret);
R->setFragment(F);
return Ret;
}
MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
unsigned Flags, unsigned EntrySize,
const MCSymbolELF *Group,
const MCSectionELF *RelInfoSection) {
StringMap<bool>::iterator I;
bool Inserted;
std::tie(I, Inserted) =
RelSecNames.insert(std::make_pair(Name.str(), true));
return createELFSectionImpl(
I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
}
MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
const Twine &Suffix, unsigned Type,
unsigned Flags,
unsigned EntrySize) {
return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
/*IsComdat=*/true);
}
MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
const Twine &Group, bool IsComdat,
unsigned UniqueID,
const MCSymbolELF *LinkedToSym) {
MCSymbolELF *GroupSym = nullptr;
if (!Group.isTriviallyEmpty() && !Group.str().empty())
GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
UniqueID, LinkedToSym);
}
MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
const MCSymbolELF *GroupSym,
bool IsComdat, unsigned UniqueID,
const MCSymbolELF *LinkedToSym) {
StringRef Group = "";
if (GroupSym)
Group = GroupSym->getName();
assert(!(LinkedToSym && LinkedToSym->getName().empty()));
// Do the lookup, if we have a hit, return it.
auto IterBool = ELFUniquingMap.insert(std::make_pair(
ELFSectionKey{Section.str(), Group,
LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
nullptr));
auto &Entry = *IterBool.first;
if (!IterBool.second)
return Entry.second;
StringRef CachedName = Entry.first.SectionName;
SectionKind Kind;
if (Flags & ELF::SHF_ARM_PURECODE)
Kind = SectionKind::getExecuteOnly();
else if (Flags & ELF::SHF_EXECINSTR)
Kind = SectionKind::getText();
else
Kind = SectionKind::getReadOnly();
MCSectionELF *Result =
createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
IsComdat, UniqueID, LinkedToSym);
Entry.second = Result;
recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
Result->getUniqueID(), Result->getEntrySize());
return Result;
}
MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
bool IsComdat) {
return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
SectionKind::getReadOnly(), 4, Group, IsComdat,
MCSection::NonUniqueID, nullptr);
}
void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
unsigned Flags, unsigned UniqueID,
unsigned EntrySize) {
bool IsMergeable = Flags & ELF::SHF_MERGE;
if (UniqueID == GenericSectionID)
ELFSeenGenericMergeableSections.insert(SectionName);
// For mergeable sections or non-mergeable sections with a generic mergeable
// section name we enter their Unique ID into the ELFEntrySizeMap so that
// compatible globals can be assigned to the same section.
if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
ELFEntrySizeMap.insert(std::make_pair(
ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
}
}
bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
return SectionName.startswith(".rodata.str") ||
SectionName.startswith(".rodata.cst");
}
bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
ELFSeenGenericMergeableSections.count(SectionName);
}
Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
unsigned Flags,
unsigned EntrySize) {
auto I = ELFEntrySizeMap.find(
MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
}
MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind) {
// Do the lookup. If we don't have a hit, return a new section.
auto &GOFFSection = GOFFUniquingMap[Section.str()];
if (!GOFFSection)
GOFFSection = new (GOFFAllocator.Allocate()) MCSectionGOFF(Section, Kind);
return GOFFSection;
}
MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
unsigned Characteristics,
SectionKind Kind,
StringRef COMDATSymName, int Selection,
unsigned UniqueID,
const char *BeginSymName) {
MCSymbol *COMDATSymbol = nullptr;
if (!COMDATSymName.empty()) {
COMDATSymbol = getOrCreateSymbol(COMDATSymName);
COMDATSymName = COMDATSymbol->getName();
}
// Do the lookup, if we have a hit, return it.
COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
auto Iter = IterBool.first;
if (!IterBool.second)
return Iter->second;
MCSymbol *Begin = nullptr;
if (BeginSymName)
Begin = createTempSymbol(BeginSymName, false);
StringRef CachedName = Iter->first.SectionName;
MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
Iter->second = Result;
return Result;
}
MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
unsigned Characteristics,
SectionKind Kind,
const char *BeginSymName) {
return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
BeginSymName);
}
MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
const MCSymbol *KeySym,
unsigned UniqueID) {
// Return the normal section if we don't have to be associative or unique.
if (!KeySym && UniqueID == GenericSectionID)
return Sec;
// If we have a key symbol, make an associative section with the same name and
// kind as the normal section.
unsigned Characteristics = Sec->getCharacteristics();
if (KeySym) {
Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
KeySym->getName(),
COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
}
return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
UniqueID);
}
MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
unsigned Flags, const Twine &Group,
unsigned UniqueID,
const char *BeginSymName) {
MCSymbolWasm *GroupSym = nullptr;
if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
GroupSym->setComdat(true);
}
return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
}
MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
unsigned Flags,
const MCSymbolWasm *GroupSym,
unsigned UniqueID,
const char *BeginSymName) {
StringRef Group = "";
if (GroupSym)
Group = GroupSym->getName();
// Do the lookup, if we have a hit, return it.
auto IterBool = WasmUniquingMap.insert(
std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
auto &Entry = *IterBool.first;
if (!IterBool.second)
return Entry.second;
StringRef CachedName = Entry.first.SectionName;
MCSymbol *Begin = createSymbol(CachedName, true, false);
Symbols[Begin->getName()] = Begin;
cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
MCSectionWasm *Result = new (WasmAllocator.Allocate())
MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
Entry.second = Result;
auto *F = new MCDataFragment();
Result->getFragmentList().insert(Result->begin(), F);
F->setParent(Result);
Begin->setFragment(F);
return Result;
}
bool MCContext::hasXCOFFSection(StringRef Section,
XCOFF::CsectProperties CsectProp) const {
return XCOFFUniquingMap.count(
XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
}
MCSectionXCOFF *MCContext::getXCOFFSection(
StringRef Section, SectionKind Kind,
Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
const char *BeginSymName,
Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue();
assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!");
// Do the lookup. If we have a hit, return it.
auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
IsDwarfSec
? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue())
: XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
nullptr));
auto &Entry = *IterBool.first;
if (!IterBool.second) {
MCSectionXCOFF *ExistedEntry = Entry.second;
if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
report_fatal_error("section's multiply symbols policy does not match");
return ExistedEntry;
}
// Otherwise, return a new section.
StringRef CachedName = Entry.first.SectionName;
MCSymbolXCOFF *QualName = nullptr;
// Debug section don't have storage class attribute.
if (IsDwarfSec)
QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
else
QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
CachedName + "[" +
XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
MCSymbol *Begin = nullptr;
if (BeginSymName)
Begin = createTempSymbol(BeginSymName, false);
// QualName->getUnqualifiedName() and CachedName are the same except when
// CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
MCSectionXCOFF *Result = nullptr;
if (IsDwarfSec)
Result = new (XCOFFAllocator.Allocate())
MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
DwarfSectionSubtypeFlags.getValue(), Begin, CachedName,
MultiSymbolsAllowed);
else
Result = new (XCOFFAllocator.Allocate())
MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
CsectProp->Type, Kind, QualName, Begin, CachedName,
MultiSymbolsAllowed);
Entry.second = Result;
auto *F = new MCDataFragment();
Result->getFragmentList().insert(Result->begin(), F);
F->setParent(Result);
if (Begin)
Begin->setFragment(F);
return Result;
}
MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
}
void MCContext::addDebugPrefixMapEntry(const std::string &From,
const std::string &To) {
DebugPrefixMap.insert(std::make_pair(From, To));
}
void MCContext::RemapDebugPaths() {
const auto &DebugPrefixMap = this->DebugPrefixMap;
if (DebugPrefixMap.empty())
return;
const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
SmallString<256> P(Path);
for (const auto &Entry : DebugPrefixMap) {
if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) {
Path = P.str().str();
break;
}
}
};
// Remap compilation directory.
std::string CompDir = std::string(CompilationDir.str());
RemapDebugPath(CompDir);
CompilationDir = CompDir;
// Remap MCDwarfDirs in all compilation units.
for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
RemapDebugPath(Dir);
}
//===----------------------------------------------------------------------===//
// Dwarf Management
//===----------------------------------------------------------------------===//
void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
// MCDwarf needs the root file as well as the compilation directory.
// If we find a '.file 0' directive that will supersede these values.
Optional<MD5::MD5Result> Cksum;
if (getDwarfVersion() >= 5) {
MD5 Hash;
MD5::MD5Result Sum;
Hash.update(Buffer);
Hash.final(Sum);
Cksum = Sum;
}
// Canonicalize the root filename. It cannot be empty, and should not
// repeat the compilation dir.
// The MCContext ctor initializes MainFileName to the name associated with
// the SrcMgr's main file ID, which might be the same as InputFileName (and
// possibly include directory components).
// Or, MainFileName might have been overridden by a -main-file-name option,
// which is supposed to be just a base filename with no directory component.
// So, if the InputFileName and MainFileName are not equal, assume
// MainFileName is a substitute basename and replace the last component.
SmallString<1024> FileNameBuf = InputFileName;
if (FileNameBuf.empty() || FileNameBuf == "-")
FileNameBuf = "<stdin>";
if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
llvm::sys::path::remove_filename(FileNameBuf);
llvm::sys::path::append(FileNameBuf, getMainFileName());
}
StringRef FileName = FileNameBuf;
if (FileName.consume_front(getCompilationDir()))
if (llvm::sys::path::is_separator(FileName.front()))
FileName = FileName.drop_front();
assert(!FileName.empty());
setMCLineTableRootFile(
/*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
}
/// getDwarfFile - takes a file name and number to place in the dwarf file and
/// directory tables. If the file number has already been allocated it is an
/// error and zero is returned and the client reports the error, else the
/// allocated file number is returned. The file numbers may be in any order.
Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
StringRef FileName,
unsigned FileNumber,
Optional<MD5::MD5Result> Checksum,
Optional<StringRef> Source,
unsigned CUID) {
MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
FileNumber);
}
/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
/// currently is assigned and false otherwise.
bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
if (FileNumber == 0)
return getDwarfVersion() >= 5;
if (FileNumber >= LineTable.getMCDwarfFiles().size())
return false;
return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
}
/// Remove empty sections from SectionsForRanges, to avoid generating
/// useless debug info for them.
void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
SectionsForRanges.remove_if(
[&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
}
CodeViewContext &MCContext::getCVContext() {
if (!CVContext.get())
CVContext.reset(new CodeViewContext);
return *CVContext.get();
}
//===----------------------------------------------------------------------===//
// Error Reporting
//===----------------------------------------------------------------------===//
void MCContext::diagnose(const SMDiagnostic &SMD) {
assert(DiagHandler && "MCContext::DiagHandler is not set");
bool UseInlineSrcMgr = false;
const SourceMgr *SMP = nullptr;
if (SrcMgr) {
SMP = SrcMgr;
} else if (InlineSrcMgr) {
SMP = InlineSrcMgr.get();
UseInlineSrcMgr = true;
} else
llvm_unreachable("Either SourceMgr should be available");
DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
}
void MCContext::reportCommon(
SMLoc Loc,
std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
// * MCContext::SrcMgr is null when the MC layer emits machine code for input
// other than assembly file, say, for .c/.cpp/.ll/.bc.
// * MCContext::InlineSrcMgr is null when the inline asm is not used.
// * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
// and MCContext::InlineSrcMgr are null.
SourceMgr SM;
const SourceMgr *SMP = &SM;
bool UseInlineSrcMgr = false;
// FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
// For MC-only execution, only SrcMgr is used;
// For non MC-only execution, InlineSrcMgr is only ctor'd if there is
// inline asm in the IR.
if (Loc.isValid()) {
if (SrcMgr) {
SMP = SrcMgr;
} else if (InlineSrcMgr) {
SMP = InlineSrcMgr.get();
UseInlineSrcMgr = true;
} else
llvm_unreachable("Either SourceMgr should be available");
}
SMDiagnostic D;
GetMessage(D, SMP);
DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
}
void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
HadError = true;
reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
});
}
void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
if (TargetOptions && TargetOptions->MCNoWarn)
return;
if (TargetOptions && TargetOptions->MCFatalWarnings) {
reportError(Loc, Msg);
} else {
reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
});
}
}
| 37,360
| 11,627
|
#include "ChangeFrontBackColorWidget.h"
#include <QDebug>
#define CHANGEFRONTBACKCOLORWIDGET_MARGIN 3
#define CHANGEFRONTBACKCOLORWIDGET_BTN_W 12
#define CHANGEFRONTBACKCOLORWIDGET_BTN_H 12
ChangeFrontBackColorWidget::ChangeFrontBackColorWidget(QWidget *parent) : QWidget(parent)
{
setAutoFillBackground(true);
}
/**
* @brief ChangeFrontBackColorWidget::setup
* 初始化UI
*/
void ChangeFrontBackColorWidget::setup()
{
int x = CHANGEFRONTBACKCOLORWIDGET_MARGIN,
y = CHANGEFRONTBACKCOLORWIDGET_MARGIN,
w = CHANGEFRONTBACKCOLORWIDGET_BTN_W,
h = CHANGEFRONTBACKCOLORWIDGET_BTN_H;
QRect rect = geometry();
qDebug() << "ChangeFrontBackColorWidget this rect:" << rect;
//填充和描边按钮
fillStrokeBtn = new ImageView(this);
fillStrokeBtn->show(x, y, w, h, ":/rc/images/widget/fill-stroke.png");
qDebug() << "ChangeFrontBackColorWidget.left rect:" << QRect(x,y,w,h);
//切换填充和描边按钮
x = rect.width() - CHANGEFRONTBACKCOLORWIDGET_MARGIN - CHANGEFRONTBACKCOLORWIDGET_BTN_W;
changeFillStrokeBtn = new ImageView(this);
changeFillStrokeBtn->show(x, y, w, h, ":/rc/images/widget/change-fill-stroke.png");
qDebug() << "ChangeFrontBackColorWidget.right rect:" << QRect(x,y,w,h);
//切换填充和描边控件
fillStrokeColorWidget = new FillStrokeColorWidget(this);
x = CHANGEFRONTBACKCOLORWIDGET_MARGIN;
y = CHANGEFRONTBACKCOLORWIDGET_MARGIN * 3 + CHANGEFRONTBACKCOLORWIDGET_BTN_H;
w = rect.width() - 2 * CHANGEFRONTBACKCOLORWIDGET_MARGIN;
h = rect.height() - y - 2 * CHANGEFRONTBACKCOLORWIDGET_MARGIN;
fillStrokeColorWidget->setGeometry(x, y, w, h);
qDebug() << "ChangeFrontBackColorWidget.bottom rect:" << QRect(x,y,w,h);
fillStrokeColorWidget->setup();
}
| 1,731
| 713
|
#include <host-config.h>
#if !defined (__MINGW32__) || (defined (__MINGW32__) && __GNUC__ >= 10)
#include <compare>
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <cctype>
#include <libgen.h>
#include <cerrno>
#include <unistd.h>
#if defined (HAVE_LZ4)
#include <lz4.h>
#endif
#include <mono/metadata/assembly.h>
#include <mono/metadata/image.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/mono-debug.h>
#include "java-interop-util.h"
#include "monodroid.h"
#include "util.hh"
#include "embedded-assemblies.hh"
#include "globals.hh"
#include "monodroid-glue.hh"
#include "xamarin-app.hh"
#include "cpp-util.hh"
#include "startup-aware-lock.hh"
using namespace xamarin::android;
using namespace xamarin::android::internal;
// A utility class which allows us to manage memory allocated by `mono_guid_to_string` in an elegant way. We can create
// temporary instances of this class in calls to e.g. `log_debug` which are executed ONLY when debug logging is enabled
class MonoGuidString final
{
public:
explicit MonoGuidString (const uint8_t *id) noexcept
{
guid = mono_guid_to_string (id);
}
~MonoGuidString ()
{
::free (guid);
}
const char* get () const noexcept
{
return guid;
}
private:
char *guid = nullptr;
};
void EmbeddedAssemblies::set_assemblies_prefix (const char *prefix)
{
if (assemblies_prefix_override != nullptr)
delete[] assemblies_prefix_override;
assemblies_prefix_override = prefix != nullptr ? utils.strdup_new (prefix) : nullptr;
}
force_inline void
EmbeddedAssemblies::get_assembly_data (uint8_t *data, uint32_t data_size, [[maybe_unused]] const char *name, uint8_t*& assembly_data, uint32_t& assembly_data_size) noexcept
{
#if defined (ANDROID) && defined (HAVE_LZ4) && defined (RELEASE)
auto header = reinterpret_cast<const CompressedAssemblyHeader*>(data);
if (header->magic == COMPRESSED_DATA_MAGIC) {
if (XA_UNLIKELY (compressed_assemblies.descriptors == nullptr)) {
log_fatal (LOG_ASSEMBLY, "Compressed assembly found but no descriptor defined");
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
if (XA_UNLIKELY (header->descriptor_index >= compressed_assemblies.count)) {
log_fatal (LOG_ASSEMBLY, "Invalid compressed assembly descriptor index %u", header->descriptor_index);
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
CompressedAssemblyDescriptor &cad = compressed_assemblies.descriptors[header->descriptor_index];
assembly_data_size = data_size - sizeof(CompressedAssemblyHeader);
if (!cad.loaded) {
if (XA_UNLIKELY (cad.data == nullptr)) {
log_fatal (LOG_ASSEMBLY, "Invalid compressed assembly descriptor at %u: no data", header->descriptor_index);
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
bool log_timing = utils.should_log (LOG_TIMING) && !(log_timing_categories & LOG_TIMING_BARE);
timing_period decompress_time;
if (XA_UNLIKELY (log_timing)) {
decompress_time.mark_start ();
}
if (header->uncompressed_length != cad.uncompressed_file_size) {
if (header->uncompressed_length > cad.uncompressed_file_size) {
log_fatal (LOG_ASSEMBLY, "Compressed assembly '%s' is larger than when the application was built (expected at most %u, got %u). Assemblies don't grow just like that!", name, cad.uncompressed_file_size, header->uncompressed_length);
exit (FATAL_EXIT_MISSING_ASSEMBLY);
} else {
log_debug (LOG_ASSEMBLY, "Compressed assembly '%s' is smaller than when the application was built. Adjusting accordingly.", name);
}
cad.uncompressed_file_size = header->uncompressed_length;
}
const char *data_start = reinterpret_cast<const char*>(data + sizeof(CompressedAssemblyHeader));
int ret = LZ4_decompress_safe (data_start, reinterpret_cast<char*>(cad.data), static_cast<int>(assembly_data_size), static_cast<int>(cad.uncompressed_file_size));
if (XA_UNLIKELY (log_timing)) {
decompress_time.mark_end ();
TIMING_LOG_INFO (decompress_time, "%s LZ4 decompression time", name);
}
if (ret < 0) {
log_fatal (LOG_ASSEMBLY, "Decompression of assembly %s failed with code %d", name, ret);
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
if (static_cast<uint64_t>(ret) != cad.uncompressed_file_size) {
log_debug (LOG_ASSEMBLY, "Decompression of assembly %s yielded a different size (expected %lu, got %u)", name, cad.uncompressed_file_size, static_cast<uint32_t>(ret));
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
cad.loaded = true;
}
assembly_data = reinterpret_cast<uint8_t*>(cad.data);
assembly_data_size = cad.uncompressed_file_size;
} else
#endif
{
assembly_data = data;
assembly_data_size = data_size;
}
}
force_inline void
EmbeddedAssemblies::get_assembly_data (XamarinAndroidBundledAssembly const& e, uint8_t*& assembly_data, uint32_t& assembly_data_size) noexcept
{
get_assembly_data (e.data, e.data_size, e.name, assembly_data, assembly_data_size);
}
force_inline void
EmbeddedAssemblies::get_assembly_data (AssemblyStoreSingleAssemblyRuntimeData const& e, uint8_t*& assembly_data, uint32_t& assembly_data_size) noexcept
{
get_assembly_data (e.image_data, e.descriptor->data_size, "<assembly_store>", assembly_data, assembly_data_size);
}
#if defined (NET6)
MonoAssembly*
EmbeddedAssemblies::open_from_bundles (MonoAssemblyName* aname, MonoAssemblyLoadContextGCHandle alc_gchandle, [[maybe_unused]] MonoError *error)
{
auto loader = [&] (uint8_t *assembly_data, uint32_t assembly_data_size, const char *name) -> MonoImage* {
return mono_image_open_from_data_alc (
alc_gchandle,
reinterpret_cast<char*>(assembly_data),
assembly_data_size,
0 /* need_copy */,
nullptr /* status */,
name
);
};
return open_from_bundles (aname, loader, false /* ref_only */);
}
#endif // def NET6
MonoAssembly*
EmbeddedAssemblies::open_from_bundles (MonoAssemblyName* aname, bool ref_only)
{
auto loader = [&] (uint8_t *assembly_data, uint32_t assembly_data_size, const char *name) -> MonoImage* {
return mono_image_open_from_data_with_name (
reinterpret_cast<char*>(assembly_data),
assembly_data_size,
0,
nullptr,
ref_only,
name
);
};
return open_from_bundles (aname, loader, ref_only);
}
template<bool LogMapping>
force_inline void
EmbeddedAssemblies::map_runtime_file (XamarinAndroidBundledAssembly& file) noexcept
{
md_mmap_info map_info = md_mmap_apk_file (file.apk_fd, file.data_offset, file.data_size, file.name);
if (monodroidRuntime.is_startup_in_progress ()) {
file.data = static_cast<uint8_t*>(map_info.area);
} else {
uint8_t *expected_null = nullptr;
bool already_mapped = !__atomic_compare_exchange (
/* ptr */ &file.data,
/* expected */ &expected_null,
/* desired */ reinterpret_cast<uint8_t**>(&map_info.area),
/* weak */ false,
/* success_memorder */ __ATOMIC_ACQUIRE,
/* failure_memorder */ __ATOMIC_RELAXED
);
if (already_mapped) {
log_debug (LOG_ASSEMBLY, "Assembly %s already mmapped by another thread, unmapping our copy", file.name);
munmap (map_info.area, file.data_size);
map_info.area = nullptr;
}
}
if constexpr (LogMapping) {
if (XA_UNLIKELY (utils.should_log (LOG_ASSEMBLY) && map_info.area != nullptr)) {
const char *p = (const char*) file.data;
std::array<char, 9> header;
for (size_t j = 0; j < header.size () - 1; ++j)
header[j] = isprint (p [j]) ? p [j] : '.';
header [header.size () - 1] = '\0';
log_info_nocheck (LOG_ASSEMBLY, "file-offset: % 8x start: %08p end: %08p len: % 12i zip-entry: %s name: %s [%s]",
(int) file.data_offset, file.data, file.data + file.data_size, (int) file.data_size, file.name, file.name, header.data ());
}
}
}
force_inline void
EmbeddedAssemblies::map_assembly (XamarinAndroidBundledAssembly& file) noexcept
{
map_runtime_file<true> (file);
}
force_inline void
EmbeddedAssemblies::map_debug_data (XamarinAndroidBundledAssembly& file) noexcept
{
map_runtime_file<false> (file);
}
force_inline MonoAssembly*
EmbeddedAssemblies::load_bundled_assembly (
XamarinAndroidBundledAssembly& assembly,
dynamic_local_string<SENSIBLE_PATH_MAX> const& name,
dynamic_local_string<SENSIBLE_PATH_MAX> const& abi_name,
std::function<MonoImage*(uint8_t*, uint32_t, const char*)> loader,
bool ref_only) noexcept
{
if (assembly.name == nullptr || assembly.name[0] == '\0') {
return nullptr;
}
if (strcmp (assembly.name, name.get ()) != 0) {
if (strcmp (assembly.name, abi_name.get ()) != 0) {
return nullptr;
} else {
log_debug (LOG_ASSEMBLY, "open_from_bundles: found architecture-specific: '%s'", abi_name.get ());
}
}
if (assembly.data == nullptr) {
map_assembly (assembly);
}
uint8_t *assembly_data;
uint32_t assembly_data_size;
get_assembly_data (assembly, assembly_data, assembly_data_size);
MonoImage *image = loader (assembly_data, assembly_data_size, name.get ());
if (image == nullptr) {
return nullptr;
}
if (have_and_want_debug_symbols) {
uint32_t base_name_length = assembly.name_length - 3; // we need the trailing dot
for (XamarinAndroidBundledAssembly& debug_file : *bundled_debug_data) {
if (debug_file.name_length < base_name_length) {
continue;
}
if (strncmp (debug_file.name, assembly.name, base_name_length) != 0) {
continue;
}
if (debug_file.data == nullptr) {
map_debug_data (debug_file);
}
if (debug_file.data != nullptr) {
if (debug_file.data_size > std::numeric_limits<int>::max ()) {
log_warn (LOG_ASSEMBLY, "Debug info file '%s' is too big for Mono to consume", debug_file.name);
} else {
mono_debug_open_image_from_memory (image, reinterpret_cast<const mono_byte*>(debug_file.data), static_cast<int>(debug_file.data_size));
}
}
break;
}
}
MonoImageOpenStatus status;
MonoAssembly *a = mono_assembly_load_from_full (image, name.get (), &status, ref_only);
if (a == nullptr) {
return nullptr;
}
#if !defined (NET6)
// In dotnet the call is a no-op
mono_config_for_assembly (image);
#endif
return a;
}
force_inline MonoAssembly*
EmbeddedAssemblies::individual_assemblies_open_from_bundles (dynamic_local_string<SENSIBLE_PATH_MAX>& name, std::function<MonoImage*(uint8_t*, size_t, const char*)> loader, bool ref_only) noexcept
{
if (!utils.ends_with (name, SharedConstants::DLL_EXTENSION)) {
name.append (SharedConstants::DLL_EXTENSION);
}
log_debug (LOG_ASSEMBLY, "individual_assemblies_open_from_bundles: looking for bundled name: '%s'", name.get ());
dynamic_local_string<SENSIBLE_PATH_MAX> abi_name;
abi_name
.assign_c (BasicAndroidSystem::get_built_for_abi_name ())
.append (zip_path_separator)
.append (name);
MonoAssembly *a = nullptr;
for (size_t i = 0; i < application_config.number_of_assemblies_in_apk; i++) {
a = load_bundled_assembly (bundled_assemblies [i], name, abi_name, loader, ref_only);
if (a != nullptr) {
return a;
}
}
if (extra_bundled_assemblies != nullptr) {
for (XamarinAndroidBundledAssembly& assembly : *extra_bundled_assemblies) {
a = load_bundled_assembly (assembly, name, abi_name, loader, ref_only);
if (a != nullptr) {
return a;
}
}
}
return nullptr;
}
force_inline const AssemblyStoreHashEntry*
EmbeddedAssemblies::find_assembly_store_entry (hash_t hash, const AssemblyStoreHashEntry *entries, size_t entry_count) noexcept
{
#if !defined (__MINGW32__) || (defined (__MINGW32__) && __GNUC__ >= 10)
hash_t entry_hash;
const AssemblyStoreHashEntry *ret;
while (entry_count > 0) {
ret = entries + (entry_count / 2);
if constexpr (std::is_same_v<hash_t, uint64_t>) {
entry_hash = ret->hash64;
} else {
entry_hash = ret->hash32;
}
std::strong_ordering result = hash <=> entry_hash;
if (result < 0) {
entry_count /= 2;
} else if (result > 0) {
entries = ret + 1;
entry_count -= entry_count / 2 + 1;
} else {
return ret;
}
}
#endif // ndef __MINGW32__ || (def __MINGW32__ && __GNUC__ >= 10)
return nullptr;
}
force_inline MonoAssembly*
EmbeddedAssemblies::assembly_store_open_from_bundles (dynamic_local_string<SENSIBLE_PATH_MAX>& name, std::function<MonoImage*(uint8_t*, size_t, const char*)> loader, bool ref_only) noexcept
{
size_t len = name.length ();
bool have_dll_ext = utils.ends_with (name, SharedConstants::DLL_EXTENSION);
if (have_dll_ext) {
len -= sizeof(SharedConstants::DLL_EXTENSION) - 1;
}
hash_t name_hash = xxhash::hash (name.get (), len);
log_debug (LOG_ASSEMBLY, "assembly_store_open_from_bundles: looking for bundled name: '%s' (hash 0x%zx)", name.get (), name_hash);
const AssemblyStoreHashEntry *hash_entry = find_assembly_store_entry (name_hash, assembly_store_hashes, application_config.number_of_assemblies_in_apk);
if (hash_entry == nullptr) {
log_warn (LOG_ASSEMBLY, "Assembly '%s' (hash 0x%zx) not found", name.get (), name_hash);
return nullptr;
}
if (hash_entry->mapping_index >= application_config.number_of_assemblies_in_apk) {
log_fatal (LOG_ASSEMBLY, "Invalid assembly index %u, exceeds the maximum index of %u", hash_entry->mapping_index, application_config.number_of_assemblies_in_apk - 1);
abort ();
}
AssemblyStoreSingleAssemblyRuntimeData &assembly_runtime_info = assembly_store_bundled_assemblies[hash_entry->mapping_index];
if (assembly_runtime_info.image_data == nullptr) {
if (hash_entry->store_id >= application_config.number_of_assembly_store_files) {
log_fatal (LOG_ASSEMBLY, "Invalid assembly store ID %u, exceeds the maximum of %u", hash_entry->store_id, application_config.number_of_assembly_store_files - 1);
abort ();
}
AssemblyStoreRuntimeData &rd = assembly_stores[hash_entry->store_id];
if (hash_entry->local_store_index >= rd.assembly_count) {
log_fatal (LOG_ASSEMBLY, "Invalid index %u into local store assembly descriptor array", hash_entry->local_store_index);
}
AssemblyStoreAssemblyDescriptor *bba = &rd.assemblies[hash_entry->local_store_index];
// The assignments here don't need to be atomic, the value will always be the same, so even if two threads
// arrive here at the same time, nothing bad will happen.
assembly_runtime_info.image_data = rd.data_start + bba->data_offset;
assembly_runtime_info.descriptor = bba;
if (bba->debug_data_offset != 0) {
assembly_runtime_info.debug_info_data = rd.data_start + bba->debug_data_offset;
}
#if !defined (NET6)
if (bba->config_data_size != 0) {
assembly_runtime_info.config_data = rd.data_start + bba->config_data_offset;
// Mono takes ownership of the pointers
mono_register_config_for_assembly (
utils.string_concat (name.get (), ".dll"),
utils.strdup_new (reinterpret_cast<const char*>(assembly_runtime_info.config_data))
);
}
#endif // NET6
log_debug (
LOG_ASSEMBLY,
"Mapped: image_data == %p; debug_info_data == %p; config_data == %p; descriptor == %p; data size == %u; debug data size == %u; config data size == %u",
assembly_runtime_info.image_data,
assembly_runtime_info.debug_info_data,
assembly_runtime_info.config_data,
assembly_runtime_info.descriptor,
assembly_runtime_info.descriptor->data_size,
assembly_runtime_info.descriptor->debug_data_size,
assembly_runtime_info.descriptor->config_data_size
);
}
uint8_t *assembly_data;
uint32_t assembly_data_size;
if (!have_dll_ext) {
// AOT needs this since Mono will form the DSO name by appending the .so suffix to the assembly name passed to
// functions below and `monodroid_dlopen` uses the `.dll.so` extension to check whether we're being asked to load
// the AOTd code for an assembly.
name.append (SharedConstants::DLL_EXTENSION);
}
get_assembly_data (assembly_runtime_info, assembly_data, assembly_data_size);
MonoImage *image = loader (assembly_data, assembly_data_size, name.get ());
if (image == nullptr) {
log_warn (LOG_ASSEMBLY, "Failed to load MonoImage of '%s'", name.get ());
return nullptr;
}
if (have_and_want_debug_symbols && assembly_runtime_info.debug_info_data != nullptr) {
log_debug (LOG_ASSEMBLY, "Registering debug data for assembly '%s'", name.get ());
mono_debug_open_image_from_memory (image, reinterpret_cast<const mono_byte*> (assembly_runtime_info.debug_info_data), static_cast<int>(assembly_runtime_info.descriptor->debug_data_size));
}
MonoImageOpenStatus status;
MonoAssembly *a = mono_assembly_load_from_full (image, name.get (), &status, ref_only);
if (a == nullptr) {
return nullptr;
}
#if !defined (NET6)
mono_config_for_assembly (image);
#endif
return a;
}
MonoAssembly*
EmbeddedAssemblies::open_from_bundles (MonoAssemblyName* aname, std::function<MonoImage*(uint8_t*, size_t, const char*)> loader, bool ref_only)
{
const char *culture = mono_assembly_name_get_culture (aname);
const char *asmname = mono_assembly_name_get_name (aname);
dynamic_local_string<SENSIBLE_PATH_MAX> name;
if (culture != nullptr && *culture != '\0') {
name.append_c (culture);
name.append (zip_path_separator);
}
name.append_c (asmname);
MonoAssembly *a;
if (application_config.have_assembly_store) {
a = assembly_store_open_from_bundles (name, loader, ref_only);
} else {
a = individual_assemblies_open_from_bundles (name, loader, ref_only);
}
if (a == nullptr) {
log_warn (LOG_ASSEMBLY, "open_from_bundles: failed to load assembly %s", name.get ());
}
return a;
}
#if defined (NET6)
MonoAssembly*
EmbeddedAssemblies::open_from_bundles (MonoAssemblyLoadContextGCHandle alc_gchandle, MonoAssemblyName *aname, [[maybe_unused]] char **assemblies_path, [[maybe_unused]] void *user_data, MonoError *error)
{
return embeddedAssemblies.open_from_bundles (aname, alc_gchandle, error);
}
#else // def NET6
MonoAssembly*
EmbeddedAssemblies::open_from_bundles_refonly (MonoAssemblyName *aname, [[maybe_unused]] char **assemblies_path, [[maybe_unused]] void *user_data)
{
return embeddedAssemblies.open_from_bundles (aname, true);
}
#endif // ndef NET6
MonoAssembly*
EmbeddedAssemblies::open_from_bundles_full (MonoAssemblyName *aname, [[maybe_unused]] char **assemblies_path, [[maybe_unused]] void *user_data)
{
return embeddedAssemblies.open_from_bundles (aname, false);
}
void
EmbeddedAssemblies::install_preload_hooks_for_appdomains ()
{
mono_install_assembly_preload_hook (open_from_bundles_full, nullptr);
#if !defined (NET6)
mono_install_assembly_refonly_preload_hook (open_from_bundles_refonly, nullptr);
#endif // ndef NET6
}
#if defined (NET6)
void
EmbeddedAssemblies::install_preload_hooks_for_alc ()
{
mono_install_assembly_preload_hook_v3 (
open_from_bundles,
nullptr /* user_data */,
0 /* append */
);
}
#endif // def NET6
template<typename Key, typename Entry, int (*compare)(const Key*, const Entry*), bool use_extra_size>
const Entry*
EmbeddedAssemblies::binary_search (const Key *key, const Entry *base, size_t nmemb, [[maybe_unused]] size_t extra_size)
{
static_assert (compare != nullptr, "compare is a required template parameter");
// This comes from the user code, so let's be civil
if (key == nullptr) {
log_warn (LOG_ASSEMBLY, "Key passed to binary_search must not be nullptr");
return nullptr;
}
// This is a coding error on our part, crash!
if (base == nullptr) {
log_fatal (LOG_ASSEMBLY, "Map address not passed to binary_search");
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
constexpr size_t size = sizeof(Entry);
while (nmemb > 0) {
const Entry *ret;
if constexpr (use_extra_size) {
ret = reinterpret_cast<const Entry*>(reinterpret_cast<const uint8_t*>(base) + ((size + extra_size) * (nmemb / 2)));
} else {
ret = base + (nmemb / 2);
}
int result = compare (key, ret);
if (result < 0) {
nmemb /= 2;
} else if (result > 0) {
if constexpr (use_extra_size) {
base = reinterpret_cast<const Entry*>(reinterpret_cast<const uint8_t*>(ret) + size + extra_size);
} else {
base = ret + 1;
}
nmemb -= nmemb / 2 + 1;
} else {
return ret;
}
}
return nullptr;
}
#if defined (DEBUG) || !defined (ANDROID)
int
EmbeddedAssemblies::compare_type_name (const char *type_name, const TypeMapEntry *entry)
{
if (entry == nullptr)
return 1;
return strcmp (type_name, entry->from);
}
MonoReflectionType*
EmbeddedAssemblies::typemap_java_to_managed (const char *java_type_name)
{
const TypeMapEntry *entry = nullptr;
if (application_config.instant_run_enabled) {
TypeMap *module;
for (size_t i = 0; i < type_map_count; i++) {
module = &type_maps[i];
entry = binary_search<const char, TypeMapEntry, compare_type_name, false> (java_type_name, module->java_to_managed, module->entry_count);
if (entry != nullptr)
break;
}
} else {
entry = binary_search<const char, TypeMapEntry, compare_type_name, false> (java_type_name, type_map.java_to_managed, type_map.entry_count);
}
if (XA_UNLIKELY (entry == nullptr)) {
log_info (LOG_ASSEMBLY, "typemap: unable to find mapping to a managed type from Java type '%s'", java_type_name);
return nullptr;
}
const char *managed_type_name = entry->to;
if (managed_type_name == nullptr) {
log_debug (LOG_ASSEMBLY, "typemap: Java type '%s' maps either to an open generic type or an interface type.", java_type_name);
return nullptr;
}
log_debug (LOG_DEFAULT, "typemap: Java type '%s' corresponds to managed type '%s'", java_type_name, managed_type_name);
MonoType *type = mono_reflection_type_from_name (const_cast<char*>(managed_type_name), nullptr);
if (XA_UNLIKELY (type == nullptr)) {
log_info (LOG_ASSEMBLY, "typemap: managed type '%s' (mapped from Java type '%s') could not be loaded", managed_type_name, java_type_name);
return nullptr;
}
MonoReflectionType *ret = mono_type_get_object (utils.get_current_domain (), type);
if (XA_UNLIKELY (ret == nullptr)) {
log_warn (LOG_ASSEMBLY, "typemap: unable to instantiate managed type '%s'", managed_type_name);
return nullptr;
}
return ret;
}
#else
MonoReflectionType*
EmbeddedAssemblies::typemap_java_to_managed (const char *java_type_name)
{
TypeMapModule *module;
const TypeMapJava *java_entry = binary_search<const char, TypeMapJava, compare_java_name, true> (java_type_name, map_java, java_type_count, java_name_width);
if (java_entry == nullptr) {
log_info (LOG_ASSEMBLY, "typemap: unable to find mapping to a managed type from Java type '%s'", java_type_name);
return nullptr;
}
if (java_entry->module_index >= map_module_count) {
log_warn (LOG_ASSEMBLY, "typemap: mapping from Java type '%s' to managed type has invalid module index", java_type_name);
return nullptr;
}
module = const_cast<TypeMapModule*>(&map_modules[java_entry->module_index]);
const TypeMapModuleEntry *entry = binary_search <uint32_t, TypeMapModuleEntry, compare_type_token> (&java_entry->type_token_id, module->map, module->entry_count);
if (entry == nullptr) {
log_info (LOG_ASSEMBLY, "typemap: unable to find mapping from Java type '%s' to managed type with token ID %u in module [%s]", java_type_name, java_entry->type_token_id, MonoGuidString (module->module_uuid).get ());
return nullptr;
}
uint32_t type_token_id = java_entry->type_token_id;
if (module->image == nullptr) {
module->image = mono_image_loaded (module->assembly_name);
if (module->image == nullptr) {
// TODO: load
log_error (LOG_ASSEMBLY, "typemap: assembly '%s' not loaded yet!", module->assembly_name);
}
if (module->image == nullptr) {
log_error (LOG_ASSEMBLY, "typemap: unable to load assembly '%s' when looking up managed type corresponding to Java type '%s'", module->assembly_name, java_type_name);
return nullptr;
}
}
log_debug (LOG_ASSEMBLY, "typemap: java type '%s' corresponds to managed token id %u (0x%x)", java_type_name, type_token_id, type_token_id);
MonoClass *klass = mono_class_get (module->image, static_cast<uint32_t>(type_token_id));
if (klass == nullptr) {
log_error (LOG_ASSEMBLY, "typemap: unable to find managed type with token ID %u in assembly '%s', corresponding to Java type '%s'", type_token_id, module->assembly_name, java_type_name);
return nullptr;
}
#if defined (NET6)
// MonoVM in dotnet runtime doesn't use the `domain` parameter passed to `mono_type_get_object` (since AppDomains
// are gone in NET6+), in fact, the function `mono_type_get_object` calls (`mono_type_get_object_checked`) itself
// calls `mono_get_root_domain`. Thus, we can save on a one function call here by passing `nullptr`
constexpr MonoDomain *domain = nullptr;
#else
MonoDomain *domain = utils.get_current_domain ();
#endif
MonoReflectionType *ret = mono_type_get_object (domain, mono_class_get_type (klass));
if (ret == nullptr) {
log_warn (LOG_ASSEMBLY, "typemap: unable to instantiate managed type with token ID %u in assembly '%s', corresponding to Java type '%s'", type_token_id, module->assembly_name, java_type_name);
return nullptr;
}
return ret;
}
int
EmbeddedAssemblies::compare_java_name (const char *java_name, const TypeMapJava *entry)
{
if (entry == nullptr || entry->java_name[0] == '\0') {
return -1;
}
return strcmp (java_name, reinterpret_cast<const char*>(entry->java_name));
}
#endif
MonoReflectionType*
EmbeddedAssemblies::typemap_java_to_managed (MonoString *java_type)
{
timing_period total_time;
if (XA_UNLIKELY (utils.should_log (LOG_TIMING))) {
timing = new Timing ();
total_time.mark_start ();
}
if (XA_UNLIKELY (java_type == nullptr)) {
log_warn (LOG_ASSEMBLY, "typemap: null 'java_type' passed to 'typemap_java_to_managed'");
return nullptr;
}
c_unique_ptr<char> java_type_name {mono_string_to_utf8 (java_type)};
if (XA_UNLIKELY (!java_type_name || *java_type_name == '\0')) {
log_warn (LOG_ASSEMBLY, "typemap: empty Java type name passed to 'typemap_java_to_managed'");
return nullptr;
}
MonoReflectionType *ret = typemap_java_to_managed (java_type_name.get ());
if (XA_UNLIKELY (utils.should_log (LOG_TIMING))) {
total_time.mark_end ();
Timing::info (total_time, "Typemap.java_to_managed: end, total time");
}
return ret;
}
#if defined (DEBUG) || !defined (ANDROID)
inline const TypeMapEntry*
EmbeddedAssemblies::typemap_managed_to_java (const char *managed_type_name)
{
const TypeMapEntry *entry = nullptr;
if (application_config.instant_run_enabled) {
TypeMap *module;
for (size_t i = 0; i < type_map_count; i++) {
module = &type_maps[i];
entry = binary_search<const char, TypeMapEntry, compare_type_name, false> (managed_type_name, module->managed_to_java, module->entry_count);
if (entry != nullptr)
break;
}
} else {
entry = binary_search<const char, TypeMapEntry, compare_type_name, false> (managed_type_name, type_map.managed_to_java, type_map.entry_count);
}
return entry;
}
inline const char*
EmbeddedAssemblies::typemap_managed_to_java ([[maybe_unused]] MonoType *type, MonoClass *klass, [[maybe_unused]] const uint8_t *mvid)
{
c_unique_ptr<char> type_name {mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_FULL_NAME)};
MonoImage *image = mono_class_get_image (klass);
const char *image_name = mono_image_get_name (image);
size_t type_name_len = strlen (type_name.get ());
size_t image_name_len = strlen (image_name);
dynamic_local_string<SENSIBLE_PATH_MAX> full_name;
full_name
.append (type_name.get (), type_name_len)
.append (", ")
.append (image_name, image_name_len);
const TypeMapEntry *entry = typemap_managed_to_java (full_name.get ());
if (XA_UNLIKELY (entry == nullptr)) {
log_info (LOG_ASSEMBLY, "typemap: unable to find mapping to a Java type from managed type '%s'", full_name.get ());
return nullptr;
}
return entry->to;
}
#else
inline int
EmbeddedAssemblies::compare_type_token (const uint32_t *token, const TypeMapModuleEntry *entry)
{
if (entry == nullptr) {
log_fatal (LOG_ASSEMBLY, "typemap: compare_type_token: entry is nullptr");
exit (FATAL_EXIT_MISSING_ASSEMBLY);
}
if (*token < entry->type_token_id)
return -1;
if (*token > entry->type_token_id)
return 1;
return 0;
}
inline int
EmbeddedAssemblies::compare_mvid (const uint8_t *mvid, const TypeMapModule *module)
{
return memcmp (mvid, module->module_uuid, sizeof(module->module_uuid));
}
inline const char*
EmbeddedAssemblies::typemap_managed_to_java ([[maybe_unused]] MonoType *type, MonoClass *klass, const uint8_t *mvid)
{
if (mvid == nullptr) {
log_warn (LOG_ASSEMBLY, "typemap: no mvid specified in call to typemap_managed_to_java");
return nullptr;
}
const TypeMapModule *map;
size_t map_entry_count;
map = map_modules;
map_entry_count = map_module_count;
const TypeMapModule *match = binary_search<uint8_t, TypeMapModule, compare_mvid> (mvid, map, map_entry_count);
if (match == nullptr) {
log_info (LOG_ASSEMBLY, "typemap: module matching MVID [%s] not found.", MonoGuidString (mvid).get ());
return nullptr;
}
if (match->map == nullptr) {
log_warn (LOG_ASSEMBLY, "typemap: module with MVID [%s] has no associated type map.", MonoGuidString (mvid).get ());
return nullptr;
}
uint32_t token = mono_class_get_type_token (klass);
log_debug (LOG_ASSEMBLY, "typemap: MVID [%s] maps to assembly %s, looking for token %d (0x%x), table index %d", MonoGuidString (mvid).get (), match->assembly_name, token, token, token & 0x00FFFFFF);
// Each map entry is a pair of 32-bit integers: [TypeTokenID][JavaMapArrayIndex]
const TypeMapModuleEntry *entry = binary_search <uint32_t, TypeMapModuleEntry, compare_type_token> (&token, match->map, match->entry_count);
if (entry == nullptr) {
if (match->duplicate_count > 0 && match->duplicate_map != nullptr) {
log_debug (LOG_ASSEMBLY, "typemap: searching module [%s] duplicate map for token %u (0x%x)", MonoGuidString (mvid).get (), token, token);
entry = binary_search <uint32_t, TypeMapModuleEntry, compare_type_token> (&token, match->duplicate_map, match->duplicate_count);
}
if (entry == nullptr) {
log_info (LOG_ASSEMBLY, "typemap: type with token %d (0x%x) in module {%s} (%s) not found.", token, token, MonoGuidString (mvid).get (), match->assembly_name);
return nullptr;
}
}
uint32_t java_entry_count;
java_entry_count = java_type_count;
if (entry->java_map_index >= java_entry_count) {
log_warn (LOG_ASSEMBLY, "typemap: type with token %d (0x%x) in module {%s} (%s) has invalid Java type index %u", token, token, MonoGuidString (mvid).get (), match->assembly_name, entry->java_map_index);
return nullptr;
}
const char *ret;
const TypeMapJava *java_entry = reinterpret_cast<const TypeMapJava*> (reinterpret_cast<const uint8_t*>(map_java) + ((sizeof(TypeMapJava) + java_name_width) * entry->java_map_index));
ret = reinterpret_cast<const char*>(reinterpret_cast<const uint8_t*>(java_entry) + 8);
if (XA_UNLIKELY (ret == nullptr)) {
log_warn (LOG_ASSEMBLY, "typemap: empty Java type name returned for entry at index %u", entry->java_map_index);
}
log_debug (
LOG_ASSEMBLY,
"typemap: type with token %d (0x%x) in module {%s} (%s) corresponds to Java type '%s'",
token,
token,
MonoGuidString (mvid).get (),
match->assembly_name,
ret
);
return ret;
}
#endif
const char*
EmbeddedAssemblies::typemap_managed_to_java (MonoReflectionType *reflection_type, const uint8_t *mvid)
{
timing_period total_time;
if (XA_UNLIKELY (utils.should_log (LOG_TIMING))) {
timing = new Timing ();
total_time.mark_start ();
}
MonoType *type = mono_reflection_type_get_type (reflection_type);
if (type == nullptr) {
log_warn (LOG_ASSEMBLY, "Failed to map reflection type to MonoType");
return nullptr;
}
const char *ret = typemap_managed_to_java (type, mono_class_from_mono_type (type), mvid);
if (XA_UNLIKELY (utils.should_log (LOG_TIMING))) {
total_time.mark_end ();
Timing::info (total_time, "Typemap.managed_to_java: end, total time");
}
return ret;
}
EmbeddedAssemblies::md_mmap_info
EmbeddedAssemblies::md_mmap_apk_file (int fd, uint32_t offset, size_t size, const char* filename)
{
md_mmap_info file_info;
md_mmap_info mmap_info;
size_t pageSize = static_cast<size_t>(utils.monodroid_getpagesize ());
size_t offsetFromPage = offset % pageSize;
size_t offsetPage = offset - offsetFromPage;
size_t offsetSize = size + offsetFromPage;
mmap_info.area = mmap (nullptr, offsetSize, PROT_READ, MAP_PRIVATE, fd, static_cast<off_t>(offsetPage));
if (mmap_info.area == MAP_FAILED) {
log_fatal (LOG_DEFAULT, "Could not `mmap` apk fd %d entry `%s`: %s", fd, filename, strerror (errno));
exit (FATAL_EXIT_CANNOT_FIND_APK);
}
mmap_info.size = offsetSize;
file_info.area = (void*)((const char*)mmap_info.area + offsetFromPage);
file_info.size = size;
log_info (LOG_ASSEMBLY, " mmap_start: %08p mmap_end: %08p mmap_len: % 12u file_start: %08p file_end: %08p file_len: % 12u apk descriptor: %d file: %s",
mmap_info.area, reinterpret_cast<int*> (mmap_info.area) + mmap_info.size, mmap_info.size,
file_info.area, reinterpret_cast<int*> (file_info.area) + file_info.size, file_info.size, fd, filename);
return file_info;
}
void
EmbeddedAssemblies::gather_bundled_assemblies_from_apk (const char* apk, monodroid_should_register should_register)
{
int fd;
if ((fd = open (apk, O_RDONLY)) < 0) {
log_error (LOG_DEFAULT, "ERROR: Unable to load application package %s.", apk);
exit (FATAL_EXIT_NO_ASSEMBLIES);
}
log_info (LOG_ASSEMBLY, "APK %s FD: %d", apk, fd);
zip_load_entries (fd, apk, should_register);
}
#if defined (DEBUG) || !defined (ANDROID)
ssize_t EmbeddedAssemblies::do_read (int fd, void *buf, size_t count)
{
ssize_t ret;
do {
ret = ::read (
fd,
buf,
#if defined (WINDOWS)
static_cast<unsigned int>(count)
#else
count
#endif
);
} while (ret < 0 && errno == EINTR);
return ret;
}
template<typename H>
bool
EmbeddedAssemblies::typemap_read_header ([[maybe_unused]] int dir_fd, const char *file_type, const char *dir_path, const char *file_path, uint32_t expected_magic, H &header, size_t &file_size, int &fd)
{
struct stat sbuf;
int res;
#if __ANDROID_API__ < 21
std::unique_ptr<char> full_file_path {utils.path_combine (dir_path, file_path)};
res = stat (full_file_path.get (), &sbuf);
#else
res = fstatat (dir_fd, file_path, &sbuf, 0);
#endif
if (res < 0) {
log_error (LOG_ASSEMBLY, "typemap: failed to stat %s file '%s/%s': %s", file_type, dir_path, file_path, strerror (errno));
return false;
}
file_size = static_cast<size_t>(sbuf.st_size);
if (file_size < sizeof (header)) {
log_error (LOG_ASSEMBLY, "typemap: %s file '%s/%s' is too small (must be at least %u bytes)", file_type, dir_path, file_path, sizeof (header));
return false;
}
#if __ANDROID_API__ < 21
fd = open (full_file_path.get (), O_RDONLY);
#else
fd = openat (dir_fd, file_path, O_RDONLY);
#endif
if (fd < 0) {
log_error (LOG_ASSEMBLY, "typemap: failed to open %s file %s/%s for reading: %s", file_type, dir_path, file_path, strerror (errno));
return false;
}
ssize_t nread = do_read (fd, &header, sizeof (header));
if (nread <= 0) {
if (nread < 0) {
log_error (LOG_ASSEMBLY, "typemap: failed to read %s file header from '%s/%s': %s", file_type, dir_path, file_path, strerror (errno));
} else {
log_error (LOG_ASSEMBLY, "typemap: end of file while reading %s file header from '%s/%s'", file_type, dir_path, file_path);
}
return false;
}
if (header.magic != expected_magic) {
log_error (LOG_ASSEMBLY, "typemap: invalid magic value in the %s file header from '%s/%s': expected 0x%X, got 0x%X", file_type, dir_path, file_path, expected_magic, header.magic);
return false;
}
if (header.version != MODULE_FORMAT_VERSION) {
log_error (LOG_ASSEMBLY, "typemap: incompatible %s format version. This build supports only version %u, file '%s/%s' uses version %u", file_type, MODULE_FORMAT_VERSION, dir_path, file_path, header.version);
return false;
}
return true;
}
std::unique_ptr<uint8_t[]>
EmbeddedAssemblies::typemap_load_index (TypeMapIndexHeader &header, size_t file_size, int index_fd)
{
size_t entry_size = header.module_file_name_width;
size_t data_size = entry_size * type_map_count;
if (sizeof(header) + data_size > file_size) {
log_error (LOG_ASSEMBLY, "typemap: index file is too small, expected %u, found %u bytes", data_size + sizeof(header), file_size);
return nullptr;
}
auto data = std::make_unique<uint8_t[]> (data_size);
ssize_t nread = do_read (index_fd, data.get (), data_size);
if (nread != static_cast<ssize_t>(data_size)) {
log_error (LOG_ASSEMBLY, "typemap: failed to read %u bytes from index file. %s", data_size, strerror (errno));
return nullptr;
}
uint8_t *p = data.get ();
for (size_t i = 0; i < type_map_count; i++) {
type_maps[i].assembly_name = reinterpret_cast<char*>(p);
p += entry_size;
}
return data;
}
std::unique_ptr<uint8_t[]>
EmbeddedAssemblies::typemap_load_index (int dir_fd, const char *dir_path, const char *index_path)
{
log_debug (LOG_ASSEMBLY, "typemap: loading TypeMap index file '%s/%s'", dir_path, index_path);
TypeMapIndexHeader header;
size_t file_size;
int fd = -1;
std::unique_ptr<uint8_t[]> data;
if (typemap_read_header (dir_fd, "TypeMap index", dir_path, index_path, MODULE_INDEX_MAGIC, header, file_size, fd)) {
type_map_count = header.entry_count;
type_maps = new TypeMap[type_map_count]();
data = typemap_load_index (header, file_size, fd);
}
if (fd >= 0)
close (fd);
return data;
}
bool
EmbeddedAssemblies::typemap_load_file (BinaryTypeMapHeader &header, const char *dir_path, const char *file_path, int file_fd, TypeMap &module)
{
size_t alloc_size = ADD_WITH_OVERFLOW_CHECK (size_t, header.assembly_name_length, 1);
module.assembly_name = new char[alloc_size];
ssize_t nread = do_read (file_fd, module.assembly_name, header.assembly_name_length);
if (nread != static_cast<ssize_t>(header.assembly_name_length)) {
log_error (LOG_ASSEMBLY, "tyemap: failed to read map assembly name from '%s/%s': %s", dir_path, file_path, strerror (errno));
return false;
}
module.assembly_name [header.assembly_name_length] = 0;
module.entry_count = header.entry_count;
log_debug (
LOG_ASSEMBLY,
"typemap: '%s/%s':: entry count == %u; Java name field width == %u; Managed name width == %u; assembly name length == %u; assembly name == %s",
dir_path, file_path, header.entry_count, header.java_name_width, header.managed_name_width, header.assembly_name_length, module.assembly_name
);
// [name][index]
size_t java_entry_size = header.java_name_width + sizeof(uint32_t);
size_t managed_entry_size = header.managed_name_width + sizeof(uint32_t);
size_t data_size = ADD_WITH_OVERFLOW_CHECK (
size_t,
header.entry_count * java_entry_size,
header.entry_count * managed_entry_size
);
module.data = new uint8_t [data_size];
nread = do_read (file_fd, module.data, data_size);
if (nread != static_cast<ssize_t>(data_size)) {
log_error (LOG_ASSEMBLY, "tyemap: failed to read map data from '%s/%s': %s", dir_path, file_path, strerror (errno));
return false;
}
module.java_to_managed = new TypeMapEntry [module.entry_count];
module.managed_to_java = new TypeMapEntry [module.entry_count];
uint8_t *java_start = module.data;
uint8_t *managed_start = module.data + (module.entry_count * java_entry_size);
uint8_t *java_pos = java_start;
uint8_t *managed_pos = managed_start;
TypeMapEntry *cur;
constexpr uint32_t INVALID_TYPE_INDEX = std::numeric_limits<uint32_t>::max ();
for (size_t i = 0; i < module.entry_count; i++) {
cur = &module.java_to_managed[i];
cur->from = reinterpret_cast<char*>(java_pos);
uint32_t idx;
// This might seem slow but it is in fact compiled into a single instruction and is safe when loading the 32-bit
// integer from unaligned memory
memcpy (&idx, java_pos + header.java_name_width, sizeof (idx));
if (idx < INVALID_TYPE_INDEX) {
cur->to = reinterpret_cast<char*>(managed_start + (managed_entry_size * idx));
} else {
// Ignore the type mapping
cur->to = nullptr;
}
java_pos += java_entry_size;
cur = &module.managed_to_java[i];
cur->from = reinterpret_cast<char*>(managed_pos);
memcpy (&idx, managed_pos + header.managed_name_width, sizeof (idx));
cur->to = reinterpret_cast<char*>(java_start + (java_entry_size * idx));
managed_pos += managed_entry_size;
}
return true;
}
bool
EmbeddedAssemblies::typemap_load_file (int dir_fd, const char *dir_path, const char *file_path, TypeMap &module)
{
log_debug (LOG_ASSEMBLY, "typemap: loading TypeMap file '%s/%s'", dir_path, file_path);
bool ret = true;
BinaryTypeMapHeader header;
size_t file_size;
int fd = -1;
module.java_to_managed = nullptr;
module.managed_to_java = nullptr;
if (!typemap_read_header (dir_fd, "TypeMap", dir_path, file_path, MODULE_MAGIC_NAMES, header, file_size, fd)) {
ret = false;
goto cleanup;
}
ret = typemap_load_file (header, dir_path, file_path, fd, module);
cleanup:
if (fd >= 0)
close (fd);
if (!ret) {
delete[] module.java_to_managed;
module.java_to_managed = nullptr;
delete[] module.managed_to_java;
module.managed_to_java = nullptr;
}
return ret;
}
void
EmbeddedAssemblies::try_load_typemaps_from_directory (const char *path)
{
if (!application_config.instant_run_enabled) {
log_info (LOG_ASSEMBLY, "typemap: instant run disabled, not loading type maps from storage");
return;
}
std::unique_ptr<char> dir_path {utils.path_combine (path, "typemaps")};
monodroid_dir_t *dir;
if ((dir = utils.monodroid_opendir (dir_path.get ())) == nullptr) {
log_warn (LOG_ASSEMBLY, "typemap: could not open directory: `%s`", dir_path.get ());
return;
}
int dir_fd;
#if __ANDROID_API__ < 21
dir_fd = -1;
#else
dir_fd = dirfd (dir);
#endif
constexpr char index_name[] = "typemap.index";
// The pointer must be stored here because, after index is loaded, module.assembly_name points into the index data
// and must be valid until after the actual module file is loaded.
std::unique_ptr<uint8_t[]> index_data = typemap_load_index (dir_fd, dir_path.get (), index_name);
if (!index_data) {
log_fatal (LOG_ASSEMBLY, "typemap: unable to load TypeMap data index from '%s/%s'", dir_path.get (), index_name);
exit (FATAL_EXIT_NO_ASSEMBLIES); // TODO: use a new error code here
}
for (size_t i = 0; i < type_map_count; i++) {
TypeMap *module = &type_maps[i];
if (!typemap_load_file (dir_fd, dir_path.get (), module->assembly_name, *module)) {
continue;
}
}
utils.monodroid_closedir (dir);
}
#endif
size_t
EmbeddedAssemblies::register_from (const char *apk_file, monodroid_should_register should_register)
{
size_t prev = number_of_found_assemblies;
gather_bundled_assemblies_from_apk (apk_file, should_register);
log_info (LOG_ASSEMBLY, "Package '%s' contains %i assemblies", apk_file, number_of_found_assemblies - prev);
return number_of_found_assemblies;
}
| 42,691
| 16,794
|
/*
* Copyright (c) 2018, Bosch Software Innovations GmbH.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. 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 <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <OgreEntity.h>
#include <OgreMesh.h>
#include <OgreManualObject.h>
#include "visualization_msgs/msg/marker.hpp"
#include "rviz_rendering/objects/arrow.hpp"
#include "rviz_rendering/objects/shape.hpp"
#include "../../scene_graph_introspection.hpp"
#include "rviz_default_plugins/displays/path/path_display.hpp"
#include "../display_test_fixture.hpp"
using namespace ::testing; // NOLINT
class PathTestFixture : public DisplayTestFixture
{
public:
PathTestFixture()
{
path_display_ = std::make_shared<rviz_default_plugins::displays::PathDisplay>(context_.get());
}
std::shared_ptr<rviz_default_plugins::displays::PathDisplay> path_display_;
};
nav_msgs::msg::Path::ConstSharedPtr createPathMessage()
{
auto message = std::make_shared<nav_msgs::msg::Path>();
message->header = std_msgs::msg::Header();
message->header.frame_id = "path_frame";
message->header.stamp = rclcpp::Clock().now();
auto pose = geometry_msgs::msg::PoseStamped();
pose.pose.position.x = 1;
pose.pose.position.y = 1;
pose.pose.position.z = 1;
auto orientation = Ogre::Quaternion::IDENTITY;
pose.pose.orientation.w = orientation.w;
pose.pose.orientation.x = orientation.x;
pose.pose.orientation.y = orientation.y;
pose.pose.orientation.z = orientation.z;
auto pose2 = geometry_msgs::msg::PoseStamped();
pose2.pose.position.x = 4;
pose2.pose.position.y = 2;
pose2.pose.position.z = 0;
auto orientation2 = Ogre::Quaternion::IDENTITY;
pose2.pose.orientation.w = orientation2.w;
pose2.pose.orientation.x = orientation2.x;
pose2.pose.orientation.y = orientation2.y;
pose2.pose.orientation.z = orientation2.z;
message->poses = std::vector<geometry_msgs::msg::PoseStamped>({pose, pose2});
return message;
}
TEST_F(PathTestFixture, processMessage_adds_nothing_to_scene_if_invalid_transformation) {
EXPECT_CALL(*frame_manager_, getTransform(_, _, _, _)).WillOnce(Return(false)); // NOLINT
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getNumSections(), Eq(0u));
}
TEST_F(PathTestFixture, processMessage_adds_vertices_to_scene) {
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getSection(0)->getRenderOperation()->vertexData->vertexCount, Eq(2u));
}
TEST_F(PathTestFixture, reset_clears_the_scene) {
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
path_display_->reset();
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getNumSections(), Eq(0u));
}
TEST_F(PathTestFixture, reset_is_idempotent) {
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
path_display_->reset();
path_display_->reset();
ASSERT_TRUE(1);
}
TEST_F(PathTestFixture, reset_removes_all_axes) {
path_display_->findProperty("Pose Style")->setValue("Axes");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
EXPECT_THAT(rviz_default_plugins::findAllAxes(scene_manager_->getRootSceneNode()), SizeIs(2));
path_display_->reset();
EXPECT_THAT(rviz_default_plugins::findAllAxes(scene_manager_->getRootSceneNode()), SizeIs(0));
}
TEST_F(PathTestFixture, reset_removes_all_arrows) {
path_display_->findProperty("Pose Style")->setValue("Arrows");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
EXPECT_THAT(rviz_default_plugins::findAllArrows(scene_manager_->getRootSceneNode()), SizeIs(2));
path_display_->reset();
EXPECT_THAT(rviz_default_plugins::findAllArrows(scene_manager_->getRootSceneNode()), SizeIs(0));
}
TEST_F(PathTestFixture, processMessage_transforms_the_vertices_correctly) {
auto position = Ogre::Vector3(1, 2, 3);
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getSection(0)->getRenderOperation()->vertexData->vertexCount, Eq(2u));
// Use bounding box to indirectly assert the vertices
EXPECT_THAT(object->getBoundingBox().getMinimum(), Vector3Eq(Ogre::Vector3(2, 3, 3)));
EXPECT_THAT(object->getBoundingBox().getMaximum(), Vector3Eq(Ogre::Vector3(5, 4, 4)));
}
TEST_F(PathTestFixture, processMessage_adds_billboard_line_to_scene) {
path_display_->findProperty("Line Style")->setValue("Billboards");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneBillboardChain(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getNumberOfChains(), Eq(1u));
EXPECT_THAT(object->getNumChainElements(0), Eq(2u));
EXPECT_THAT(object->getChainElement(0, 0).position, Vector3Eq(Ogre::Vector3(4, 2, 0)));
EXPECT_THAT(object->getChainElement(0, 1).position, Vector3Eq(Ogre::Vector3(1, 1, 1)));
}
TEST_F(PathTestFixture, processMessage_adds_axes_to_scene) {
path_display_->findProperty("Pose Style")->setValue("Axes");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto axes = rviz_default_plugins::findAllAxes(scene_manager_->getRootSceneNode());
EXPECT_THAT(axes, SizeIs(2));
auto axes_positions = rviz_default_plugins::getPositionsFromNodes(axes);
EXPECT_THAT(axes_positions, Contains(Vector3Eq(Ogre::Vector3(4, 2, 0))));
EXPECT_THAT(axes_positions, Contains(Vector3Eq(Ogre::Vector3(1, 1, 1))));
}
TEST_F(PathTestFixture, processMessage_adds_arrows_to_scene) {
path_display_->findProperty("Pose Style")->setValue("Arrows");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto arrows = rviz_default_plugins::findAllArrows(scene_manager_->getRootSceneNode());
EXPECT_THAT(arrows, SizeIs(2));
auto arrow_positions = rviz_default_plugins::getPositionsFromNodes(arrows);
EXPECT_THAT(arrow_positions, Contains(Vector3Eq(Ogre::Vector3(1, 1, 1))));
EXPECT_THAT(arrow_positions, Contains(Vector3Eq(Ogre::Vector3(4, 2, 0))));
// default orientation is set to (0.5, -0.5, -0.5, -0.5) by arrow
auto default_orientation = Ogre::Quaternion(0.5f, -0.5f, -0.5f, -0.5f);
auto arrow_orientations = rviz_default_plugins::getOrientationsFromNodes(arrows);
EXPECT_THAT(arrow_orientations, Each(QuaternionEq(default_orientation)));
}
| 9,270
| 3,288
|
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2019-2022 Second State INC
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 233
| 101
|
// Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_Mast.BP_Mast_C.AttemptToAddDamageDecal
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> RepairableState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class UDecalComponent* DecalComponent (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor)
// struct FTransform RelativeTransform (ConstParm, Parm, IsPlainOldData, NoDestructor)
// class UMaterialInterface* NewDecalMaterial (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::AttemptToAddDamageDecal(TEnumAsByte<Repair_ERepairableState> RepairableState, class UDecalComponent** DecalComponent, const struct FTransform& RelativeTransform, class UMaterialInterface* NewDecalMaterial)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.AttemptToAddDamageDecal");
ABP_Mast_C_AttemptToAddDamageDecal_Params params;
params.RepairableState = RepairableState;
params.RelativeTransform = RelativeTransform;
params.NewDecalMaterial = NewDecalMaterial;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (DecalComponent != nullptr)
*DecalComponent = params.DecalComponent;
}
// Function BP_Mast.BP_Mast_C.IsMastVisuallyFractured
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool ABP_Mast_C::IsMastVisuallyFractured()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.IsMastVisuallyFractured");
ABP_Mast_C_IsMastVisuallyFractured_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function BP_Mast.BP_Mast_C.Customise Static Mesh
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UStaticMesh* New_Static_Mesh (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class UStaticMeshComponent* Static_Mesh_Component (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::Customise_Static_Mesh(class UStaticMesh* New_Static_Mesh, class UStaticMeshComponent* Static_Mesh_Component)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Customise Static Mesh");
ABP_Mast_C_Customise_Static_Mesh_Params params;
params.New_Static_Mesh = New_Static_Mesh;
params.Static_Mesh_Component = Static_Mesh_Component;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.Trim Array Func
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// TArray<class UObject*> TargetArray (Parm, OutParm, ZeroConstructor, ReferenceParm)
// int Size (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::Trim_Array_Func(TArray<class UObject*>* TargetArray, int Size)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Trim Array Func");
ABP_Mast_C_Trim_Array_Func_Params params;
params.Size = Size;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (TargetArray != nullptr)
*TargetArray = params.TargetArray;
}
// Function BP_Mast.BP_Mast_C.Initialise Sail Parameters
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::Initialise_Sail_Parameters()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Initialise Sail Parameters");
ABP_Mast_C_Initialise_Sail_Parameters_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.Populate Lists of Yards and Sails
// (Public, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::Populate_Lists_of_Yards_and_Sails()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Populate Lists of Yards and Sails");
ABP_Mast_C_Populate_Lists_of_Yards_and_Sails_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.Cull Excess Components
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// TArray<class UActorComponent*> TargetArray (Parm, OutParm, ZeroConstructor, ReferenceParm)
void ABP_Mast_C::Cull_Excess_Components(TArray<class UActorComponent*>* TargetArray)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Cull Excess Components");
ABP_Mast_C_Cull_Excess_Components_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (TargetArray != nullptr)
*TargetArray = params.TargetArray;
}
// Function BP_Mast.BP_Mast_C.Initialise Sails
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::Initialise_Sails()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Initialise Sails");
ABP_Mast_C_Initialise_Sails_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.UserConstructionScript");
ABP_Mast_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.OnMastDescLoaded
// (Event, Public, BlueprintEvent)
// Parameters:
// class UMastDescAsset* MastDesc (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::OnMastDescLoaded(class UMastDescAsset* MastDesc)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.OnMastDescLoaded");
ABP_Mast_C_OnMastDescLoaded_Params params;
params.MastDesc = MastDesc;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.OnMastMeshSwapRequested
// (Event, Protected, BlueprintEvent)
// Parameters:
// class UStaticMesh* NewMeshBottom (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class UStaticMesh* NewMeshTop (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::OnMastMeshSwapRequested(class UStaticMesh* NewMeshBottom, class UStaticMesh* NewMeshTop)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.OnMastMeshSwapRequested");
ABP_Mast_C_OnMastMeshSwapRequested_Params params;
params.NewMeshBottom = NewMeshBottom;
params.NewMeshTop = NewMeshTop;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature
// (BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> State (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<Repair_ERepairableState> PreviousState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class URepairableComponent* RepairableComponent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature(TEnumAsByte<Repair_ERepairableState> State, TEnumAsByte<Repair_ERepairableState> PreviousState, class URepairableComponent* RepairableComponent)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature");
ABP_Mast_C_BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature_Params params;
params.State = State;
params.PreviousState = PreviousState;
params.RepairableComponent = RepairableComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature
// (BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> State (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<Repair_ERepairableState> PreviousState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class URepairableComponent* RepairableComponent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature(TEnumAsByte<Repair_ERepairableState> State, TEnumAsByte<Repair_ERepairableState> PreviousState, class URepairableComponent* RepairableComponent)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature");
ABP_Mast_C_BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature_Params params;
params.State = State;
params.PreviousState = PreviousState;
params.RepairableComponent = RepairableComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature
// (BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> State (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<Repair_ERepairableState> PreviousState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class URepairableComponent* RepairableComponent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature(TEnumAsByte<Repair_ERepairableState> State, TEnumAsByte<Repair_ERepairableState> PreviousState, class URepairableComponent* RepairableComponent)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature");
ABP_Mast_C_BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature_Params params;
params.State = State;
params.PreviousState = PreviousState;
params.RepairableComponent = RepairableComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.ExecuteUbergraph_BP_Mast
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::ExecuteUbergraph_BP_Mast(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.ExecuteUbergraph_BP_Mast");
ABP_Mast_C_ExecuteUbergraph_BP_Mast_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void ABP_Mast_C::AfterRead()
{
AMast::AfterRead();
READ_PTR_FULL(MastTopComponent, UStaticMeshComponent);
READ_PTR_FULL(TopgallantActor, UChildActorComponent);
READ_PTR_FULL(MainsailActor, UChildActorComponent);
READ_PTR_FULL(TopsailActor, UChildActorComponent);
READ_PTR_FULL(Main_Yard, UStaticMeshComponent);
READ_PTR_FULL(Topgallant_Yard, UStaticMeshComponent);
READ_PTR_FULL(Top_Yard, UStaticMeshComponent);
READ_PTR_FULL(MastBaseComponent, UStaticMeshComponent);
READ_PTR_FULL(Sail_Material, UMaterialInstance);
READ_PTR_FULL(DamageDecalRight, UDecalComponent);
READ_PTR_FULL(DamageDecalLeft, UDecalComponent);
}
void ABP_Mast_C::BeforeDelete()
{
AMast::BeforeDelete();
DELE_PTR_FULL(MastTopComponent);
DELE_PTR_FULL(TopgallantActor);
DELE_PTR_FULL(MainsailActor);
DELE_PTR_FULL(TopsailActor);
DELE_PTR_FULL(Main_Yard);
DELE_PTR_FULL(Topgallant_Yard);
DELE_PTR_FULL(Top_Yard);
DELE_PTR_FULL(MastBaseComponent);
DELE_PTR_FULL(Sail_Material);
DELE_PTR_FULL(DamageDecalRight);
DELE_PTR_FULL(DamageDecalLeft);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 13,390
| 4,743
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from foo_client_interface.djinni
#pragma once
#include <atomic>
#include <experimental/optional>
#include "foo_some_other_record.hpp"
#ifdef __cplusplus
extern "C" {
#endif
#include "dh__foo_some_other_record.h"
#ifdef __cplusplus
}
#endif
struct DjinniFooSomeOtherRecord {
static djinni::Handle<DjinniRecordHandle> fromCpp(const ::testsuite::FooSomeOtherRecord& dr);
static ::testsuite::FooSomeOtherRecord toCpp(djinni::Handle<DjinniRecordHandle> dh);
static djinni::Handle<DjinniOptionalRecordHandle> fromCpp(std::experimental::optional<::testsuite::FooSomeOtherRecord> dc);
static std::experimental::optional<::testsuite::FooSomeOtherRecord> toCpp(djinni::Handle<DjinniOptionalRecordHandle> dh);
};
| 794
| 272
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
// TODO: test with more field types...
namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
std::cout << "Basis # " << basis << std::endl;
FieldInformation lfi("LatVolMesh", basis, "double");
size_type sizex = 2, sizey = 3, sizez = 4;
Point minb(-1.0, -1.0, -1.0);
Point maxb(1.0, 1.0, 1.0);
MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
FieldHandle ofh = CreateField(lfi,mesh);
ofh->vfield()->clear_all_values();
GetFieldBoundaryAlgo algo;
FieldHandle boundary;
MatrixHandle mapping;
algo.run(ofh, boundary, mapping);
ASSERT_TRUE(boundary.get() != nullptr);
/// @todo: need assertions on boundary field
if (basis != -1)
{
ASSERT_TRUE(mapping != nullptr);
EXPECT_EQ(expectedMatrixRows, mapping->nrows());
EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
EXPECT_EQ(expectedMatrixString, matrix_to_string(*convertMatrix::toDense(mapping)));
}
}
const std::string matrixCells =
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n";
const std::string matrixNodes =
"1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}
TEST(GetFieldBoundaryTest, LatVolBoundary)
{
runTest(0, 22, 6, matrixCells);
runTest(-1, 0, 0);
runTest(1, 24, 24, matrixNodes);
/*
EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
EXPECT_EQ(0, info.dataMin);
EXPECT_EQ(0, info.dataMax);
EXPECT_EQ(0, info.numdata_);
EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}
TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
GetFieldBoundaryAlgo algo;
FieldHandle input, output;
MatrixHandle mapping;
EXPECT_FALSE(algo.run(input, output, mapping));
EXPECT_FALSE(algo.run(input, output));
}
| 5,486
| 2,997
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_system_provider/throttled_file_system.h"
#include <stddef.h>
#include <memory>
#include <vector>
#include "base/files/file.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/file_system_provider/abort_callback.h"
#include "chrome/browser/chromeos/file_system_provider/fake_provided_file_system.h"
#include "chrome/browser/chromeos/file_system_provider/provided_file_system_info.h"
#include "chrome/common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace file_system_provider {
namespace {
const char kExtensionId[] = "mbflcebpggnecokmikipoihdbecnjfoj";
const char kFileSystemId[] = "camera-pictures";
const char kDisplayName[] = "Camera Pictures";
typedef std::vector<base::File::Error> StatusLog;
typedef std::vector<std::pair<int, base::File::Error>> OpenLog;
// Writes a |result| to the |log| vector for a status callback.
void LogStatus(StatusLog* log, base::File::Error result) {
log->push_back(result);
}
// Writes a |result| to the |log| vector for opening a file.
void LogOpen(OpenLog* log, int handle, base::File::Error result) {
log->push_back(std::make_pair(handle, result));
}
} // namespace
class FileSystemProviderThrottledFileSystemTest : public testing::Test {
protected:
FileSystemProviderThrottledFileSystemTest() {}
~FileSystemProviderThrottledFileSystemTest() override {}
void SetUp() override {}
// Initializes the throttled file system with |limit| number of opened files
// at once. If 0, then no limit.
void SetUpFileSystem(size_t limit) {
MountOptions options(kFileSystemId, kDisplayName);
options.opened_files_limit = limit;
ProvidedFileSystemInfo file_system_info(
kExtensionId, options, base::FilePath() /* mount_path */,
false /* configurable */, true /* watchable */,
extensions::SOURCE_FILE);
file_system_.reset(new ThrottledFileSystem(
base::WrapUnique(new FakeProvidedFileSystem(file_system_info))));
}
content::TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<ThrottledFileSystem> file_system_;
};
TEST_F(FileSystemProviderThrottledFileSystemTest, OpenFile_LimitedToOneAtOnce) {
SetUpFileSystem(1);
OpenLog first_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &first_open_log));
OpenLog second_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &second_open_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
EXPECT_EQ(0u, second_open_log.size());
// Close the first file.
StatusLog close_log;
file_system_->CloseFile(first_open_log[0].first,
base::Bind(&LogStatus, &close_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, close_log.size());
EXPECT_EQ(base::File::FILE_OK, close_log[0]);
// The second enqueued file should be opened.
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
ASSERT_EQ(1u, second_open_log.size());
EXPECT_EQ(base::File::FILE_OK, second_open_log[0].second);
}
TEST_F(FileSystemProviderThrottledFileSystemTest, OpenFile_NoLimit) {
SetUpFileSystem(0); // No limit.
OpenLog first_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &first_open_log));
OpenLog second_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &second_open_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
ASSERT_EQ(1u, second_open_log.size());
EXPECT_EQ(base::File::FILE_OK, second_open_log[0].second);
// Close files.
StatusLog first_close_log;
file_system_->CloseFile(first_open_log[0].first,
base::Bind(&LogStatus, &first_close_log));
StatusLog second_close_log;
file_system_->CloseFile(second_open_log[0].first,
base::Bind(&LogStatus, &second_close_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_close_log.size());
EXPECT_EQ(base::File::FILE_OK, first_close_log[0]);
ASSERT_EQ(1u, second_close_log.size());
EXPECT_EQ(base::File::FILE_OK, second_close_log[0]);
// Confirm, that files are not opened again.
EXPECT_EQ(1u, first_open_log.size());
EXPECT_EQ(1u, second_open_log.size());
}
TEST_F(FileSystemProviderThrottledFileSystemTest, AbortAfterRun) {
SetUpFileSystem(1);
OpenLog first_open_log;
AbortCallback abort_callback =
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &first_open_log));
OpenLog second_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &second_open_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
EXPECT_EQ(0u, second_open_log.size());
}
} // namespace file_system_provider
} // namespace chromeos
| 5,695
| 2,006
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/media/audio/audio_core/pipeline_config.h"
#include <gtest/gtest.h>
namespace media::audio {
namespace {
TEST(PipelineConfigTest, CalculateChannels) {
auto config = PipelineConfig::Default();
// No effects, the pipeline channelization is the same as the output of the root mix stage.
EXPECT_EQ(config.root().output_channels, config.channels());
// With rechannelization effects, the last effect defines the channelization.
config.mutable_root().effects.push_back(
{"lib.so", "effect", "e1", "", {config.root().output_channels + 1}});
config.mutable_root().effects.push_back(
{"lib.so", "effect", "e2", "", {config.root().output_channels + 2}});
EXPECT_EQ(config.root().output_channels + 2, config.channels());
}
} // namespace
} // namespace media::audio
| 967
| 315
|
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Trung Dac Nguyen (ORNL)
------------------------------------------------------------------------- */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "pair_beck_gpu.h"
#include "atom.h"
#include "atom_vec.h"
#include "comm.h"
#include "force.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "integrate.h"
#include "memory.h"
#include "error.h"
#include "neigh_request.h"
#include "universe.h"
#include "update.h"
#include "domain.h"
#include <string.h>
#include "gpu_extra.h"
#include "math_special.h"
using namespace LAMMPS_NS;
using namespace MathSpecial;
// External functions from cuda library for atom decomposition
int beck_gpu_init(const int ntypes, double **cutsq, double **host_aa,
double **alpha, double **beta, double **AA, double **BB,
double *special_lj, const int nlocal,
const int nall, const int max_nbors, const int maxspecial,
const double cell_size, int &gpu_mode, FILE *screen);
void beck_gpu_clear();
int ** beck_gpu_compute_n(const int ago, const int inum,
const int nall, double **host_x, int *host_type,
double *sublo, double *subhi, tagint *tag, int **nspecial,
tagint **special, const bool eflag, const bool vflag,
const bool eatom, const bool vatom, int &host_start,
int **ilist, int **jnum,
const double cpu_time, bool &success);
void beck_gpu_compute(const int ago, const int inum, const int nall,
double **host_x, int *host_type, int *ilist, int *numj,
int **firstneigh, const bool eflag, const bool vflag,
const bool eatom, const bool vatom, int &host_start,
const double cpu_time, bool &success);
double beck_gpu_bytes();
/* ---------------------------------------------------------------------- */
PairBeckGPU::PairBeckGPU(LAMMPS *lmp) : PairBeck(lmp), gpu_mode(GPU_FORCE)
{
respa_enable = 0;
reinitflag = 0;
cpu_time = 0.0;
GPU_EXTRA::gpu_ready(lmp->modify, lmp->error);
}
/* ----------------------------------------------------------------------
free all arrays
------------------------------------------------------------------------- */
PairBeckGPU::~PairBeckGPU()
{
beck_gpu_clear();
}
/* ---------------------------------------------------------------------- */
void PairBeckGPU::compute(int eflag, int vflag)
{
if (eflag || vflag) ev_setup(eflag,vflag);
else evflag = vflag_fdotr = 0;
int nall = atom->nlocal + atom->nghost;
int inum, host_start;
bool success = true;
int *ilist, *numneigh, **firstneigh;
if (gpu_mode != GPU_FORCE) {
inum = atom->nlocal;
firstneigh = beck_gpu_compute_n(neighbor->ago, inum, nall,
atom->x, atom->type, domain->sublo,
domain->subhi, atom->tag, atom->nspecial,
atom->special, eflag, vflag, eflag_atom,
vflag_atom, host_start,
&ilist, &numneigh, cpu_time, success);
} else {
inum = list->inum;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
beck_gpu_compute(neighbor->ago, inum, nall, atom->x, atom->type,
ilist, numneigh, firstneigh, eflag, vflag, eflag_atom,
vflag_atom, host_start, cpu_time, success);
}
if (!success)
error->one(FLERR,"Insufficient memory on accelerator");
if (host_start<inum) {
cpu_time = MPI_Wtime();
cpu_compute(host_start, inum, eflag, vflag, ilist, numneigh, firstneigh);
cpu_time = MPI_Wtime() - cpu_time;
}
}
/* ----------------------------------------------------------------------
init specific to this pair style
------------------------------------------------------------------------- */
void PairBeckGPU::init_style()
{
if (force->newton_pair)
error->all(FLERR,"Cannot use newton pair with beck/gpu pair style");
// Repeat cutsq calculation because done after call to init_style
double maxcut = -1.0;
double cut;
for (int i = 1; i <= atom->ntypes; i++) {
for (int j = i; j <= atom->ntypes; j++) {
if (setflag[i][j] != 0 || (setflag[i][i] != 0 && setflag[j][j] != 0)) {
cut = init_one(i,j);
cut *= cut;
if (cut > maxcut)
maxcut = cut;
cutsq[i][j] = cutsq[j][i] = cut;
} else
cutsq[i][j] = cutsq[j][i] = 0.0;
}
}
double cell_size = sqrt(maxcut) + neighbor->skin;
int maxspecial=0;
if (atom->molecular)
maxspecial=atom->maxspecial;
int success = beck_gpu_init(atom->ntypes+1, cutsq, aa, alpha, beta,
AA, BB, force->special_lj, atom->nlocal,
atom->nlocal+atom->nghost, 300, maxspecial,
cell_size, gpu_mode, screen);
GPU_EXTRA::check_flag(success,error,world);
if (gpu_mode == GPU_FORCE) {
int irequest = neighbor->request(this,instance_me);
neighbor->requests[irequest]->half = 0;
neighbor->requests[irequest]->full = 1;
}
}
/* ---------------------------------------------------------------------- */
double PairBeckGPU::memory_usage()
{
double bytes = Pair::memory_usage();
return bytes + beck_gpu_bytes();
}
/* ---------------------------------------------------------------------- */
void PairBeckGPU::cpu_compute(int start, int inum, int eflag, int vflag,
int *ilist, int *numneigh, int **firstneigh) {
int i,j,ii,jj,jnum,itype,jtype;
double xtmp,ytmp,ztmp,delx,dely,delz,evdwl,fpair;
double rsq,r5,force_beck,factor_lj;
double r,rinv;
double aaij,alphaij,betaij;
double term1,term1inv,term2,term3,term4,term5,term6;
int *jlist;
double **x = atom->x;
double **f = atom->f;
int *type = atom->type;
double *special_lj = force->special_lj;
// loop over neighbors of my atoms
for (ii = start; ii < inum; ii++) {
i = ilist[ii];
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_lj = special_lj[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
r = sqrt(rsq);
r5 = rsq*rsq*r;
aaij = aa[itype][jtype];
alphaij = alpha[itype][jtype];
betaij = beta[itype][jtype];
term1 = aaij*aaij + rsq;
term2 = powint(term1,-5);
term3 = 21.672 + 30.0*aaij*aaij + 6.0*rsq;
term4 = alphaij + r5*betaij;
term5 = alphaij + 6.0*r5*betaij;
rinv = 1.0/r;
force_beck = AA[itype][jtype]*exp(-1.0*r*term4)*term5;
force_beck -= BB[itype][jtype]*r*term2*term3;
fpair = factor_lj*force_beck*rinv;
f[i][0] += delx*fpair;
f[i][1] += dely*fpair;
f[i][2] += delz*fpair;
if (eflag) {
term6 = powint(term1,-3);
term1inv = 1.0/term1;
evdwl = AA[itype][jtype]*exp(-1.0*r*term4);
evdwl -= BB[itype][jtype]*term6*(1.0+(2.709+3.0*aaij*aaij)*term1inv);
evdwl *= factor_lj;
}
if (evflag) ev_tally_full(i,evdwl,0.0,fpair,delx,dely,delz);
}
}
}
}
| 8,272
| 2,871
|
/* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
#include "../../../include/pl/compiler.hpp"
#if PL_COMPILER == PL_COMPILER_GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#endif // PL_COMPILER == PL_COMPILER_GCC
#include "../../doctest.h"
#if PL_COMPILER == PL_COMPILER_GCC
#pragma GCC diagnostic pop
#endif // PL_COMPILER == PL_COMPILER_GCC
#include "../../../include/pl/thd/monitor.hpp" // pl::thd::monitor
#include <cstring> // std::strcmp
#include <string> // std::string
#include <utility> // std::move
namespace pl {
namespace test {
namespace {
class monitor_test_type {
public:
using this_type = monitor_test_type;
monitor_test_type(int i, double d, std::string s)
: m_i{i}, m_d{d}, m_s{std::move(s)}
{
}
double d() const noexcept
{
return m_d;
}
void d(double d) noexcept
{
m_d = d;
}
void set_d_to_25() noexcept
{
d(25.0);
}
const char* str() const noexcept
{
return m_s.data();
}
int m_i;
private:
double m_d;
std::string m_s;
};
} // anonymous namespace
} // namespace test
} // namespace pl
TEST_CASE("monitor_test")
{
pl::thd::monitor<pl::test::monitor_test_type> monitor{
pl::test::monitor_test_type{1, 2.0, "text"}};
CHECK(
monitor([](pl::test::monitor_test_type& o) { return o.d(); })
== doctest::Approx{2.0});
monitor(&pl::test::monitor_test_type::set_d_to_25);
CHECK(
monitor(static_cast<double (pl::test::monitor_test_type::*)() const>(
&pl::test::monitor_test_type::d))
== doctest::Approx{25.0});
CHECK(std::strcmp(monitor(&pl::test::monitor_test_type::str), "text") == 0);
CHECK(monitor(&pl::test::monitor_test_type::m_i) == 1);
}
| 3,157
| 1,096
|
// DLLDemo.cpp : Defines the entry point for the DLL application.
//
#include "sense4.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "common.h"
#include "..\inc\sample_26.h"
#include "DLLDemo.h"
/* global variables definition */
SENSE4_CONTEXT stS4Ctx = {0};
unsigned long dwBytesReturned = 0;
IO_PACKAGE stDataPkgIn = {0};
IO_PACKAGE stDataPkgOut = {0};
#define S4_EXE_FILE_1 "f001"
#define S4_EXE_FILE_2 "f002"
int enc_dec_ecb(int id, unsigned char cmd, unsigned char *in, unsigned char inlen,
unsigned char *out, unsigned char *outlen)
{
unsigned long dwResult = S4_SUCCESS;
assert(NULL != out && NULL != outlen && NULL != in);
assert(cmd == DES_ENC_ECB || cmd == DES_DEC_ECB || cmd == TDES_ENC_ECB || cmd == TDES_DEC_ECB);
stDataPkgIn.tag = cmd;
stDataPkgIn.len = inlen;
memcpy(stDataPkgIn.buff, in, inlen);
//printf("id=%d\n",id);
if (id == 1) {
dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_1, &stDataPkgIn,
IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
//printf("%s\n",S4_EXE_FILE_1);
} else if (id == 2){
dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_2, &stDataPkgIn,
IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
//printf("%s\n",S4_EXE_FILE_2);
}
if (dwResult != S4_SUCCESS)
{
return S4_ERROR_INVALID_DATA;
}
if (*outlen < stDataPkgOut.len)
{
return S4_ERROR_OUT_BUFFER;
}
*outlen = stDataPkgOut.len;
memcpy(out,stDataPkgOut.buff,stDataPkgOut.len);
return S4_SUCCESS;
}
int enc_dec_cbc(unsigned char cmd, unsigned char *iv, unsigned char *in, unsigned char inlen,
unsigned char *out, unsigned char *outlen)
{
unsigned long dwResult = S4_SUCCESS;
DATA_BLOCK stDataBlk = {0};
assert(NULL != out && NULL != outlen && NULL != in && iv != NULL);
assert(cmd == DES_ENC_CBC || cmd == DES_DEC_CBC || cmd == TDES_ENC_CBC || cmd == TDES_DEC_CBC);
if (inlen > MAX_DATA_BLOCK_LEN)
{
return S4_ERROR_INPUT_TOO_LONG;
}
memcpy(stDataBlk.iv, iv, sizeof(stDataBlk.iv));
stDataBlk.len = inlen;
memcpy(stDataBlk.buff, in, inlen);
stDataPkgIn.tag = cmd;
stDataPkgIn.len = sizeof(stDataBlk) - sizeof(stDataBlk.buff) + stDataBlk.len;
memcpy(stDataPkgIn.buff, &stDataBlk, stDataPkgIn.len);
dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_1, &stDataPkgIn,
IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
if (dwResult != S4_SUCCESS)
{
return dwResult;
}
if (*outlen < stDataPkgOut.len)
{
return S4_ERROR_INSUFFICIENT_BUFFER;
}
*outlen = stDataPkgOut.len;
memcpy(out,stDataPkgOut.buff,stDataPkgOut.len);
return S4_SUCCESS;
}
extern "C" _declspec(dllexport) unsigned long TestEIV(unsigned char * buff)
{
SENSE4_CONTEXT ctx = {0};
SENSE4_CONTEXT *pctx = NULL;
unsigned long size = 0;
unsigned long ret = 0;
S4Enum(pctx, &size);
if (size == 0)
{
//printf("EliteIV not found!\n");
return 111;
}
pctx = (SENSE4_CONTEXT *)malloc(size);
if (pctx == NULL)
{
//printf("Not enough memory!\n");
return 222;
}
ret = S4Enum(pctx, &size);
if (ret != S4_SUCCESS)
{
//printf("Enumerate EliteIV error!\n");
free(pctx);
return ret;
}
memcpy(&ctx, pctx, sizeof(SENSE4_CONTEXT));
free(pctx);
pctx = NULL;
ret = S4Open(&ctx);
if (ret != S4_SUCCESS)
{
//printf("Open EliteIV failed!\n");
return ret;
}
ret = S4ChangeDir(&ctx, "\\");
if (ret != S4_SUCCESS)
{
//printf("No root directory found!\n");
S4Close(&ctx);
return ret;
}
ret = S4VerifyPin(&ctx, (unsigned char *)"12345678", 8, S4_USER_PIN);
if (ret != S4_SUCCESS)
{
//printf("Verify user PIN failed!\n");
S4Close(&ctx);
return ret;
}
ret = S4Execute(&ctx, "0001", buff, 10, buff, 10, &size);
if (ret != S4_SUCCESS)
{
//printf("Execute EliteIV exe failed!\n");
S4Close(&ctx);
return ret;
}
S4Close(&ctx);
return 0;
}
extern "C" _declspec(dllexport) int crypto(
int type, /* 0=encryptpgraphy, 1=decryptography */
unsigned char fromText[],
unsigned char toText[]
)
/*extern "C" __declspec(dllexport) int crypto(int type,
unsigned char fromText[],
unsigned char toText[]
)*/
{
unsigned long dwResult = S4_SUCCESS;
unsigned char lpUserPin[] = USERPEN;
unsigned char TextLen = BUFFERLENGTH;
unsigned char tmp;
//printf("call crypto\n");
if (!(dwResult = OpenS4ByIndex(FIRST_S4_INDEX,&stS4Ctx)))
{
return S4_ERROR_DEVICE;
}
dwResult = S4ChangeDir(&stS4Ctx, "\\");
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
// Call S4VerifyPin(...) to verify User PIN so as to get the privilege to execute the program in EliteIV.
dwResult = S4VerifyPin(&stS4Ctx, lpUserPin, strlen((LPCSTR)lpUserPin), S4_USER_PIN);
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
if(type == 0){
if (dwResult = enc_dec_ecb(1, TDES_ENC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
else {
if (dwResult = enc_dec_ecb(1, TDES_DEC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
/* for better security,use the following instead of using S4close() directly */
ResetAndCloseS4(&stS4Ctx);
return S4_SUCCESS;
}
extern "C" _declspec(dllexport) int crypto2(
int type, /* 0=encryptpgraphy, 1=decryptography */
unsigned char fromText[],
unsigned char toText[]
)
/*extern "C" __declspec(dllexport) int crypto(int type,
unsigned char fromText[],
unsigned char toText[]
)*/
{
unsigned long dwResult = S4_SUCCESS;
unsigned char lpUserPin[] = USERPEN;
unsigned char TextLen = BUFFERLENGTH;
unsigned char tmp;
//printf("call crypto2\n");
if (!(dwResult = OpenS4ByIndex(FIRST_S4_INDEX,&stS4Ctx)))
{
return S4_ERROR_DEVICE;
}
dwResult = S4ChangeDir(&stS4Ctx, "\\");
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
// Call S4VerifyPin(...) to verify User PIN so as to get the privilege to execute the program in EliteIV.
dwResult = S4VerifyPin(&stS4Ctx, lpUserPin, strlen((LPCSTR)lpUserPin), S4_USER_PIN);
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
if(type == 0){
if (dwResult = enc_dec_ecb(2, TDES_ENC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
else {
if (dwResult = enc_dec_ecb(2, TDES_DEC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
/* for better security,use the following instead of using S4close() directly */
ResetAndCloseS4(&stS4Ctx);
return S4_SUCCESS;
}
char char2hex(char c)
{
if (c < 0x0A) {
return c + 0x30;
}
else if (c >= 0x0A && c <= 0x0F) {
return c + 0x41 - 0x0A;
}
else {
return 'x';
}
}
/* using crypto2() encrypt random pass from server */
extern "C" _declspec(dllexport) int encryptrand(
unsigned char random[], /* 16 byte chars like: dasf98723478fd7a */
unsigned char encrypt_hex[] /* 32 byte hex chars like: 00010203040506070809f0f1f2f3f4f5 */
)
{
int i;
char a, b;
unsigned char encrypt[200];
unsigned long dwResult;
memset(encrypt, 0, 200);
dwResult = crypto2(0, random, encrypt);
for (i=0; i<16; i++){
a = (encrypt[i] & 0xF0) >> 4;
b = encrypt[i] & 0x0F;
encrypt_hex[2 * i] = char2hex(a);
encrypt_hex[2 * i + 1] = char2hex(b);
}
return dwResult;
}
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
| 7,886
| 3,593
|
/******************************************************************************/
/* */
/* Unit Name : atmos.cpp */
/* */
/* Abstract : Calculates atmosphere at the current altitude */
/* */
/* Naming Conventions : */
/* */
/* Public Functions : Mixed case with no underscores */
/* Private Functions : Mixed case with no underscores */
/* Public Functions : Mixed case with no underscores */
/* Global Variables : Mixed case with no underscores */
/* Classless Functions : Mixed case with no underscores */
/* Classes : All upper case seperated by an underscore */
/* Defined Constants : All upper case seperated by an underscore */
/* Macros : All upper case seperated by an underscore */
/* Structs/Types : All upper case seperated by an underscore */
/* Private Variables : All lower case seperated by an underscore */
/* Public Variables : All lower case seperated by an underscore */
/* Local Variables : All lower case seperated by an underscore */
/* */
/* Development History : */
/* Date Programer Description */
/*----------------------------------------------------------------------------*/
/* 23-Jan-95 LR Initial Write */
/* */
/******************************************************************************/
#include "stdhdr.h"
#include "airframe.h"
#include "simdrive.h"
#include "ffeedbk.h"
#include "Graphics/Include/drawsgmt.h"
static float lastqBar = 0; // Note: This limits us to 1 ownship/Force feedback stick per machine
static const float tropoAlt = 36089.0F, tropoAlt2 = 65617;
extern bool g_bFFCenterFix;
/********************************************************************/
/* */
/* Routine: void AirframeClass::Atmosphere(void) */
/* */
/* Description: */
/* Calculates current state included pressure, mach, qbar and */
/* qsom for normalizing. */
/* */
/* Inputs: */
/* None */
/* */
/* Outputs: */
/* None */
/* */
/* Development History : */
/* Date Programer Description */
/*------------------------------------------------------------------*/
/* 23-Jan-95 LR Initial Write */
/* */
/********************************************************************/
void AirframeClass::Atmosphere(void)
{
float ttheta, rsigma;
float pdelta, sound;
float qpasl1, oper, pa, qc;
pdelta = CalcPressureRatio(-z, &ttheta, &rsigma);
sound = (float)sqrt(ttheta) * AASL;
rho = rsigma * RHOASL;
pa = pdelta * PASL;
if (IsSet(Trimming))
{
if (mach > 3.0)
//vt = CalcMach(mach, pdelta) * sound;
vt = mach * KNOTS_TO_FTPSEC;
else
vt = mach * sound;
}
/*----------------------------*/
/* calculate dynamic pressure */
/*----------------------------*/
mach = vt / ((float)sqrt(ttheta) * AASL);//ME123 CALCULATE A TRUE MACH...NOT JUST VT/SPEEDOFSOUND
if (fabs(vt) > 1.0F)
{
qbar = 0.5F * rho * vt * vt;
/*-------------------------------*/
/* calculate calibrated airspeed */
/*-------------------------------*/
if (mach <= 1.0F)
qc = ((float)pow((1.0F + 0.2F * mach * mach), 3.5F) - 1.0F) * pa;
else
qc = ((166.9F * mach * mach) / (float)(pow((7.0F - 1.0F / (mach * mach)), 2.5F)) - 1.0F) * pa;
qpasl1 = qc / PASL + 1.0F;
vcas = 1479.12F * (float)sqrt(pow(qpasl1, 0.285714F) - 1.0F);
if (qc > 1889.64F)
{
oper = qpasl1 * (float)pow((7.0F - AASLK * AASLK / (vcas * vcas)), 2.5F);
if (oper < 0.0F) oper = 0.1F;
vcas = 51.1987F * (float)sqrt(oper);
}
/*------------------------*/
/* normalizing parameters */
/*------------------------*/
qsom = qbar * area / mass;
qovt = qbar / vt;
}
else
{
vcas = max(vt * FTPSEC_TO_KNOTS, 0.001F);
qsom = 0.1F;
qovt = 0.1F;
qbar = 0.001F;
mach = 0.001F;
}
//Wombat778 12-02-2003 Removed
/*
if (platform == SimDriver.GetPlayerEntity())
{
if (g_bFFCenterFix) JoystickPlayEffect (JoyAutoCenter, 20000); //Wombat778 11-26-2003 Changed method of FFCenterfix. Added because of some reports that centering cuts out after an effect is played
{
if (qbar < 250)
{
if (fabs (qbar - lastqBar) > 5.0F)
{
if ( not g_bFFCenterFix) //Wombat778 9-29-2003 Allows user to have the fixed centering force for FF sticks
JoystickPlayEffect (JoyAutoCenter, FloatToInt32((qbar/250.0F * 0.5F + 0.5F) * 10000.0F));
//lastqBar = qbar; // JB 010301 FF would cut out < 250
}
lastqBar = qbar; // JB 010301 FF would cut out < 250
}
else
{
if (fabs (qbar - lastqBar) > 5.0F)
if ( not g_bFFCenterFix) //Wombat778 9-29-2003 Allows user to have the fixed centering force for FF sticks
JoystickPlayEffect (JoyAutoCenter, 10000);
lastqBar = qbar;
}
}
}*/
//Wombat778 12-02-2003 redid this section to be tighter. Also, this should fix centering properly. g_bFFCenterFix now means that a constant instead of variable FF force is used
if (platform == SimDriver.GetPlayerAircraft())
{
if ((fabs(qbar - lastqBar) > 5.0F) or not lastqBar)
{
if ((qbar > 250) or g_bFFCenterFix)
{
JoystickPlayEffect(JoyAutoCenter, 10000);
}
else
{
JoystickPlayEffect(JoyAutoCenter, FloatToInt32((qbar / 250.0F * 0.5F + 0.5F) * 10000.0F));
}
lastqBar = qbar;
}
}
}
float AirframeClass::CalcTASfromCAS(float cas)
{
float ttheta, rsigma;
float sound, pdelta, desMach;
pdelta = CalcPressureRatio(-z, &ttheta, &rsigma);
desMach = CalcMach(cas, pdelta);
sound = (float)sqrt(ttheta) * AASL;
return desMach * sound * 3600.0F / 6080.0F;
}
float AirframeClass::CalcMach(float GetKias, float press_ratio)
{
float a0 = 661.4785F;
float kiasa, qcp0, qcpa;
float u, fu, fpu;
kiasa = GetKias / a0;
qcp0 = (float)pow((1.0 + 0.2 * kiasa * kiasa), 3.5) - 1.0F;
if (kiasa >= 1.0)
qcp0 = 166.921F * (float)pow(kiasa, 7.0F) / (float)pow((7.0F * kiasa * kiasa - 1.0F), 2.5F) - 1.0F;
qcpa = qcp0 / press_ratio;
if (qcpa >= 0.892929F)
{
u = 2.0F;
do
{
fu = 166.921F * (float)pow(u, 7.0F) / (float)pow((7.0F * u * u - 1.0F), 2.5F) - (1.0F + qcpa);
fpu = 7.0F * 166.921F * (float)pow(u, 6.0F) * (2.0F * u * u - 1.0F) / (float)pow((7.0F * u * u - 1.0F), 3.5F);
u -= fu / fpu;
}
while (fabs(fu) > 0.001F);
return (u);
}
else
{
return ((float)sqrt((pow((qcpa + 1.0F), (1.0F / 3.5F)) - 1.0F) / 0.2F));
}
}
float AirframeClass::CalcPressureRatio(float alt, float* ttheta, float* rsigma)
{
/*-----------------------------------------------*/
/* calculate temperature ratio and density ratio */
/*-----------------------------------------------*/
if (alt <= tropoAlt)
{
*ttheta = 1.0F - 0.000006875F * alt;
*rsigma = (float)pow(*ttheta, 4.255876F);
}
else if (alt < tropoAlt2)
{
*ttheta = 0.751865F;
*rsigma = 0.297076F * (float)exp(0.00004806 * (tropoAlt - alt));
}
else
{
*ttheta = 0.682457f + alt / 945374.0f;
*rsigma = (float)pow(0.978261 + alt / 659515.0, -35.16319);
}
return (*ttheta) * (*rsigma);
}
// sort of atmospheric
float AirframeClass::EngineSmokeFactor()
{
switch (auxaeroData->engineSmokes)
{
default:
return 2;
case 1: // vortex
case 0: // nothing
return 1;
case 2: // light smoke
return 2;
case 3:
return 4;
}
}
int AirframeClass::EngineTrail()
{
switch (auxaeroData->engineSmokes)
{
case 0: // nothing
return -1;
case 1: // vortex
return TRAIL_VORTEX;
case 2: // light smoke
return TRAIL_SMOKE;
case 3:
return TRAIL_DARKSMOKE;
default:
/*if (auxaeroData->engineSmokes > 3 and auxaeroData->engineSmokes - 3 < TRAIL_MAX)
return auxaeroData->engineSmokes - 3;*/
if (auxaeroData->engineSmokes > 3)
return auxaeroData->engineSmokes;//Cobra Allow for more engine trails
else return -1;
}
}
| 10,360
| 3,392
|
#include "wmpch.h"
#include "World.h"
namespace InGame {
float World::s_LimitTurnTime = 0;
int World::s_LimitSuddenDeathTurn = 0;
int World::s_CurrentTurn = 0;
World::World(const InitiateData& initData)
{
s_LimitSuddenDeathTurn = initData.LimitSuddenDeathTurn;
s_LimitTurnTime = initData.LimitTurnTime;
s_CurrentTurn = 0;
//Create Entity
m_ID = Gear::EntitySystem::CreateEntity(true, "World");
//Attach Component
Gear::EntitySystem::AttachComponent(m_ID, {
Gear::ComponentID::FSM, Gear::ComponentID::Status, Gear::ComponentID::Timer,
Gear::ComponentID::LateDrawer
});
//Set Component specific
Gear::EntitySystem::SetFSM(m_ID, {
{ WorldState::InGameStart, new InGemeStartHandler }, { WorldState::OnStart, new WorldOnStartHandler },
{ WorldState::OnPrepareRun, new WorldOnPrepareRunHandler }, { WorldState::OnRunning, new WorldOnRunningHandler},
{ WorldState::OnQuitWindow, new WorldOnQuitWindowHandler}, {WorldState::OnWaiting, new WorldOnWaitingHandler },
{ WorldState::OnGameVictory, new WorldOnVictoryHandler }, { WorldState::OnGameDraw, new WorldOnDrawHandler },
{WorldState::OnGameEnd, new WorldOnGameEndHandler }
});
Gear::EntitySystem::GetFSM(m_ID)->SetCurrentState(WorldState::InGameStart);
Gear::EntitySystem::SetStatus(m_ID, {
{ WorldInfo::CurrentWormName, std::string("") }, { WorldInfo::CurrentWormID, -1},
{ WorldInfo::DyeInfo, std::stack<int>()},
{ WorldInfo::CurrnetTeam, std::string("") }, { WorldInfo::CurrentTeamColor, TeamColor::Blue },
{ WorldInfo::TeamInfo, initData.Teams }, { WorldInfo::TeamInfoBlink, false }
});
Gear::EntitySystem::SetStatusHanlder(m_ID, {
{ WorldStatusHandleType::DisplayWaitingCount, Gear::CreateRef<WorldDisplayWaitingCountHandler>() },
{ WorldStatusHandleType::DisplayTeamInfo, Gear::CreateRef<WorldDisplayTeamInfoHandler>() },
{ WorldStatusHandleType::DisplayMassage, Gear::CreateRef<WorldDisplayMasageHandler>() },
});
auto status = Gear::EntitySystem::GetStatus(m_ID);
status->PushNeedHandleData(WorldStatusHandleType::DisplayTeamInfo,
Gear::Status::StatHandleData(WorldTeamInfoDenoteData(Gear::TextureStorage::GetTexture2D("WormNameBorder"))));
auto lateDrawer = Gear::EntitySystem::GetLateDrawer(m_ID);
glm::mat4 fogTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 1.0f)) * glm::scale(glm::mat4(1.0f), glm::vec3(1000.0f, 1000.0f, 1.0f));
lateDrawer->UpLoadDrawStuff("Fog", Gear::LateDrawer::QuardStuff(fogTranslate, glm::vec4(0.0f, 0.0f, 0.001f, 1.0f)));
//Subscpribe EventChannel
//Gear::EventSystem::SubscribeChannel(m_ID, EventChannel::MouseClick);
Gear::EventSystem::SubscribeChannel(m_ID, EventChannel::World);
Gear::EventSystem::RegisterEventHandler(m_ID, EventChannel::World, Gear::CreateRef<WorldEventHandler>());
bgms.push_back("ingame-01-generic");
bgms.push_back("ingame-02-cavern");
bgms.push_back("ingame-03-jungle");
bgms.push_back("ingame-04-battlezone");
bgms.push_back("ingame-05-forest");
bgms.push_back("ingame-06-weird-alien-plan");
bgms.push_back("ingame-07-outerspace");
bgms.push_back("ingame-08-desert");
bgms.push_back("ingame-09-hell");
bgms.push_back("ingame-10-mech-workshop");
bgms.push_back("ingame-11-rain&surf");
}
World::~World()
{
Gear::EventSystem::UnSubscribeChannel(m_ID, EventChannel::MouseClick);
Gear::EntitySystem::DeleteEntity(m_ID);
}
void World::Update(Gear::Timestep ts)
{
if (!IS_PLAYING_SOUND(WormsSound::bgm) && !IS_PLAYING_SOUND(WormsSound::Hos))
{
PLAY_SOUND_NAME(bgms[Gear::Util::GetRndInt(11)], WormsSound::bgm);
Gear::SoundSystem::Get()->SetVolue(WormsSound::bgm, 0.5f);
}
}
}
| 3,661
| 1,474
|
/*****************************************************************************
FilterBank.cpp
Author: Laurent de Soras, 2017
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/def.h"
#include "mfx/dsp/iir/DesignEq2p.h"
#include "mfx/dsp/iir/TransSZBilin.h"
#include "mfx/dsp/mix/Fpu.h"
#include "mfx/pi/nzbl/FilterBank.h"
#include <algorithm>
#include <cassert>
#include <cmath>
namespace mfx
{
namespace pi
{
namespace nzbl
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
// Does not compute the latency if latency < 0 as input
void FilterBank::reset (double sample_freq, int max_buf_len, double &latency)
{
assert (sample_freq > 0);
assert (max_buf_len > 0);
fstb::unused (max_buf_len);
const bool lat_flag = (latency >= 0);
latency = 0;
_sample_freq = float ( sample_freq);
_inv_fs = float (1 / sample_freq);
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
Band & band = _band_arr [band_cnt];
band._env.set_sample_freq (sample_freq);
// Computes the envelope times.
// For the lowest band, we use 30 Hz as reference to make sure that the
// lowest frequencies are not distorded. Consequently, the gate will be
// slow to react. But low frequency rumble is generally steady (it comes
// from the power supply) therefore this is not a problem.
float f = 30;
if (band_cnt > 0)
{
f = compute_split_freq (band_cnt - 1);
}
const int mult = 16;
float t = float (mult / (2 * fstb::PI)) / f;
// Longer release helps preventing amplitude modulation on periodic
// noise bursts
const float min_at = 0.005f;
const float min_rt = 0.050f;
const float at = std::max (t, min_at);
const float rt = std::max (t, min_rt);
band._env.set_times (at, rt);
}
constexpr float k = 0.65f; // Thiele coefficient
const float alpha = float (sqrt (2 * (1 - k * k)));
static const float as [3] = { 1, alpha, 1 }; // Shared poles
static const float bls [_nbr_stages] [3] = { { 1, 0, 0 }, { 1, 0, k } };
static const float bhs [_nbr_stages] [3] = { { 0, 0, 1 }, { k, 0, 1 } };
for (int split_cnt = 0; split_cnt < _nbr_split; ++split_cnt)
{
Split & split = _split_arr [split_cnt];
const float f0 = compute_split_freq (split_cnt);
const float kf =
mfx::dsp::iir::TransSZBilin::compute_k_approx (f0 * _inv_fs);
for (int stage = 0; stage < _nbr_stages; ++stage)
{
float bz [3];
float az [3];
// LP
mfx::dsp::iir::TransSZBilin::map_s_to_z_approx (
bz, az, bls [stage], as, kf
);
split._lpf [stage].set_z_eq (bz, az);
split._fix [stage].set_z_eq (bz, az);
// HP
mfx::dsp::iir::TransSZBilin::map_s_to_z_approx (
bz, az, bhs [stage], as, kf
);
split._hpf [stage].set_z_eq (bz, az);
// Evaluates the group delay
if (lat_flag)
{
// Base frequency for latency evaluation. Hz
constexpr double f_lat = 700;
// Uses the HPs or LPs depending on the tested frequency
if (f0 < f_lat)
{
split._hpf [stage].get_z_eq (bz, az);
}
else
{
split._lpf [stage].get_z_eq (bz, az);
}
az [0] = 1;
const double gd = mfx::dsp::iir::DesignEq2p::compute_group_delay (
bz, az, sample_freq, f_lat
);
latency += gd;
}
}
}
clear_buffers ();
}
// thr is a linear value
void FilterBank::set_threshold (int band_idx, float thr)
{
assert (band_idx >= 0);
assert (band_idx < _nbr_bands);
assert (thr >= 0);
_band_arr [band_idx]._thr = thr;
}
// Can work in-place
void FilterBank::process_block (float dst_ptr [], const float src_ptr [], int nbr_spl)
{
assert (_sample_freq > 0);
assert (dst_ptr != nullptr);
assert (src_ptr != nullptr);
assert (nbr_spl > 0);
assert (nbr_spl <= _max_blk_size);
// Splits the signal in several bands
for (int split_idx = 0; split_idx < _nbr_split; ++split_idx)
{
Split & split = _split_arr [split_idx];
// The lower part goes to the current band, and the higher part
// propagates to the next band
float * lo_ptr = _band_arr [split_idx ]._buf.data ();
float * hi_ptr = _band_arr [split_idx + 1]._buf.data ();
split._hpf [0].process_block (hi_ptr, src_ptr, nbr_spl);
split._hpf [1].process_block (hi_ptr, hi_ptr, nbr_spl);
split._lpf [0].process_block (lo_ptr, src_ptr, nbr_spl);
split._lpf [1].process_block (lo_ptr, lo_ptr, nbr_spl);
// Next bands will be filtered in-place.
src_ptr = hi_ptr;
}
// Band processing
// Divides the current block in almost equal sub-blocks, fitting in
// the maximum processing length.
const int nbr_sub_blocks = (nbr_spl + _dspl_rate - 1) >> _dspl_rate_l2;
const int sub_block_len = (nbr_spl + nbr_sub_blocks - 1) / nbr_sub_blocks;
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
process_band (band_cnt, nbr_spl, sub_block_len);
}
// Band merging
for (int split_idx = 1; split_idx < _nbr_split; ++split_idx)
{
Split & split = _split_arr [split_idx];
float * prv_ptr = _band_arr [split_idx - 1]._buf.data ();
float * cur_ptr = _band_arr [split_idx ]._buf.data ();
split._fix [0].process_block (prv_ptr, prv_ptr, nbr_spl);
split._fix [1].process_block (prv_ptr, prv_ptr, nbr_spl);
mfx::dsp::mix::Fpu::mix_1_1 (cur_ptr, prv_ptr, nbr_spl);
}
// The last two bands don't need compensation processing
mfx::dsp::mix::Fpu::copy_2_1 (
dst_ptr,
_band_arr [_nbr_bands - 2]._buf.data (),
_band_arr [_nbr_bands - 1]._buf.data (),
nbr_spl
);
}
void FilterBank::clear_buffers ()
{
for (int split_cnt = 0; split_cnt < _nbr_split; ++split_cnt)
{
Split & split = _split_arr [split_cnt];
for (int stage = 0; stage < _nbr_stages; ++stage)
{
split._lpf [stage].clear_buffers ();
split._hpf [stage].clear_buffers ();
split._fix [stage].clear_buffers ();
}
}
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
Band & band = _band_arr [band_cnt];
band._env.clear_buffers ();
}
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*
Other possible formula for the gain shape:
x = (limit (env / thr, 1, _thr_hi_rel) - 1) / (_thr_hi_rel - 1)
g = 0.5 * ((1 - (1 - x) ^ 8) ^ 2 + (1 - (1 - x) ^ 3) ^ 2)
No div, but 1 / thr must be precalculated too
*/
void FilterBank::process_band (int band_idx, int nbr_spl, int sub_block_len)
{
assert (band_idx >= 0);
assert (band_idx < _nbr_bands);
assert (nbr_spl > 0);
assert (nbr_spl <= _max_blk_size);
assert (sub_block_len > 0);
assert (sub_block_len <= nbr_spl);
Band & band = _band_arr [band_idx];
if (band._thr >= 1e-9f)
{
float * buf_ptr = band._buf.data ();
const float thr = band._thr;
int block_pos = 0;
do
{
float * buf2_ptr = buf_ptr + block_pos;
const int block_len = std::min (nbr_spl - block_pos, sub_block_len);
const float blen_inv = fstb::rcp_uint <float> (block_len);
// Downsamples input^2 by averaging
float sum = 0;
for (int pos = 0; pos < block_len; ++pos)
{
const auto x = buf2_ptr [pos];
sum += x * x;
}
const float avg = sum * blen_inv;
const float e2 = band._env.analyse_block_raw_cst (avg, block_len);
const float env = sqrtf (e2);
// g0 = thr / max (env, thr)
const float g0 = thr / std::max (env, thr);
// gain = (1 - max ((_thr_hi_rel * g0 - 1) / (_thr_hi_rel - 1), 0)) ^ 4
float g = (_thr_hi_rel * g0 - 1) * _mul_thr_hi;
g = fstb::ipowpc <4> (1 - std::max (g, 0.f));
// Volume
mfx::dsp::mix::Fpu::scale_1_vlr (buf2_ptr, block_len, band._g_old, g);
// Next sub-block
band._g_old = g;
block_pos += block_len;
}
while (block_pos < nbr_spl);
}
}
constexpr float FilterBank::compute_split_freq (int split_idx)
{
return float (125 << split_idx);
}
} // namespace nzbl
} // namespace pi
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 8,739
| 3,844
|
/* Copyright 2021 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.
==============================================================================*/
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/gpu_device_array.h"
#include "tensorflow/core/kernels/gpu_device_array_gpu.h"
#include "tensorflow/core/kernels/gpu_prim_helpers.h"
#include "tensorflow/core/kernels/sparse_concat_op.h"
#include "tensorflow/core/lib/core/bits.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
namespace tensorflow {
typedef Eigen::GpuDevice GPUDevice;
namespace functor {
namespace {
template <typename T>
__global__ void SparseConcatKernel(
int64 output_nnz, int rank, int concat_dim, bool need_to_sort,
GpuDeviceArrayStruct<const int64*> ind_ptrs_data,
GpuDeviceArrayStruct<const T*> val_ptrs_data,
GpuDeviceArrayStruct<int64_t> nnz_scan_data,
GpuDeviceArrayStruct<int64_t> concat_size_scan_data,
GpuDeviceArrayStruct<int64_t> output_shape_data,
int64* __restrict__ output_inds, T* __restrict__ output_vals,
int64* __restrict__ output_flat_inds) {
const int64* __restrict__* __restrict__ ind_ptrs =
GetGpuDeviceArrayOnDevice(&ind_ptrs_data);
const T* __restrict__* __restrict__ val_ptrs =
GetGpuDeviceArrayOnDevice(&val_ptrs_data);
const int64* __restrict__ nnz_scan =
GetGpuDeviceArrayOnDevice(&nnz_scan_data);
const int64* __restrict__ concat_size_scan =
GetGpuDeviceArrayOnDevice(&concat_size_scan_data);
const int64* __restrict__ output_shape =
GetGpuDeviceArrayOnDevice(&output_shape_data);
const int64 num_inputs = ind_ptrs_data.size;
for (int64 nz : GpuGridRangeX<int64_t>(output_nnz)) {
const int64 input_num =
gpu_helper::upper_bound<int64_t>(nnz_scan, num_inputs, nz) - 1;
const int64 input_nz = nz - nnz_scan[input_num];
const int64 ind_offset = concat_size_scan[input_num];
if (!need_to_sort) {
output_vals[nz] = val_ptrs[input_num][input_nz];
}
int64 flat_ind = 0;
for (int j = 0; j < rank; ++j) {
const int64 output_ind = ind_ptrs[input_num][input_nz * rank + j] +
(j == concat_dim ? ind_offset : 0);
if (!need_to_sort) {
output_inds[nz * rank + j] = output_ind;
} else {
flat_ind = flat_ind * output_shape[j] + output_ind;
output_flat_inds[nz] = flat_ind;
}
}
}
}
template <typename T>
__global__ void SparseConcatPermuteKernel(
int64 output_nnz, int rank, GpuDeviceArrayStruct<const T*> val_ptrs_data,
GpuDeviceArrayStruct<int64_t> nnz_scan_data,
GpuDeviceArrayStruct<int64_t> output_shape_data,
const int64* __restrict__ output_flat_inds,
const int64* __restrict__ permutation, int64* __restrict__ output_inds,
T* __restrict__ output_vals) {
const T* __restrict__* __restrict__ val_ptrs =
GetGpuDeviceArrayOnDevice(&val_ptrs_data);
const int64* __restrict__ nnz_scan =
GetGpuDeviceArrayOnDevice(&nnz_scan_data);
const int64* __restrict__ output_shape =
GetGpuDeviceArrayOnDevice(&output_shape_data);
const int64 num_inputs = val_ptrs_data.size;
for (int64 nz : GpuGridRangeX<int64_t>(output_nnz)) {
const int64 permuted_nz = permutation[nz];
const int64 input_num =
gpu_helper::upper_bound<int64_t>(nnz_scan, num_inputs, permuted_nz) - 1;
const int64 input_nz = permuted_nz - nnz_scan[input_num];
output_vals[nz] = val_ptrs[input_num][input_nz];
int64 output_flat_ind = output_flat_inds[permuted_nz];
for (int j = rank - 1; j >= 0; --j) {
const int64 output_dim_size = output_shape[j];
output_inds[nz * rank + j] = output_flat_ind % output_dim_size;
output_flat_ind /= output_dim_size;
}
}
}
} // namespace
template <typename T>
struct SparseConcatFunctor<GPUDevice, T> {
void operator()(OpKernelContext* context, const OpInputList& inds,
const OpInputList& vals, const OpInputList& shapes,
int concat_dim) {
const int N = inds.size();
const TensorShape input_shape0(shapes[0].vec<int64_t>());
const int rank = input_shape0.dims();
// The input non-zeros are assumed to be sorted by increasing dimension
// number (i.e., row-major order), so if the concatenation is along the
// first dimension then they remain in order and we can directly compute the
// output indices and values. To concatenate along other dimensions, we
// first compute the flattened (1D) row-major output indices, then sort
// these to obtain the required permutation, and finally gather the permuted
// input values.
GpuDeviceArrayOnHost<const int64*> ind_ptrs(context, N);
GpuDeviceArrayOnHost<const T*> val_ptrs(context, N);
GpuDeviceArrayOnHost<int64_t> nnz_scan(context, N + 1);
GpuDeviceArrayOnHost<int64_t> concat_size_scan(context, N + 1);
OP_REQUIRES_OK(context, ind_ptrs.Init());
OP_REQUIRES_OK(context, val_ptrs.Init());
OP_REQUIRES_OK(context, nnz_scan.Init());
OP_REQUIRES_OK(context, concat_size_scan.Init());
int64 nnz_sum = 0;
int64 concat_size_sum = 0;
nnz_scan.Set(0, nnz_sum);
concat_size_scan.Set(0, concat_size_sum);
for (int i = 0; i < N; ++i) {
ind_ptrs.Set(i, inds[i].matrix<int64_t>().data());
val_ptrs.Set(i, vals[i].vec<T>().data());
nnz_sum += inds[i].dim_size(0);
nnz_scan.Set(i + 1, nnz_sum);
const TensorShape current_shape(shapes[i].vec<int64_t>());
concat_size_sum += current_shape.dim_size(concat_dim);
concat_size_scan.Set(i + 1, concat_size_sum);
}
OP_REQUIRES_OK(context, ind_ptrs.Finalize());
OP_REQUIRES_OK(context, val_ptrs.Finalize());
OP_REQUIRES_OK(context, nnz_scan.Finalize());
OP_REQUIRES_OK(context, concat_size_scan.Finalize());
const int64 output_nnz = nnz_sum;
const int64 output_concat_size = concat_size_sum;
const bool need_to_sort = concat_dim != 0;
GpuDeviceArrayOnHost<int64_t> output_shape(context, rank);
int64 output_dense_elements;
if (need_to_sort) {
OP_REQUIRES_OK(context, output_shape.Init());
output_dense_elements = 1;
for (int j = 0; j < rank; ++j) {
int64 output_dim_size =
j == concat_dim ? output_concat_size : input_shape0.dim_size(j);
output_shape.Set(j, output_dim_size);
output_dense_elements *= output_dim_size;
}
OP_REQUIRES_OK(context, output_shape.Finalize());
}
int64* output_inds_ptr = nullptr;
T* output_vals_ptr = nullptr;
int64* output_flat_inds_ptr = nullptr;
Tensor output_flat_inds;
if (need_to_sort) {
// SparseConcatKernel will (only) produce output_flat_inds.
OP_REQUIRES_OK(context,
context->allocate_temp(DT_INT64, TensorShape({output_nnz}),
&output_flat_inds));
output_flat_inds_ptr = output_flat_inds.vec<int64_t>().data();
} else {
OP_REQUIRES_OK(
context, allocate_outputs(context, rank, output_nnz, &output_inds_ptr,
&output_vals_ptr));
}
const GPUDevice& device = context->eigen_gpu_device();
GpuLaunchConfig config = GetGpuLaunchConfig(
output_nnz, device, &SparseConcatKernel<T>,
/*dynamic_shared_memory_size=*/0, /*block_size_limit=*/0);
OP_REQUIRES_OK(
context, GpuLaunchKernel(
SparseConcatKernel<T>, config.block_count,
config.thread_per_block, 0, device.stream(), output_nnz,
rank, concat_dim, need_to_sort, ind_ptrs.data(),
val_ptrs.data(), nnz_scan.data(), concat_size_scan.data(),
(need_to_sort ? output_shape.data()
: GpuDeviceArrayStruct<int64_t>()),
output_inds_ptr, output_vals_ptr, output_flat_inds_ptr));
if (!need_to_sort) return;
OP_REQUIRES_OK(context,
allocate_outputs(context, rank, output_nnz, &output_inds_ptr,
&output_vals_ptr));
Tensor permutation;
OP_REQUIRES_OK(context,
context->allocate_temp(DT_INT64, TensorShape({output_nnz}),
&permutation));
int64* permutation_ptr = permutation.vec<int64_t>().data();
OP_REQUIRES_OK(
context,
GpuRadixSort(context, /*size=*/output_nnz,
/*keys_in=*/output_flat_inds_ptr,
/*keys_out=*/static_cast<int64*>(nullptr),
/*indices_in=*/static_cast<const int64*>(nullptr),
/*indices_out=*/permutation_ptr,
/*num_bits=*/Log2Ceiling64(output_dense_elements)));
config = GetGpuLaunchConfig(
output_nnz, device, &SparseConcatPermuteKernel<T>,
/*dynamic_shared_memory_size=*/0, /*block_size_limit=*/0);
OP_REQUIRES_OK(
context,
GpuLaunchKernel(SparseConcatPermuteKernel<T>, config.block_count,
config.thread_per_block, 0, device.stream(), output_nnz,
rank, val_ptrs.data(), nnz_scan.data(),
output_shape.data(), output_flat_inds_ptr,
permutation_ptr, output_inds_ptr, output_vals_ptr));
}
private:
Status allocate_outputs(OpKernelContext* context, int rank, int64 output_nnz,
int64** output_inds_ptr, T** output_vals_ptr) const {
Tensor* output_inds = nullptr;
TF_RETURN_IF_ERROR(context->allocate_output(
0, TensorShape({output_nnz, rank}), &output_inds));
*output_inds_ptr = output_inds->matrix<int64_t>().data();
Tensor* output_vals = nullptr;
TF_RETURN_IF_ERROR(
context->allocate_output(1, TensorShape({output_nnz}), &output_vals));
*output_vals_ptr = output_vals->vec<T>().data();
return Status::OK();
}
};
#define DEFINE_SPARSE_CONCAT_FUNCTOR(T) \
template struct SparseConcatFunctor<GPUDevice, T>;
TF_CALL_POD_TYPES(DEFINE_SPARSE_CONCAT_FUNCTOR);
#undef DEFINE_SPARSE_CONCAT_FUNCTOR
} // namespace functor
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
| 10,958
| 3,946
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ==++==
//
//
// ==--==
#include "sos.h"
#include "disasm.h"
#include <dbghelp.h>
#include "corhdr.h"
#include "cor.h"
#include "dacprivate.h"
#include "sospriv.h"
#include "corerror.h"
#include "safemath.h"
#include <psapi.h>
#include <cordebug.h>
#include <xcordebug.h>
#include <metahost.h>
#include <mscoree.h>
#include <tchar.h>
#include "debugshim.h"
#include "gcinfo.h"
#ifndef STRESS_LOG
#define STRESS_LOG
#endif // STRESS_LOG
#define STRESS_LOG_READONLY
#include "stresslog.h"
#ifdef FEATURE_PAL
#include <sys/stat.h>
#include <dlfcn.h>
#endif // !FEATURE_PAL
#include "coreclrhost.h"
#include <set>
#include <string>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
const char * const CorElementTypeName[ELEMENT_TYPE_MAX]=
{
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) c,
#include "cortypeinfo.h"
#undef TYPEINFO
};
const char * const CorElementTypeNamespace[ELEMENT_TYPE_MAX]=
{
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) ns,
#include "cortypeinfo.h"
#undef TYPEINFO
};
IXCLRDataProcess *g_clrData = NULL;
ISOSDacInterface *g_sos = NULL;
#ifndef IfFailRet
#define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { return (Status); } } while (0)
#endif
// Max number of reverted rejit versions that !dumpmd and !ip2md will print
const UINT kcMaxRevertedRejitData = 10;
const UINT kcMaxTieredVersions = 10;
#ifndef FEATURE_PAL
// ensure we always allocate on the process heap
void* __cdecl operator new(size_t size) throw()
{ return HeapAlloc(GetProcessHeap(), 0, size); }
void __cdecl operator delete(void* pObj) throw()
{ HeapFree(GetProcessHeap(), 0, pObj); }
void* __cdecl operator new[](size_t size) throw()
{ return HeapAlloc(GetProcessHeap(), 0, size); }
void __cdecl operator delete[](void* pObj) throw()
{ HeapFree(GetProcessHeap(), 0, pObj); }
/**********************************************************************\
* Routine Description: *
* *
* This function is called to get the memory address given a symbol *
* name. It handles difference in symbol name between ntsd and *
* windbg. *
* *
\**********************************************************************/
DWORD_PTR GetValueFromExpression(___in __in_z const char *const instr)
{
_ASSERTE(g_pRuntime != nullptr);
LoadRuntimeSymbols();
std::string symbol;
symbol.append(GetRuntimeModuleName());
symbol.append("!");
symbol.append(instr);
ULONG64 dwAddr;
const char* str = symbol.c_str();
char name[256];
dwAddr = 0;
HRESULT hr = g_ExtSymbols->GetOffsetByName (str, &dwAddr);
if (SUCCEEDED(hr))
return (DWORD_PTR)dwAddr;
else if (hr == S_FALSE && dwAddr)
return (DWORD_PTR)dwAddr;
strcpy_s (name, _countof(name), str);
char *ptr;
if ((ptr = strstr (name, "__")) != NULL)
{
ptr[0] = ':';
ptr[1] = ':';
ptr += 2;
while ((ptr = strstr(ptr, "__")) != NULL)
{
ptr[0] = ':';
ptr[1] = ':';
ptr += 2;
}
dwAddr = 0;
hr = g_ExtSymbols->GetOffsetByName (name, &dwAddr);
if (SUCCEEDED(hr))
return (DWORD_PTR)dwAddr;
else if (hr == S_FALSE && dwAddr)
return (DWORD_PTR)dwAddr;
}
else if ((ptr = strstr (name, "::")) != NULL)
{
ptr[0] = '_';
ptr[1] = '_';
ptr += 2;
while ((ptr = strstr(ptr, "::")) != NULL)
{
ptr[0] = '_';
ptr[1] = '_';
ptr += 2;
}
dwAddr = 0;
hr = g_ExtSymbols->GetOffsetByName (name, &dwAddr);
if (SUCCEEDED(hr))
return (DWORD_PTR)dwAddr;
else if (hr == S_FALSE && dwAddr)
return (DWORD_PTR)dwAddr;
}
return 0;
}
#endif // FEATURE_PAL
void ReportOOM()
{
ExtOut("SOS Error: Out of memory\n");
}
BOOL IsDumpFile()
{
static int g_fDumpFile = -1;
if (g_fDumpFile == -1) {
ULONG Class;
ULONG Qualifier;
g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
if (Qualifier >= DEBUG_DUMP_SMALL)
g_fDumpFile = 1;
else
g_fDumpFile = 0;
}
return g_fDumpFile != 0;
}
BOOL g_InMinidumpSafeMode = FALSE;
BOOL IsMiniDumpFileNODAC ()
{
#ifndef FEATURE_PAL
ULONG Class;
ULONG Qualifier;
g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
if (Qualifier == DEBUG_DUMP_SMALL)
{
g_ExtControl->GetDumpFormatFlags(&Qualifier);
if ((Qualifier & DEBUG_FORMAT_USER_SMALL_FULL_MEMORY) == 0)
{
return TRUE;
}
}
#endif // FEATURE_PAL
return FALSE;
}
// We use this predicate to mean the smallest, most restrictive kind of
// minidump file. There is no heap dump, only that set of information
// gathered to make !clrstack, !threads, !help, !eeversion and !pe work.
BOOL IsMiniDumpFile ()
{
#ifndef FEATURE_PAL
// It is okay for this to be static, because although the debugger may debug multiple
// managed processes at once, I don't believe multiple dumpfiles of different
// types is a scenario to worry about.
if (IsMiniDumpFileNODAC())
{
// Beyond recognizing the dump type above, all we can rely on for this
// is a flag set by the user indicating they want a safe mode minidump
// experience. This is primarily for testing.
return g_InMinidumpSafeMode;
}
#endif // FEATURE_PAL
return FALSE;
}
ULONG DebuggeeType()
{
static ULONG Class = DEBUG_CLASS_UNINITIALIZED;
if (Class == DEBUG_CLASS_UNINITIALIZED) {
ULONG Qualifier;
g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
}
return Class;
}
const WCHAR GetTargetDirectorySeparatorW()
{
if (IsWindowsTarget()) {
return W('\\');
}
else {
return W('/');
}
}
#ifndef FEATURE_PAL
// Check if a file exist
BOOL FileExist (const char *filename)
{
WIN32_FIND_DATA FindFileData;
HANDLE handle = FindFirstFile (filename, &FindFileData);
if (handle != INVALID_HANDLE_VALUE) {
FindClose (handle);
return TRUE;
}
else
return FALSE;
}
BOOL FileExist (const WCHAR *filename)
{
WIN32_FIND_DATAW FindFileData;
HANDLE handle = FindFirstFileW (filename, &FindFileData);
if (handle != INVALID_HANDLE_VALUE) {
FindClose (handle);
return TRUE;
}
else
return FALSE;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find out if a dll is bbt-ized *
* *
\**********************************************************************/
BOOL IsRetailBuild (size_t base)
{
IMAGE_DOS_HEADER DosHeader;
if (g_ExtData->ReadVirtual(TO_CDADDR(base), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
return FALSE;
IMAGE_NT_HEADERS32 Header32;
if (g_ExtData->ReadVirtual(TO_CDADDR(base + DosHeader.e_lfanew), &Header32, sizeof(Header32), NULL) != S_OK)
return FALSE;
// If there is no COMHeader, this can not be managed code.
if (Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress == 0)
return FALSE;
size_t debugDirAddr = base + Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
size_t nSize = Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
IMAGE_DEBUG_DIRECTORY debugDir;
size_t nbytes = 0;
while (nbytes < nSize) {
if (g_ExtData->ReadVirtual(TO_CDADDR(debugDirAddr+nbytes), &debugDir, sizeof(debugDir), NULL) != S_OK)
return FALSE;
if (debugDir.Type == 0xA) {
return TRUE;
}
nbytes += sizeof(debugDir);
}
return FALSE;
}
#endif // !FEATURE_PAL
/**********************************************************************\
* Routine Description: *
* *
* This function is called to read memory from the debugee's *
* address space. If the initial read fails, it attempts to read *
* only up to the edge of the page containing "offset". *
* *
\**********************************************************************/
BOOL SafeReadMemory (TADDR offset, PVOID lpBuffer, ULONG cb, PULONG lpcbBytesRead)
{
BOOL bRet = SUCCEEDED(g_ExtData->ReadVirtual(TO_CDADDR(offset), lpBuffer, cb, lpcbBytesRead));
if (!bRet)
{
cb = _min(cb, (ULONG)(NextOSPageAddress(offset) - offset));
bRet = SUCCEEDED(g_ExtData->ReadVirtual(TO_CDADDR(offset), lpBuffer, cb, lpcbBytesRead));
}
return bRet;
}
ULONG OSPageSize ()
{
static ULONG pageSize = 0;
if (pageSize == 0)
g_ExtControl->GetPageSize(&pageSize);
return pageSize;
}
size_t NextOSPageAddress (size_t addr)
{
size_t pageSize = OSPageSize();
return (addr+pageSize)&(~(pageSize-1));
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to get the address of MethodDesc *
* given an ip address *
* *
\**********************************************************************/
void IP2MethodDesc (DWORD_PTR IP, DWORD_PTR &methodDesc, JITTypes &jitType,
DWORD_PTR &gcinfoAddr)
{
CLRDATA_ADDRESS EIP = TO_CDADDR(IP);
DacpCodeHeaderData codeHeaderData;
methodDesc = NULL;
gcinfoAddr = NULL;
if (codeHeaderData.Request(g_sos, EIP) != S_OK)
{
return;
}
methodDesc = (DWORD_PTR) codeHeaderData.MethodDescPtr;
jitType = (JITTypes) codeHeaderData.JITType;
gcinfoAddr = (DWORD_PTR) codeHeaderData.GCInfo;
}
BOOL IsValueField (DacpFieldDescData *pFD)
{
return (pFD->Type == ELEMENT_TYPE_VALUETYPE);
}
void DisplayDataMember (DacpFieldDescData* pFD, DWORD_PTR dwAddr, BOOL fAlign=TRUE)
{
if (dwAddr > 0)
{
// we must have called this function for a "real" (non-zero size) data type
PREFIX_ASSUME(gElementTypeInfo[pFD->Type] != 0);
DWORD_PTR dwTmp = dwAddr;
bool bVTStatic = (pFD->bIsStatic && pFD->Type == ELEMENT_TYPE_VALUETYPE);
if (gElementTypeInfo[pFD->Type] != NO_SIZE || bVTStatic)
{
union Value
{
char ch;
short Short;
DWORD_PTR ptr;
int Int;
unsigned int UInt;
__int64 Int64;
unsigned __int64 UInt64;
float Float;
double Double;
} value;
ZeroMemory(&value, sizeof(value));
if (bVTStatic)
{
// static VTypes are boxed
moveBlock (value, dwTmp, gElementTypeInfo[ELEMENT_TYPE_CLASS]);
}
else
{
moveBlock (value, dwTmp, gElementTypeInfo[pFD->Type]);
}
switch (pFD->Type)
{
case ELEMENT_TYPE_I1:
// there's no ANSI conformant type specifier for
// signed char, so use the next best thing,
// signed short (sign extending)
if (fAlign)
ExtOut("%" POINTERSIZE "hd", (short)value.ch);
else
ExtOut("%d", value.ch);
break;
case ELEMENT_TYPE_I2:
if (fAlign)
ExtOut("%" POINTERSIZE "hd", value.Short);
else
ExtOut("%d", value.Short);
break;
case ELEMENT_TYPE_I4:
if (fAlign)
ExtOut("%" POINTERSIZE "d", value.Int);
else
ExtOut("%d", value.Int);
break;
case ELEMENT_TYPE_I8:
if (fAlign)
ExtOut("%" POINTERSIZE "I64d", value.Int64);
else
ExtOut("%I64d", value.Int64);
break;
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_BOOLEAN:
if (fAlign)
// there's no ANSI conformant type specifier for
// unsigned char, so use the next best thing,
// unsigned short, not extending the sign
ExtOut("%" POINTERSIZE "hu", (USHORT)value.Short);
else
ExtOut("%u", value.ch);
break;
case ELEMENT_TYPE_U2:
if (fAlign)
ExtOut("%" POINTERSIZE "hu", value.Short);
else
ExtOut("%u", value.Short);
break;
case ELEMENT_TYPE_U4:
if (fAlign)
ExtOut("%" POINTERSIZE "u", value.UInt);
else
ExtOut("%u", value.UInt);
break;
case ELEMENT_TYPE_U8:
if (fAlign)
ExtOut("%" POINTERSIZE "I64u", value.UInt64);
else
ExtOut("%I64u", value.UInt64);
break;
case ELEMENT_TYPE_I:
case ELEMENT_TYPE_U:
if (fAlign)
ExtOut("%" POINTERSIZE "p", SOS_PTR(value.ptr));
else
ExtOut("%p", SOS_PTR(value.ptr));
break;
case ELEMENT_TYPE_R4:
ExtOut("%f", value.Float);
break;
case ELEMENT_TYPE_R8:
ExtOut("%f", value.Double);
break;
case ELEMENT_TYPE_CHAR:
if (fAlign)
ExtOut("%" POINTERSIZE "hx", value.Short);
else
ExtOut("%x", value.Short);
break;
case ELEMENT_TYPE_VALUETYPE:
if (value.ptr)
DMLOut(DMLValueClass(pFD->MTOfType, dwTmp));
else
ExtOut("%p", SOS_PTR(0));
break;
default:
if (value.ptr)
DMLOut(DMLObject(value.ptr));
else
ExtOut("%p", SOS_PTR(0));
break;
}
}
else
{
if (pFD->Type == ELEMENT_TYPE_VALUETYPE)
DMLOut(DMLValueClass(pFD->MTOfType, dwTmp));
else
ExtOut("%p", SOS_PTR(0));
}
}
else
{
ExtOut("%" POINTERSIZE "s", " ");
}
}
void GetStaticFieldPTR(DWORD_PTR* pOutPtr, DacpDomainLocalModuleData* pDLMD, DacpMethodTableData* pMTD, DacpFieldDescData* pFDD, BYTE* pFlags = 0)
{
DWORD_PTR dwTmp;
if (pFDD->Type == ELEMENT_TYPE_VALUETYPE
|| pFDD->Type == ELEMENT_TYPE_CLASS)
{
dwTmp = (DWORD_PTR) pDLMD->pGCStaticDataStart + pFDD->dwOffset;
}
else
{
dwTmp = (DWORD_PTR) pDLMD->pNonGCStaticDataStart + pFDD->dwOffset;
}
*pOutPtr = 0;
if (pMTD->bIsDynamic)
{
ExtOut("dynamic statics NYI");
return;
}
else
{
if (pFlags && pMTD->bIsShared)
{
BYTE flags;
DWORD_PTR pTargetFlags = (DWORD_PTR) pDLMD->pClassData + RidFromToken(pMTD->cl) - 1;
move_xp (flags, pTargetFlags);
*pFlags = flags;
}
*pOutPtr = dwTmp;
}
return;
}
void GetDLMFlags(DacpDomainLocalModuleData* pDLMD, DacpMethodTableData* pMTD, BYTE* pFlags)
{
if (pMTD->bIsDynamic)
{
ExtOut("dynamic statics NYI");
return;
}
else
{
if (pFlags)
{
BYTE flags;
DWORD_PTR pTargetFlags = (DWORD_PTR) pDLMD->pClassData + RidFromToken(pMTD->cl) - 1;
move_xp (flags, pTargetFlags);
*pFlags = flags;
}
}
return;
}
void GetThreadStaticFieldPTR(DWORD_PTR* pOutPtr, DacpThreadLocalModuleData* pTLMD, DacpMethodTableData* pMTD, DacpFieldDescData* pFDD, BYTE* pFlags = 0)
{
DWORD_PTR dwTmp;
if (pFDD->Type == ELEMENT_TYPE_VALUETYPE
|| pFDD->Type == ELEMENT_TYPE_CLASS)
{
dwTmp = (DWORD_PTR) pTLMD->pGCStaticDataStart + pFDD->dwOffset;
}
else
{
dwTmp = (DWORD_PTR) pTLMD->pNonGCStaticDataStart + pFDD->dwOffset;
}
*pOutPtr = 0;
if (pMTD->bIsDynamic)
{
ExtOut("dynamic thread statics NYI");
return;
}
else
{
if (pFlags)
{
BYTE flags;
DWORD_PTR pTargetFlags = (DWORD_PTR) pTLMD->pClassData + RidFromToken(pMTD->cl) - 1;
move_xp (flags, pTargetFlags);
*pFlags = flags;
}
*pOutPtr = dwTmp;
}
return;
}
void DisplaySharedStatic(ULONG64 dwModuleDomainID, DacpMethodTableData* pMT, DacpFieldDescData *pFD)
{
DacpAppDomainStoreData adsData;
if (adsData.Request(g_sos)!=S_OK)
{
ExtOut("Unable to get AppDomain information\n");
}
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adsData.DomainCount];
if (pArray==NULL)
{
ReportOOM();
return;
}
if (g_sos->GetAppDomainList(adsData.DomainCount,pArray, NULL)!=S_OK)
{
ExtOut("Unable to get array of AppDomains\n");
return;
}
#if defined(_TARGET_WIN64_)
ExtOut(" >> Domain:Value ");
#else
ExtOut(" >> Domain:Value ");
#endif
// Skip the SystemDomain and SharedDomain
for (int i = 0; i < adsData.DomainCount ; i ++)
{
DacpAppDomainData appdomainData;
if (appdomainData.Request(g_sos,pArray[i])!=S_OK)
{
ExtOut("Unable to get AppDomain %lx\n",pArray[i]);
return;
}
DacpDomainLocalModuleData vDomainLocalModule;
if (g_sos->GetDomainLocalModuleDataFromAppDomain(appdomainData.AppDomainPtr, (int)dwModuleDomainID, &vDomainLocalModule) != S_OK)
{
// On .NET Core, dwModuleDomainID is the address of the DomainLocalModule.
if (vDomainLocalModule.Request(g_sos, dwModuleDomainID) != S_OK)
{
DMLOut(" %s:NotInit ", DMLDomain(pArray[i]));
continue;
}
}
DWORD_PTR dwTmp;
BYTE Flags = 0;
GetStaticFieldPTR(&dwTmp, &vDomainLocalModule , pMT, pFD, &Flags);
if ((Flags&1) == 0) {
// We have not initialized this yet.
DMLOut(" %s:NotInit ", DMLDomain(pArray[i]));
continue;
}
else if (Flags & 2) {
// We have not initialized this yet.
DMLOut(" %s:FailInit", DMLDomain(pArray[i]));
continue;
}
DMLOut(" %s:", DMLDomain(appdomainData.AppDomainPtr));
DisplayDataMember(pFD, dwTmp, FALSE);
}
ExtOut(" <<\n");
}
void DisplayThreadStatic (DacpModuleData* pModule, DacpMethodTableData* pMT, DacpFieldDescData *pFD, BOOL fIsShared)
{
SIZE_T dwModuleIndex = (SIZE_T)pModule->dwModuleIndex;
SIZE_T dwModuleDomainID = (SIZE_T)pModule->dwModuleID;
DacpThreadStoreData ThreadStore;
ThreadStore.Request(g_sos);
ExtOut(" >> Thread:Value");
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread)
{
DacpThreadData vThread;
if (vThread.Request(g_sos, CurThread) != S_OK)
{
ExtOut(" error getting thread %p, aborting this field\n", SOS_PTR(CurThread));
return;
}
if (vThread.osThreadId != 0)
{
CLRDATA_ADDRESS appDomainAddr = vThread.domain;
// Get the DLM (we need this to check the ClassInit flags).
// It's annoying that we have to issue one request for
// domain-neutral modules and domain-specific modules.
DacpDomainLocalModuleData vDomainLocalModule;
if (fIsShared)
{
if (g_sos->GetDomainLocalModuleDataFromAppDomain(appDomainAddr, (int)dwModuleDomainID, &vDomainLocalModule) != S_OK)
{
// On .NET Core, dwModuleDomainID is the address of the DomainLocalModule.
if (vDomainLocalModule.Request(g_sos, dwModuleDomainID) != S_OK)
{
// Not initialized, go to next thread and continue looping
CurThread = vThread.nextThread;
continue;
}
}
}
else
{
if (g_sos->GetDomainLocalModuleDataFromModule(pMT->Module, &vDomainLocalModule) != S_OK)
{
// Not initialized, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
}
// Get the TLM
DacpThreadLocalModuleData vThreadLocalModule;
if (g_sos->GetThreadLocalModuleData(CurThread, (int)dwModuleIndex, &vThreadLocalModule) != S_OK)
{
// Not initialized, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
DWORD_PTR dwTmp;
BYTE Flags = 0;
GetThreadStaticFieldPTR(&dwTmp, &vThreadLocalModule, pMT, pFD, &Flags);
if ((Flags&4) == 0)
{
// Not allocated, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
Flags = 0;
GetDLMFlags(&vDomainLocalModule, pMT, &Flags);
if ((Flags&1) == 0)
{
// Not initialized, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
ExtOut(" %x:", vThread.osThreadId);
DisplayDataMember(pFD, dwTmp, FALSE);
}
// Go to next thread
CurThread = vThread.nextThread;
}
ExtOut(" <<\n");
}
const char * ElementTypeName(unsigned type)
{
switch (type) {
case ELEMENT_TYPE_PTR:
return "PTR";
break;
case ELEMENT_TYPE_BYREF:
return "BYREF";
break;
case ELEMENT_TYPE_VALUETYPE:
return "VALUETYPE";
break;
case ELEMENT_TYPE_CLASS:
return "CLASS";
break;
case ELEMENT_TYPE_VAR:
return "VAR";
break;
case ELEMENT_TYPE_ARRAY:
return "ARRAY";
break;
case ELEMENT_TYPE_FNPTR:
return "FNPTR";
break;
case ELEMENT_TYPE_SZARRAY:
return "SZARRAY";
break;
case ELEMENT_TYPE_MVAR:
return "MVAR";
break;
default:
if ((type >= _countof(CorElementTypeName)) || (CorElementTypeName[type] == NULL))
{
return "";
}
return CorElementTypeName[type];
break;
}
} // ElementTypeName
const char * ElementTypeNamespace(unsigned type)
{
if ((type >= _countof(CorElementTypeName)) || (CorElementTypeNamespace[type] == NULL))
{
return "";
}
return CorElementTypeNamespace[type];
}
void ComposeName_s(CorElementType Type, __out_ecount(capacity_buffer) LPSTR buffer, size_t capacity_buffer)
{
const char *p = ElementTypeNamespace(Type);
if ((p) && (*p != '\0'))
{
strcpy_s(buffer,capacity_buffer,p);
strcat_s(buffer,capacity_buffer,".");
strcat_s(buffer,capacity_buffer,ElementTypeName(Type));
}
else
{
strcpy_s(buffer,capacity_buffer,ElementTypeName(Type));
}
}
// NOTE: pszName is changed
// INPUT MAXCHARS RETURN
// HelloThere 5 ...re
// HelloThere 8 ...There
LPWSTR FormatTypeName (__out_ecount (maxChars) LPWSTR pszName, UINT maxChars)
{
UINT iStart = 0;
UINT iLen = (int) _wcslen(pszName);
if (iLen > maxChars)
{
iStart = iLen - maxChars;
UINT numDots = (maxChars < 3) ? maxChars : 3;
for (UINT i=0; i < numDots; i++)
pszName[iStart+i] = '.';
}
return pszName + iStart;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to dump all fields of a managed object. *
* dwStartAddr specifies the beginning memory address. *
* bFirst is used to avoid printing header every time. *
* *
\**********************************************************************/
void DisplayFields(CLRDATA_ADDRESS cdaMT, DacpMethodTableData *pMTD, DacpMethodTableFieldData *pMTFD, DWORD_PTR dwStartAddr, BOOL bFirst, BOOL bValueClass)
{
static DWORD numInstanceFields = 0;
if (bFirst)
{
ExtOutIndent();
ExtOut("%" POINTERSIZE "s %8s %8s %20s %2s %8s %" POINTERSIZE "s %s\n",
"MT", "Field", "Offset", "Type", "VT", "Attr", "Value", "Name");
numInstanceFields = 0;
}
BOOL fIsShared = pMTD->bIsShared;
if (pMTD->ParentMethodTable)
{
DacpMethodTableData vParentMethTable;
if (vParentMethTable.Request(g_sos,pMTD->ParentMethodTable) != S_OK)
{
ExtOut("Invalid parent MethodTable\n");
return;
}
DacpMethodTableFieldData vParentMethTableFields;
if (vParentMethTableFields.Request(g_sos,pMTD->ParentMethodTable) != S_OK)
{
ExtOut("Invalid parent EEClass\n");
return;
}
DisplayFields(pMTD->ParentMethodTable, &vParentMethTable, &vParentMethTableFields, dwStartAddr, FALSE, bValueClass);
}
DWORD numStaticFields = 0;
CLRDATA_ADDRESS dwAddr = pMTFD->FirstField;
DacpFieldDescData vFieldDesc;
// Get the module name
DacpModuleData module;
if (module.Request(g_sos, pMTD->Module)!=S_OK)
return;
ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
while (numInstanceFields < pMTFD->wNumInstanceFields
|| numStaticFields < pMTFD->wNumStaticFields)
{
if (IsInterrupt())
return;
ExtOutIndent ();
if ((vFieldDesc.Request(g_sos, dwAddr)!=S_OK) ||
(vFieldDesc.Type >= ELEMENT_TYPE_MAX))
{
ExtOut("Unable to display fields\n");
return;
}
dwAddr = vFieldDesc.NextField;
DWORD offset = vFieldDesc.dwOffset;
if(!((vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal || fIsShared) && vFieldDesc.bIsStatic))
{
if (!bValueClass)
{
offset += sizeof(BaseObject);
}
}
DMLOut("%s %8x %8x ", DMLMethodTable(vFieldDesc.MTOfType),
TokenFromRid(vFieldDesc.mb, mdtFieldDef),
offset);
char ElementName[mdNameLen];
if ((vFieldDesc.Type == ELEMENT_TYPE_VALUETYPE ||
vFieldDesc.Type == ELEMENT_TYPE_CLASS) && vFieldDesc.MTOfType)
{
NameForMT_s((DWORD_PTR)vFieldDesc.MTOfType, g_mdName, mdNameLen);
ExtOut("%20.20S ", FormatTypeName(g_mdName, 20));
}
else
{
if (vFieldDesc.Type == ELEMENT_TYPE_CLASS && vFieldDesc.TokenOfType != mdTypeDefNil)
{
// Get the name from Metadata!!!
NameForToken_s(TokenFromRid(vFieldDesc.TokenOfType, mdtTypeDef), pImport, g_mdName, mdNameLen, false);
ExtOut("%20.20S ", FormatTypeName(g_mdName, 20));
}
else
{
// If ET type from signature is different from fielddesc, then the signature one is more descriptive.
// For example, E_T_STRING in field desc will be E_T_CLASS. In minidump's case, we won't have
// the method table for it.
ComposeName_s(vFieldDesc.Type != vFieldDesc.sigType ? vFieldDesc.sigType : vFieldDesc.Type, ElementName, sizeof(ElementName)/sizeof(ElementName[0]));
ExtOut("%20.20s ", ElementName);
}
}
ExtOut("%2s ", (IsElementValueType(vFieldDesc.Type)) ? "1" : "0");
if (vFieldDesc.bIsStatic && (vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal))
{
numStaticFields ++;
if (fIsShared)
ExtOut("%8s %" POINTERSIZE "s", "shared", vFieldDesc.bIsThreadLocal ? "TLstatic" : "CLstatic");
else
ExtOut("%8s ", vFieldDesc.bIsThreadLocal ? "TLstatic" : "CLstatic");
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
if (IsMiniDumpFile())
{
ExtOut(" <no information>\n");
}
else
{
if (vFieldDesc.bIsThreadLocal)
{
DacpModuleData vModule;
if (vModule.Request(g_sos,pMTD->Module) == S_OK)
{
DisplayThreadStatic(&vModule, pMTD, &vFieldDesc, fIsShared);
}
}
else if (vFieldDesc.bIsContextLocal)
{
ExtOut("\nDisplay of context static variables is not implemented\n");
}
}
}
else if (vFieldDesc.bIsStatic)
{
numStaticFields ++;
if (fIsShared)
{
ExtOut("%8s %" POINTERSIZE "s", "shared", "static");
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
if (IsMiniDumpFile())
{
ExtOut(" <no information>\n");
}
else
{
DacpModuleData vModule;
if (vModule.Request(g_sos,pMTD->Module) == S_OK)
{
DisplaySharedStatic(vModule.dwModuleID, pMTD, &vFieldDesc);
}
}
}
else
{
ExtOut("%8s ", "static");
DacpDomainLocalModuleData vDomainLocalModule;
// The MethodTable isn't shared, so the module must not be loaded domain neutral. We can
// get the specific DomainLocalModule instance without needing to know the AppDomain in advance.
if (g_sos->GetDomainLocalModuleDataFromModule(pMTD->Module, &vDomainLocalModule) != S_OK)
{
ExtOut(" <no information>\n");
}
else
{
DWORD_PTR dwTmp;
GetStaticFieldPTR(&dwTmp, &vDomainLocalModule, pMTD, &vFieldDesc);
DisplayDataMember(&vFieldDesc, dwTmp);
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
}
}
}
else
{
numInstanceFields ++;
ExtOut("%8s ", "instance");
if (dwStartAddr > 0)
{
DWORD_PTR dwTmp = dwStartAddr + vFieldDesc.dwOffset + (bValueClass ? 0 : sizeof(BaseObject));
DisplayDataMember(&vFieldDesc, dwTmp);
}
else
{
ExtOut(" %8s", " ");
}
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
}
}
return;
}
HRESULT GetNonSharedStaticFieldValueFromName(
UINT64* pValue,
DWORD_PTR moduleAddr,
const char *typeName,
__in_z LPCWSTR wszFieldName,
CorElementType fieldType)
{
HRESULT hr = S_OK;
mdTypeDef mdType = 0;
GetInfoFromName(moduleAddr, typeName, &mdType);
if (mdType == 0)
{
return E_FAIL; // Failed to find type token
}
CLRDATA_ADDRESS cdaMethodTable = 0;
if (FAILED(hr = g_sos->GetMethodDescFromToken(moduleAddr, mdType, &cdaMethodTable)) ||
!IsValidToken(moduleAddr, mdType) ||
cdaMethodTable == 0)
{
return FAILED(hr) ? hr : E_FAIL; // Invalid type token or type is not loaded yet
}
DacpMethodTableData vMethodTable;
if ((hr = vMethodTable.Request(g_sos, cdaMethodTable)) != S_OK)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get method table data
}
if (vMethodTable.bIsShared)
{
ExtOut(" %s: %s\n", "Method table is shared (not implemented)", typeName);
return E_NOTIMPL;
}
DacpMethodTableFieldData vMethodTableFields;
if (FAILED(hr = vMethodTableFields.Request(g_sos, cdaMethodTable)))
{
return hr; // Failed to get field data
}
DacpModuleData vModule;
if ((hr = vModule.Request(g_sos, vMethodTable.Module)) != S_OK)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get module data
}
DacpDomainLocalModuleData vDomainLocalModule;
if ((hr = g_sos->GetDomainLocalModuleDataFromModule(vMethodTable.Module, &vDomainLocalModule)) != S_OK)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get domain local module data
}
ToRelease<IMetaDataImport> pImport = MDImportForModule(&vModule);
CLRDATA_ADDRESS cdaField = vMethodTableFields.FirstField;
DacpFieldDescData vFieldDesc;
bool found = false;
for (DWORD staticFieldIndex = 0; staticFieldIndex < vMethodTableFields.wNumStaticFields; )
{
if ((hr = vFieldDesc.Request(g_sos, cdaField)) != S_OK || vFieldDesc.Type >= ELEMENT_TYPE_MAX)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get member field desc
}
cdaField = vFieldDesc.NextField;
if (!vFieldDesc.bIsStatic)
{
continue;
}
++staticFieldIndex;
if (vFieldDesc.Type != fieldType)
{
continue;
}
if (FAILED(hr = NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false)))
{
return hr; // Failed to get member field name
}
if (_wcscmp(g_mdName, wszFieldName) != 0)
{
continue;
}
if (vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal)
{
ExtOut(" %s: %s.%S\n", "Static field is thread-local or context-local (not implemented)", typeName, wszFieldName);
return E_NOTIMPL;
}
found = true;
break;
}
if (!found)
{
return E_FAIL; // Static field not found
}
DWORD_PTR pValueAddr = 0;
GetStaticFieldPTR(&pValueAddr, &vDomainLocalModule, &vMethodTable, &vFieldDesc);
if (pValueAddr == 0)
{
return E_FAIL; // Failed to get static field address
}
UINT64 value = 0;
if (FAILED(MOVEBLOCK(value, pValueAddr, gElementTypeInfo[fieldType])))
{
return E_FAIL; // Failed to read static field
}
*pValue = value;
return S_OK;
}
// Return value: -1 = error,
// 0 = field not found,
// > 0 = offset to field from objAddr
int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, __in_z LPCWSTR wszFieldName, BOOL bFirst)
{
TADDR mt = NULL;
if FAILED(GetMTOfObject(TO_TADDR(cdaObj), &mt))
return -1;
return GetObjFieldOffset(cdaObj, TO_CDADDR(mt), wszFieldName, bFirst);
}
// Return value: -1 = error,
// 0 = field not found,
// > 0 = offset to field from objAddr
int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName,
BOOL bFirst/*=TRUE*/, DacpFieldDescData* pDacpFieldDescData/*=NULL*/)
{
#define EXITPOINT(EXPR) do { if(!(EXPR)) { return -1; } } while (0)
DacpObjectData objData;
DacpMethodTableData dmtd;
DacpMethodTableFieldData vMethodTableFields;
DacpFieldDescData vFieldDesc;
DacpModuleData module;
static DWORD numInstanceFields = 0; // Static due to recursion visiting parents
if (bFirst)
{
numInstanceFields = 0;
}
EXITPOINT(objData.Request(g_sos, cdaObj) == S_OK);
EXITPOINT(dmtd.Request(g_sos, cdaMT) == S_OK);
if (dmtd.ParentMethodTable)
{
DWORD retVal = GetObjFieldOffset (cdaObj, dmtd.ParentMethodTable,
wszFieldName, FALSE, pDacpFieldDescData);
if (retVal != 0)
{
// return in case of error or success.
// Fall through for field-not-found.
return retVal;
}
}
EXITPOINT (vMethodTableFields.Request(g_sos,cdaMT) == S_OK);
EXITPOINT (module.Request(g_sos,dmtd.Module) == S_OK);
CLRDATA_ADDRESS dwAddr = vMethodTableFields.FirstField;
ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
while (numInstanceFields < vMethodTableFields.wNumInstanceFields)
{
EXITPOINT (vFieldDesc.Request(g_sos, dwAddr) == S_OK);
if (!vFieldDesc.bIsStatic)
{
DWORD offset = vFieldDesc.dwOffset + sizeof(BaseObject);
NameForToken_s (TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
if (_wcscmp (wszFieldName, g_mdName) == 0)
{
if (pDacpFieldDescData != NULL)
{
*pDacpFieldDescData = vFieldDesc;
}
return offset;
}
numInstanceFields ++;
}
dwAddr = vFieldDesc.NextField;
}
// Field name not found...
return 0;
#undef EXITPOINT
}
// Return value: -1 = error
// -2 = not found
// >= 0 = offset to field from cdaValue
int GetValueFieldOffset(CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName, DacpFieldDescData* pDacpFieldDescData)
{
#define EXITPOINT(EXPR) do { if(!(EXPR)) { return -1; } } while (0)
const int NOT_FOUND = -2;
DacpMethodTableData dmtd;
DacpMethodTableFieldData vMethodTableFields;
DacpFieldDescData vFieldDesc;
DacpModuleData module;
static DWORD numInstanceFields = 0; // Static due to recursion visiting parents
numInstanceFields = 0;
EXITPOINT(vMethodTableFields.Request(g_sos, cdaMT) == S_OK);
EXITPOINT(dmtd.Request(g_sos, cdaMT) == S_OK);
EXITPOINT(module.Request(g_sos, dmtd.Module) == S_OK);
if (dmtd.ParentMethodTable)
{
DWORD retVal = GetValueFieldOffset(dmtd.ParentMethodTable, wszFieldName, pDacpFieldDescData);
if (retVal != (DWORD)NOT_FOUND)
{
// Return in case of error or success. Fall through for field-not-found.
return retVal;
}
}
CLRDATA_ADDRESS dwAddr = vMethodTableFields.FirstField;
ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
while (numInstanceFields < vMethodTableFields.wNumInstanceFields)
{
EXITPOINT(vFieldDesc.Request(g_sos, dwAddr) == S_OK);
if (!vFieldDesc.bIsStatic)
{
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
if (_wcscmp(wszFieldName, g_mdName) == 0)
{
if (pDacpFieldDescData != NULL)
{
*pDacpFieldDescData = vFieldDesc;
}
return vFieldDesc.dwOffset;
}
numInstanceFields++;
}
dwAddr = vFieldDesc.NextField;
}
// Field name not found...
return NOT_FOUND;
#undef EXITPOINT
}
// Returns an AppDomain address if AssemblyPtr is loaded into that domain only. Otherwise
// returns NULL
CLRDATA_ADDRESS IsInOneDomainOnly(CLRDATA_ADDRESS AssemblyPtr)
{
CLRDATA_ADDRESS appDomain = NULL;
DacpAppDomainStoreData adstore;
if (adstore.Request(g_sos) != S_OK)
{
ExtOut("Unable to get appdomain store\n");
return NULL;
}
size_t AllocSize;
if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), adstore.DomainCount, AllocSize))
{
ReportOOM();
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adstore.DomainCount];
if (pArray==NULL)
{
ReportOOM();
return NULL;
}
if (g_sos->GetAppDomainList(adstore.DomainCount, pArray, NULL)!=S_OK)
{
ExtOut ("Failed to get appdomain list\n");
return NULL;
}
for (int i = 0; i < adstore.DomainCount; i++)
{
if (IsInterrupt())
return NULL;
DacpAppDomainData dadd;
if (dadd.Request(g_sos, pArray[i]) != S_OK)
{
ExtOut ("Unable to get AppDomain %p\n", SOS_PTR(pArray[i]));
return NULL;
}
if (dadd.AssemblyCount)
{
size_t AssemblyAllocSize;
if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), dadd.AssemblyCount, AssemblyAllocSize))
{
ReportOOM();
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pAsmArray = new CLRDATA_ADDRESS[dadd.AssemblyCount];
if (pAsmArray==NULL)
{
ReportOOM();
return NULL;
}
if (g_sos->GetAssemblyList(dadd.AppDomainPtr,dadd.AssemblyCount,pAsmArray, NULL)!=S_OK)
{
ExtOut("Unable to get array of Assemblies\n");
return NULL;
}
for (LONG n = 0; n < dadd.AssemblyCount; n ++)
{
if (IsInterrupt())
return NULL;
if (AssemblyPtr == pAsmArray[n])
{
if (appDomain != NULL)
{
// We have found more than one AppDomain that loaded this
// assembly, we must return NULL.
return NULL;
}
appDomain = dadd.AppDomainPtr;
}
}
}
}
return appDomain;
}
CLRDATA_ADDRESS GetAppDomainForMT(CLRDATA_ADDRESS mtPtr)
{
DacpMethodTableData mt;
if (mt.Request(g_sos, mtPtr) != S_OK)
{
return NULL;
}
DacpModuleData module;
if (module.Request(g_sos, mt.Module) != S_OK)
{
return NULL;
}
DacpAssemblyData assembly;
if (assembly.Request(g_sos, module.Assembly) != S_OK)
{
return NULL;
}
DacpAppDomainStoreData adstore;
if (adstore.Request(g_sos) != S_OK)
{
return NULL;
}
return (assembly.ParentDomain == adstore.sharedDomain) ?
IsInOneDomainOnly(assembly.AssemblyPtr) :
assembly.ParentDomain;
}
CLRDATA_ADDRESS GetAppDomain(CLRDATA_ADDRESS objPtr)
{
CLRDATA_ADDRESS appDomain = NULL;
DacpObjectData objData;
if (objData.Request(g_sos,objPtr) != S_OK)
{
return NULL;
}
// First check eeclass->module->assembly->domain.
// Then check the object flags word
// finally, search threads for a reference to the object, and look at the thread context.
DacpMethodTableData mt;
if (mt.Request(g_sos,objData.MethodTable) != S_OK)
{
return NULL;
}
DacpModuleData module;
if (module.Request(g_sos,mt.Module) != S_OK)
{
return NULL;
}
DacpAssemblyData assembly;
if (assembly.Request(g_sos,module.Assembly) != S_OK)
{
return NULL;
}
DacpAppDomainStoreData adstore;
if (adstore.Request(g_sos) != S_OK)
{
return NULL;
}
if (assembly.ParentDomain == adstore.sharedDomain)
{
sos::Object obj(TO_TADDR(objPtr));
ULONG value = 0;
if (!obj.TryGetHeader(value))
{
return NULL;
}
DWORD adIndex = (value >> SBLK_APPDOMAIN_SHIFT) & SBLK_MASK_APPDOMAININDEX;
if ( ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0) || adIndex==0)
{
// No AppDomainID information. We'll make use of a heuristic.
// If the assembly is in the shared domain, we can report it as
// being in domain X if the only other domain that has the assembly
// loaded is domain X.
appDomain = IsInOneDomainOnly(assembly.AssemblyPtr);
if (appDomain == NULL && ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0))
{
if ((value & BIT_SBLK_IS_HASHCODE) == 0)
{
UINT index = value & MASK_SYNCBLOCKINDEX;
// We have a syncblock, the appdomain ID may be in there.
DacpSyncBlockData syncBlockData;
if (syncBlockData.Request(g_sos,index) == S_OK)
{
appDomain = syncBlockData.appDomainPtr;
}
}
}
}
else if ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0)
{
size_t AllocSize;
if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), adstore.DomainCount, AllocSize))
{
return NULL;
}
// we know we have a non-zero adIndex. Find the appdomain.
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adstore.DomainCount];
if (pArray==NULL)
{
return NULL;
}
if (g_sos->GetAppDomainList(adstore.DomainCount, pArray, NULL)!=S_OK)
{
return NULL;
}
for (int i = 0; i < adstore.DomainCount; i++)
{
DacpAppDomainData dadd;
if (dadd.Request(g_sos, pArray[i]) != S_OK)
{
return NULL;
}
if (dadd.dwId == adIndex)
{
appDomain = pArray[i];
break;
}
}
}
}
else
{
appDomain = assembly.ParentDomain;
}
return appDomain;
}
HRESULT FileNameForModule (DWORD_PTR pModuleAddr, __out_ecount (MAX_LONGPATH) WCHAR *fileName)
{
DacpModuleData ModuleData;
fileName[0] = L'\0';
HRESULT hr = ModuleData.Request(g_sos, TO_CDADDR(pModuleAddr));
if (SUCCEEDED(hr))
{
hr = FileNameForModule(&ModuleData,fileName);
}
return hr;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find the file name given a Module. *
* *
\**********************************************************************/
// fileName should be at least MAX_LONGPATH
HRESULT FileNameForModule(const DacpModuleData* const pModuleData, __out_ecount(MAX_LONGPATH) WCHAR* fileName)
{
fileName[0] = W('\0');
HRESULT hr = S_OK;
CLRDATA_ADDRESS dwAddr = pModuleData->File;
if (dwAddr == 0)
{
// TODO: We have dynamic module
return E_NOTIMPL;
}
CLRDATA_ADDRESS base = 0;
hr = g_sos->GetPEFileBase(dwAddr, &base);
if (SUCCEEDED(hr))
{
hr = g_sos->GetPEFileName(dwAddr, MAX_LONGPATH, fileName, NULL);
if (SUCCEEDED(hr) && fileName[0] != W('\0'))
return hr; // done
#ifndef FEATURE_PAL
// Try the base *
if (base)
{
hr = DllsName((ULONG_PTR)base, fileName);
if (SUCCEEDED(hr) && fileName[0] != W('\0'))
return hr; // done
}
#endif // !FEATURE_PAL
}
ToRelease<IXCLRDataModule> pModule;
if (SUCCEEDED(g_sos->GetModule(pModuleData->Address, &pModule)))
{
ULONG32 nameLen = 0;
hr = pModule->GetFileName(MAX_LONGPATH, &nameLen, fileName);
}
return hr;
}
void AssemblyInfo(DacpAssemblyData *pAssembly)
{
ExtOut("ClassLoader: %p\n", SOS_PTR(pAssembly->ClassLoader));
if ((ULONG64)pAssembly->AssemblySecDesc != NULL)
ExtOut("SecurityDescriptor: %p\n", SOS_PTR(pAssembly->AssemblySecDesc));
ExtOut(" Module\n");
ArrayHolder<CLRDATA_ADDRESS> Modules = new CLRDATA_ADDRESS[pAssembly->ModuleCount];
if (Modules == NULL
|| g_sos->GetAssemblyModuleList(pAssembly->AssemblyPtr, pAssembly->ModuleCount, Modules, NULL) != S_OK)
{
ReportOOM();
return;
}
for (UINT n = 0; n < pAssembly->ModuleCount; n++)
{
if (IsInterrupt())
{
return;
}
CLRDATA_ADDRESS ModuleAddr = Modules[n];
DMLOut(" %s " WIN86_8SPACES, DMLModule(ModuleAddr));
DacpModuleData moduleData;
if (moduleData.Request(g_sos, ModuleAddr) == S_OK)
{
WCHAR fileName[MAX_LONGPATH];
FileNameForModule (&moduleData, fileName);
if (fileName[0])
{
ExtOut("%S\n", fileName);
}
else
{
ExtOut("%S\n", (moduleData.bIsReflection) ? W("Dynamic Module") : W("Unknown Module"));
}
}
else
{
ExtOut("Request module data FAILED\n");
}
}
}
const char *GetStageText(DacpAppDomainDataStage stage)
{
switch(stage)
{
case STAGE_CREATING:
return "CREATING";
case STAGE_READYFORMANAGEDCODE:
return "READYFORMANAGEDCODE";
case STAGE_ACTIVE:
return "ACTIVE";
case STAGE_OPEN:
return "OPEN";
case STAGE_UNLOAD_REQUESTED:
return "UNLOAD_REQUESTED";
case STAGE_EXITING:
return "EXITING";
case STAGE_EXITED:
return "EXITED";
case STAGE_FINALIZING:
return "FINALIZING";
case STAGE_FINALIZED:
return "FINALIZED";
case STAGE_HANDLETABLE_NOACCESS:
return "HANDLETABLE_NOACCESS";
case STAGE_CLEARED:
return "CLEARED";
case STAGE_COLLECTED:
return "COLLECTED";
case STAGE_CLOSED:
return "CLOSED";
}
return "UNKNOWN";
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to dump the contents of a domain. *
* *
\**********************************************************************/
void DomainInfo (DacpAppDomainData *pDomain)
{
ExtOut("LowFrequencyHeap: %p\n", SOS_PTR(pDomain->pLowFrequencyHeap));
ExtOut("HighFrequencyHeap: %p\n", SOS_PTR(pDomain->pHighFrequencyHeap));
ExtOut("StubHeap: %p\n", SOS_PTR(pDomain->pStubHeap));
ExtOut("Stage: %s\n", GetStageText(pDomain->appDomainStage));
if ((ULONG64)pDomain->AppSecDesc != NULL)
ExtOut("SecurityDescriptor: %p\n", SOS_PTR(pDomain->AppSecDesc));
ExtOut("Name: ");
if (g_sos->GetAppDomainName(pDomain->AppDomainPtr, mdNameLen, g_mdName, NULL)!=S_OK)
{
ExtOut("Error getting AppDomain friendly name\n");
}
else
{
ExtOut("%S\n", (g_mdName[0] != L'\0') ? g_mdName : W("None"));
}
if (pDomain->AssemblyCount == 0)
return;
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[pDomain->AssemblyCount];
if (pArray==NULL)
{
ReportOOM();
return;
}
if (g_sos->GetAssemblyList(pDomain->AppDomainPtr,pDomain->AssemblyCount,pArray, NULL)!=S_OK)
{
ExtOut("Unable to get array of Assemblies\n");
return;
}
LONG n;
// Assembly vAssembly;
for (n = 0; n < pDomain->AssemblyCount; n ++)
{
if (IsInterrupt())
return;
if (n != 0)
ExtOut("\n");
DMLOut("Assembly: %s", DMLAssembly(pArray[n]));
DacpAssemblyData assemblyData;
if (assemblyData.Request(g_sos, pArray[n], pDomain->AppDomainPtr) == S_OK)
{
if (assemblyData.isDynamic)
ExtOut(" (Dynamic)");
ExtOut(" [");
if (g_sos->GetAssemblyName(pArray[n], mdNameLen, g_mdName, NULL) == S_OK)
ExtOut("%S", g_mdName);
ExtOut("]\n");
AssemblyInfo(&assemblyData);
}
}
ExtOut("\n");
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find the name of a MethodDesc using *
* metadata API. *
* *
\**********************************************************************/
BOOL NameForMD_s (DWORD_PTR pMD, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName)
{
mdName[0] = L'\0';
CLRDATA_ADDRESS StartAddr = TO_CDADDR(pMD);
DacpMethodDescData MethodDescData;
// don't need to check for minidump file as all commands are seals
// We also do not have EEJitManager to validate anyway.
//
if (!IsMiniDumpFile() && MethodDescData.Request(g_sos,StartAddr) != S_OK)
{
ExtOut("%p is not a MethodDesc\n", SOS_PTR(StartAddr));
return FALSE;
}
if (g_sos->GetMethodDescName(StartAddr, mdNameLen, mdName, NULL) != S_OK)
{
wcscpy_s(mdName, capacity_mdName, W("UNKNOWN"));
return FALSE;
}
return TRUE;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find the name of a MethodTable using *
* metadata API. *
* *
\**********************************************************************/
BOOL NameForMT_s(DWORD_PTR MTAddr, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName)
{
HRESULT hr = g_sos->GetMethodTableName(TO_CDADDR(MTAddr), (ULONG32)capacity_mdName, mdName, NULL);
return SUCCEEDED(hr);
}
WCHAR *CreateMethodTableName(TADDR mt, TADDR cmt)
{
bool array = false;
WCHAR *res = NULL;
if (mt == sos::MethodTable::GetFreeMT())
{
res = new WCHAR[5];
wcscpy_s(res, 5, W("Free"));
return res;
}
if (mt == sos::MethodTable::GetArrayMT() && cmt != NULL)
{
mt = cmt;
array = true;
}
unsigned int needed = 0;
HRESULT hr = g_sos->GetMethodTableName(mt, 0, NULL, &needed);
// If failed, we will return null.
if (SUCCEEDED(hr))
{
// +2 for [], if we need it.
res = new WCHAR[needed+2];
hr = g_sos->GetMethodTableName(mt, needed, res, NULL);
if (FAILED(hr))
{
delete [] res;
res = NULL;
}
else if (array)
{
res[needed-1] = '[';
res[needed] = ']';
res[needed+1] = 0;
}
}
return res;
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if str2 is a substring of str1 and str1 and str2 *
* share the same file path.
* *
\**********************************************************************/
BOOL IsSameModuleName (const char *str1, const char *str2)
{
if (strlen (str1) < strlen (str2))
return FALSE;
const char *ptr1 = str1 + strlen(str1)-1;
const char *ptr2 = str2 + strlen(str2)-1;
while (ptr2 >= str2)
{
#ifndef FEATURE_PAL
if (tolower(*ptr1) != tolower(*ptr2))
#else
if (*ptr1 != *ptr2)
#endif
{
return FALSE;
}
ptr2--;
ptr1--;
}
if (ptr1 >= str1 && *ptr1 != GetTargetDirectorySeparatorW() && *ptr1 != ':')
{
return FALSE;
}
return TRUE;
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if moduleAddr is the address of a module. *
* *
\**********************************************************************/
BOOL IsModule (DWORD_PTR moduleAddr)
{
DacpModuleData module;
return (module.Request(g_sos, TO_CDADDR(moduleAddr))==S_OK);
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if value is the address of a MethodTable. *
* We verify that MethodTable and EEClass are right.
* *
\**********************************************************************/
BOOL IsMethodTable (DWORD_PTR value)
{
DacpMethodTableData mtabledata;
if (mtabledata.Request(g_sos, TO_CDADDR(value))!=S_OK)
{
return FALSE;
}
return TRUE;
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if value is the address of a MethodDesc. *
* We verify that MethodTable and EEClass are right.
* *
\**********************************************************************/
BOOL IsMethodDesc (DWORD_PTR value)
{
// Just by retrieving one successfully from the DAC, we know we have a MethodDesc.
DacpMethodDescData MethodDescData;
if (MethodDescData.Request(g_sos, TO_CDADDR(value)) != S_OK)
{
return FALSE;
}
return TRUE;
}
DacpUsefulGlobalsData g_special_usefulGlobals;
BOOL IsObjectArray (DacpObjectData *pData)
{
if (pData->ObjectType == OBJ_ARRAY)
return g_special_usefulGlobals.ArrayMethodTable == pData->MethodTable;
return FALSE;
}
BOOL IsObjectArray (DWORD_PTR obj)
{
DWORD_PTR mtAddr = NULL;
if (SUCCEEDED(GetMTOfObject(obj, &mtAddr)))
return TO_TADDR(g_special_usefulGlobals.ArrayMethodTable) == mtAddr;
return FALSE;
}
BOOL IsStringObject (size_t obj)
{
DWORD_PTR mtAddr = NULL;
if (SUCCEEDED(GetMTOfObject(obj, &mtAddr)))
return TO_TADDR(g_special_usefulGlobals.StringMethodTable) == mtAddr;
return FALSE;
}
BOOL IsDerivedFrom(CLRDATA_ADDRESS mtObj, __in_z LPCWSTR baseString)
{
DacpMethodTableData dmtd;
CLRDATA_ADDRESS walkMT = mtObj;
while (walkMT != NULL)
{
if (dmtd.Request(g_sos, walkMT) != S_OK)
{
break;
}
NameForMT_s(TO_TADDR(walkMT), g_mdName, mdNameLen);
if (_wcscmp(baseString, g_mdName) == 0)
{
return TRUE;
}
walkMT = dmtd.ParentMethodTable;
}
return FALSE;
}
BOOL IsDerivedFrom(CLRDATA_ADDRESS mtObj, DWORD_PTR modulePtr, mdTypeDef typeDef)
{
DacpMethodTableData dmtd;
for (CLRDATA_ADDRESS walkMT = mtObj;
walkMT != NULL && dmtd.Request(g_sos, walkMT) == S_OK;
walkMT = dmtd.ParentMethodTable)
{
if (dmtd.Module == modulePtr && dmtd.cl == typeDef)
{
return TRUE;
}
}
return FALSE;
}
BOOL TryGetMethodDescriptorForDelegate(CLRDATA_ADDRESS delegateAddr, CLRDATA_ADDRESS* pMD)
{
if (!sos::IsObject(delegateAddr, false))
{
return FALSE;
}
sos::Object delegateObj = TO_TADDR(delegateAddr);
for (int i = 0; i < 2; i++)
{
int offset;
if ((offset = GetObjFieldOffset(delegateObj.GetAddress(), delegateObj.GetMT(), i == 0 ? W("_methodPtrAux") : W("_methodPtr"))) != 0)
{
CLRDATA_ADDRESS methodPtr;
MOVE(methodPtr, delegateObj.GetAddress() + offset);
if (methodPtr != NULL)
{
if (g_sos->GetMethodDescPtrFromIP(methodPtr, pMD) == S_OK)
{
return TRUE;
}
DacpCodeHeaderData codeHeaderData;
if (codeHeaderData.Request(g_sos, methodPtr) == S_OK)
{
*pMD = codeHeaderData.MethodDescPtr;
return TRUE;
}
}
}
}
return FALSE;
}
void DumpStackObjectsOutput(const char *location, DWORD_PTR objAddr, BOOL verifyFields)
{
// rule out pointers that are outside of the gc heap.
if (g_snapshot.GetHeap(objAddr) == NULL)
return;
DacpObjectData objectData;
if (objectData.Request(g_sos, TO_CDADDR(objAddr)) != S_OK)
return;
if (sos::IsObject(objAddr, verifyFields != FALSE)
&& !sos::MethodTable::IsFreeMT(TO_TADDR(objectData.MethodTable)))
{
DMLOut("%-" POINTERSIZE "s %s ", location, DMLObject(objAddr));
if (g_sos->GetObjectClassName(TO_CDADDR(objAddr), mdNameLen, g_mdName, NULL)==S_OK)
{
ExtOut("%S", g_mdName);
if (IsStringObject(objAddr))
{
ExtOut(" ");
StringObjectContent(objAddr, FALSE, 40);
}
else if (IsObjectArray(objAddr) &&
(g_sos->GetMethodTableName(objectData.ElementTypeHandle, mdNameLen, g_mdName, NULL) == S_OK))
{
ExtOut(" ");
ExtOut("(%S[])", g_mdName);
}
}
else
{
ExtOut("<unknown type>");
}
ExtOut("\n");
}
}
void DumpStackObjectsOutput(DWORD_PTR ptr, DWORD_PTR objAddr, BOOL verifyFields)
{
char location[64];
sprintf_s(location, 64, "%p", (DWORD_PTR *)ptr);
DumpStackObjectsOutput(location, objAddr, verifyFields);
}
void DumpStackObjectsInternal(size_t StackTop, size_t StackBottom, BOOL verifyFields)
{
for (DWORD_PTR ptr = StackTop; ptr <= StackBottom; ptr += sizeof(DWORD_PTR))
{
if (IsInterrupt())
return;
DWORD_PTR objAddr;
move_xp(objAddr, ptr);
DumpStackObjectsOutput(ptr, objAddr, verifyFields);
}
}
void DumpRegObjectHelper(const char *regName, BOOL verifyFields)
{
DWORD_PTR reg;
#ifdef FEATURE_PAL
if (FAILED(g_ExtRegisters->GetValueByName(regName, ®)))
return;
#else
DEBUG_VALUE value;
ULONG IREG;
if (FAILED(g_ExtRegisters->GetIndexByName(regName, &IREG)) ||
FAILED(g_ExtRegisters->GetValue(IREG, &value)))
return;
#if defined(SOS_TARGET_X86) || defined(SOS_TARGET_ARM)
reg = (DWORD_PTR) value.I32;
#elif defined(SOS_TARGET_AMD64) || defined(SOS_TARGET_ARM64)
reg = (DWORD_PTR) value.I64;
#else
#error Unsupported target
#endif
#endif // FEATURE_PAL
DumpStackObjectsOutput(regName, reg, verifyFields);
}
void DumpStackObjectsHelper (
TADDR StackTop,
TADDR StackBottom,
BOOL verifyFields)
{
ExtOut(g_targetMachine->GetDumpStackObjectsHeading());
LPCSTR* regs;
unsigned int cnt;
g_targetMachine->GetGCRegisters(®s, &cnt);
for (size_t i = 0; i < cnt; ++i)
DumpRegObjectHelper(regs[i], verifyFields);
// Make certain StackTop is dword aligned:
DumpStackObjectsInternal(StackTop & ~ALIGNCONST, StackBottom, verifyFields);
}
void AddToModuleList(DWORD_PTR * &moduleList, int &numModule, int &maxList,
DWORD_PTR dwModuleAddr)
{
int i;
for (i = 0; i < numModule; i ++)
{
if (moduleList[i] == dwModuleAddr)
break;
}
if (i == numModule)
{
moduleList[numModule] = dwModuleAddr;
numModule ++;
if (numModule == maxList)
{
int listLength = 0;
if (!ClrSafeInt<int>::multiply(maxList, 2, listLength))
{
ExtOut("<integer overflow>\n");
numModule = 0;
ControlC = 1;
return;
}
DWORD_PTR *list = new DWORD_PTR [listLength];
if (list == NULL)
{
numModule = 0;
ControlC = 1;
return;
}
memcpy (list, moduleList, maxList * sizeof(PVOID));
delete[] moduleList;
moduleList = list;
maxList *= 2;
}
}
}
BOOL IsFusionLoadedModule (LPCSTR fusionName, LPCSTR mName)
{
// The fusion name will be in this format:
// <module name>, Version=<version>, Culture=<culture>, PublicKeyToken=<token>
// If fusionName up to the comma matches mName (case insensitive),
// we consider that a match was found.
LPCSTR commaPos = strchr (fusionName, ',');
if (commaPos)
{
// verify that fusionName and mName match up to a comma.
while (*fusionName != ',')
{
if (*mName == '\0')
{
return FALSE;
}
#ifndef FEATURE_PAL
if (tolower(*fusionName) != tolower(*mName))
#else
if (*fusionName != *mName)
#endif
{
return FALSE;
}
fusionName++;
mName++;
}
return TRUE;
}
return FALSE;
}
BOOL DebuggerModuleNamesMatch (CLRDATA_ADDRESS PEFileAddr, ___in __in_z LPSTR mName)
{
// Another way to see if a module is the same is
// to accept that mName may be the debugger's name for
// a loaded module. We can get the debugger's name for
// the module we are looking at right now, and compare
// it with mName, if they match exactly, we can add
// the module to the list.
if (PEFileAddr)
{
CLRDATA_ADDRESS pebase = 0;
if (g_sos->GetPEFileBase(PEFileAddr, &pebase) == S_OK)
{
if (pebase)
{
ULONG Index;
ULONG64 base;
if (g_ExtSymbols->GetModuleByOffset(pebase, 0, &Index, &base) == S_OK)
{
CHAR ModuleName[MAX_LONGPATH+1];
if (g_ExtSymbols->GetModuleNames(Index, base, NULL, 0, NULL, ModuleName,
MAX_LONGPATH, NULL, NULL, 0, NULL) == S_OK)
{
if (_stricmp (ModuleName, mName) == 0)
{
return TRUE;
}
}
}
}
}
}
return FALSE;
}
DWORD_PTR *ModuleFromName(__in_opt LPSTR mName, int *numModule)
{
if (numModule == NULL)
return NULL;
DWORD_PTR *moduleList = NULL;
*numModule = 0;
HRESULT hr;
DacpAppDomainStoreData adsData;
if ((hr = adsData.Request(g_sos)) != S_OK)
{
ExtDbgOut("DacpAppDomainStoreData.Request FAILED %08x\n", hr);
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pAssemblyArray = NULL;
ArrayHolder<CLRDATA_ADDRESS> pModules = NULL;
int arrayLength = 0;
int numSpecialDomains = (adsData.sharedDomain != NULL) ? 2 : 1;
if (!ClrSafeInt<int>::addition(adsData.DomainCount, numSpecialDomains, arrayLength))
{
ExtOut("<integer overflow>\n");
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[arrayLength];
if (pArray == NULL)
{
ReportOOM();
return NULL;
}
pArray[0] = adsData.systemDomain;
if (adsData.sharedDomain != NULL)
{
pArray[1] = adsData.sharedDomain;
}
if ((hr = g_sos->GetAppDomainList(adsData.DomainCount, pArray.GetPtr() + numSpecialDomains, NULL)) != S_OK)
{
ExtOut("Unable to get array of AppDomains: %08x\n", hr);
return NULL;
}
// List all domain
size_t AllocSize;
int maxList = arrayLength; // account for system and shared domains
if (maxList <= 0 || !ClrSafeInt<size_t>::multiply(maxList, sizeof(PVOID), AllocSize))
{
ExtOut("<integer overflow>\n");
return NULL;
}
moduleList = new DWORD_PTR[maxList];
if (moduleList == NULL)
{
ReportOOM();
return NULL;
}
ArrayHolder<char> fileName = new char[MAX_LONGPATH];
// Search all domains to find a module
for (int n = 0; n < adsData.DomainCount+numSpecialDomains; n++)
{
if (IsInterrupt())
{
ExtOut("<interrupted>\n");
goto Failure;
}
DacpAppDomainData appDomain;
if (FAILED(hr = appDomain.Request(g_sos, pArray[n])))
{
// Don't print a failure message here, there is a very normal case when checking
// for modules after clr is loaded but before any AppDomains or assemblies are created
// for example:
// >sxe ld:clr
// >g
// ...
// ModLoad: runtime dll
// >!bpmd Foo.dll Foo.Bar
// we will correctly give the answer that whatever module you were looking for, it isn't loaded yet
ExtDbgOut("DacpAppDomainData.Request FAILED %08x\n", hr);
goto Failure;
}
if (appDomain.AssemblyCount)
{
pAssemblyArray = new CLRDATA_ADDRESS[appDomain.AssemblyCount];
if (pAssemblyArray==NULL)
{
ReportOOM();
goto Failure;
}
if (FAILED(hr = g_sos->GetAssemblyList(appDomain.AppDomainPtr, appDomain.AssemblyCount, pAssemblyArray, NULL)))
{
ExtOut("Unable to get array of Assemblies for the given AppDomain: %08x\n", hr);
goto Failure;
}
for (int nAssem = 0; nAssem < appDomain.AssemblyCount; nAssem ++)
{
if (IsInterrupt())
{
ExtOut("<interrupted>\n");
goto Failure;
}
DacpAssemblyData assemblyData;
if (FAILED(hr = assemblyData.Request(g_sos, pAssemblyArray[nAssem])))
{
ExtOut("Failed to request assembly: %08x\n", hr);
goto Failure;
}
pModules = new CLRDATA_ADDRESS[assemblyData.ModuleCount];
if (FAILED(hr = g_sos->GetAssemblyModuleList(assemblyData.AssemblyPtr, assemblyData.ModuleCount, pModules, NULL)))
{
ExtOut("Failed to get the modules for the given assembly: %08x\n", hr);
goto Failure;
}
for (UINT nModule = 0; nModule < assemblyData.ModuleCount; nModule++)
{
if (IsInterrupt())
{
ExtOut("<interrupted>\n");
goto Failure;
}
CLRDATA_ADDRESS ModuleAddr = pModules[nModule];
DacpModuleData ModuleData;
if (FAILED(hr = ModuleData.Request(g_sos, ModuleAddr)))
{
ExtDbgOut("Failed to request module data from assembly at %p %08x\n", ModuleAddr, hr);
continue;
}
if (mName != NULL)
{
ArrayHolder<WCHAR> moduleName = new WCHAR[MAX_LONGPATH];
FileNameForModule(&ModuleData, moduleName);
int bytesWritten = WideCharToMultiByte(CP_ACP, 0, moduleName, -1, fileName, MAX_LONGPATH, NULL, NULL);
_ASSERTE(bytesWritten > 0);
}
if ((mName == NULL) ||
IsSameModuleName(fileName, mName) ||
DebuggerModuleNamesMatch(ModuleData.File, mName) ||
IsFusionLoadedModule(fileName, mName))
{
AddToModuleList(moduleList, *numModule, maxList, (DWORD_PTR)ModuleAddr);
}
}
pModules = NULL;
}
pAssemblyArray = NULL;
}
}
return moduleList;
// We do not want to return a half-constructed list. Instead, we return NULL on a failure.
Failure:
delete [] moduleList;
return NULL;
}
#ifndef FEATURE_PAL
/**********************************************************************\
* Routine Description: *
* *
* Retrieve module base associated with the IXCLRDataModule *
* instance passed in, and the extent type requested. *
* *
\**********************************************************************/
HRESULT GetClrModuleImages(__in IXCLRDataModule* module, __in CLRDataModuleExtentType desiredType, __out PULONG64 pBase, __out PULONG64 pSize)
{
CLRDATA_ENUM enumExtents;
HRESULT hr;
_ASSERTE(pBase != nullptr);
_ASSERTE(pSize != nullptr);
*pBase = 0;
*pSize = 0;
if (FAILED(hr = module->StartEnumExtents(&enumExtents)))
{
return hr;
}
CLRDATA_MODULE_EXTENT extent;
while (module->EnumExtent(&enumExtents, &extent) == S_OK)
{
if ((desiredType == CLRDATA_MODULE_OTHER) || (desiredType == extent.type))
{
ULONG64 moduleBase;
if (FAILED(hr = g_ExtSymbols->GetModuleByOffset(extent.base, 0, nullptr, &moduleBase)))
{
if (desiredType == CLRDATA_MODULE_PE_FILE)
{
*pBase = extent.base;
*pSize = extent.length;
hr = S_OK;
}
break;
}
DEBUG_MODULE_PARAMETERS params;
if (FAILED(hr = g_ExtSymbols->GetModuleParameters(1, &moduleBase, 0, ¶ms)))
{
break;
}
*pBase = moduleBase;
*pSize = params.Size;
hr = S_OK;
break;
}
}
module->EndEnumExtents(enumExtents);
return hr;
}
#endif // FEATURE_PAL
/**********************************************************************\
* Routine Description: *
* *
* Find the IXCLRDataModule instance for the base address. *
* *
\**********************************************************************/
HRESULT GetModuleFromAddress(___in CLRDATA_ADDRESS peAddress, ___out IXCLRDataModule** ppModule)
{
*ppModule = nullptr;
int numModule;
ArrayHolder<DWORD_PTR> moduleList = ModuleFromName(NULL, &numModule);
if (moduleList != nullptr)
{
for (int i = 0; i < numModule; i++)
{
ToRelease<IXCLRDataModule> module;
HRESULT hr = g_sos->GetModule(moduleList[i], &module);
if (FAILED(hr)) {
return hr;
}
ULONG32 flags;
if ((hr = module->GetFlags(&flags)) != S_OK) {
continue;
}
if ((flags & (CLRDATA_MODULE_IS_DYNAMIC | CLRDATA_MODULE_IS_MEMORY_STREAM)) != 0) {
continue;
}
DacpGetModuleData moduleData;
hr = moduleData.Request(module);
if (FAILED(hr)) {
#ifdef FEATURE_PAL
return hr;
#else
hr = GetClrModuleImages(module, CLRDATA_MODULE_PE_FILE, &moduleData.LoadedPEAddress, &moduleData.LoadedPESize);
if (FAILED(hr))
{
return hr;
}
#endif
}
if (peAddress == moduleData.LoadedPEAddress)
{
*ppModule = module.Detach();
return S_OK;
}
}
}
return E_INVALIDARG;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a name. *
* *
\**********************************************************************/
void GetInfoFromName(DWORD_PTR ModulePtr, const char* name, mdTypeDef* retMdTypeDef)
{
DWORD_PTR ignoredModuleInfoRet = NULL;
if (retMdTypeDef)
*retMdTypeDef = 0;
ToRelease<IMetaDataImport> pImport = MDImportForModule (ModulePtr);
if (pImport == 0)
return;
static WCHAR wszName[MAX_CLASSNAME_LENGTH];
size_t n;
size_t length = strlen (name);
for (n = 0; n <= length; n ++)
wszName[n] = name[n];
// First enumerate methods. We're taking advantage of the DAC's
// CLRDataModule::EnumMethodDefinitionByName which can parse
// method names (whether in nested classes, or explicit interface
// method implementations).
ToRelease<IXCLRDataModule> ModuleDefinition;
if (g_sos->GetModule(ModulePtr, &ModuleDefinition) == S_OK)
{
CLRDATA_ENUM h;
if (ModuleDefinition->StartEnumMethodDefinitionsByName(wszName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
BOOL fStatus = FALSE;
while (ModuleDefinition->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
if (fStatus && !retMdTypeDef)
ExtOut("-----------------------\n");
mdTypeDef token;
if (pMeth->GetTokenAndScope(&token, NULL) == S_OK)
{
GetInfoFromModule(ModulePtr, token, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
fStatus = TRUE;
}
pMeth->Release();
}
ModuleDefinition->EndEnumMethodDefinitionsByName(h);
if (fStatus)
return;
}
}
// Now look for types, type members and fields
mdTypeDef cl;
mdToken tkEnclose = mdTokenNil;
WCHAR *pName;
WCHAR *pHead = wszName;
while ( ((pName = _wcschr (pHead,L'+')) != NULL) ||
((pName = _wcschr (pHead,L'/')) != NULL)) {
pName[0] = L'\0';
if (FAILED(pImport->FindTypeDefByName(pHead,tkEnclose,&tkEnclose)))
return;
pHead = pName+1;
}
pName = pHead;
// @todo: Handle Nested classes correctly.
if (SUCCEEDED (pImport->FindTypeDefByName (pName, tkEnclose, &cl)))
{
if (retMdTypeDef)
*retMdTypeDef = cl;
GetInfoFromModule(ModulePtr, cl, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
return;
}
// See if it is a method
WCHAR *pwzMethod;
if ((pwzMethod = _wcsrchr(pName, L'.')) == NULL)
return;
if (pwzMethod[-1] == L'.')
pwzMethod --;
pwzMethod[0] = L'\0';
pwzMethod ++;
// @todo: Handle Nested classes correctly.
if (SUCCEEDED(pImport->FindTypeDefByName (pName, tkEnclose, &cl)))
{
if (retMdTypeDef)
*retMdTypeDef = cl;
mdMethodDef token;
ULONG cTokens;
HCORENUM henum = NULL;
// is Member?
henum = NULL;
if (SUCCEEDED (pImport->EnumMembersWithName (&henum, cl, pwzMethod,
&token, 1, &cTokens))
&& cTokens == 1)
{
if (!retMdTypeDef) ExtOut("Member (mdToken token) of\n");
GetInfoFromModule(ModulePtr, cl, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
return;
}
// is Field?
henum = NULL;
if (SUCCEEDED (pImport->EnumFieldsWithName (&henum, cl, pwzMethod,
&token, 1, &cTokens))
&& cTokens == 1)
{
if (!retMdTypeDef) ExtOut("Field (mdToken token) of\n");
GetInfoFromModule(ModulePtr, cl, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
return;
}
}
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a token. *
* *
\**********************************************************************/
DWORD_PTR GetMethodDescFromModule(DWORD_PTR ModuleAddr, ULONG token)
{
if (TypeFromToken(token) != mdtMethodDef)
return NULL;
CLRDATA_ADDRESS md = 0;
if (FAILED(g_sos->GetMethodDescFromToken(ModuleAddr, token, &md)))
{
return NULL;
}
else if (0 == md)
{
// a NULL ReturnValue means the method desc is not loaded yet
return MD_NOT_YET_LOADED;
}
else if ( !IsMethodDesc((DWORD_PTR)md))
{
return NULL;
}
return (DWORD_PTR)md;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the MethodDefinitions given a name. *
* *
\**********************************************************************/
HRESULT GetMethodDefinitionsFromName(TADDR ModulePtr, IXCLRDataModule* mod, const char *name, IXCLRDataMethodDefinition **ppOut, int numMethods, int *numMethodsNeeded)
{
if (name == NULL)
return E_FAIL;
size_t n;
size_t length = strlen (name);
for (n = 0; n <= length; n ++)
g_mdName[n] = name[n];
CLRDATA_ENUM h;
int methodCount = 0;
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
methodCount++;
pMeth->Release();
}
mod->EndEnumMethodDefinitionsByName(h);
}
if(numMethodsNeeded != NULL)
*numMethodsNeeded = methodCount;
if(ppOut == NULL)
return S_OK;
if(numMethods > methodCount)
numMethods = methodCount;
if (methodCount > 0)
{
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
for (int i = 0; i < numMethods && mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK; i++)
{
ppOut[i] = pMeth;
}
mod->EndEnumMethodDefinitionsByName(h);
}
}
return S_OK;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a name. *
* *
\**********************************************************************/
HRESULT GetMethodDescsFromName(TADDR ModulePtr, IXCLRDataModule* mod, const char *name, DWORD_PTR **pOut,int *numMethods)
{
if (name == NULL || pOut == NULL || numMethods == NULL)
return E_FAIL;
*pOut = NULL;
*numMethods = 0;
size_t n;
size_t length = strlen (name);
for (n = 0; n <= length; n ++)
g_mdName[n] = name[n];
CLRDATA_ENUM h;
int methodCount = 0;
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
methodCount++;
pMeth->Release();
}
mod->EndEnumMethodDefinitionsByName(h);
}
if (methodCount > 0)
{
*pOut = new TADDR[methodCount];
if (*pOut==NULL)
{
ReportOOM();
return E_OUTOFMEMORY;
}
*numMethods = methodCount;
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
int i = 0;
IXCLRDataMethodDefinition *pMeth = NULL;
while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
mdTypeDef token;
if (pMeth->GetTokenAndScope(&token, NULL) != S_OK)
(*pOut)[i] = NULL;
(*pOut)[i] = GetMethodDescFromModule(ModulePtr, token);
if ((*pOut)[i] == NULL)
{
*numMethods = 0;
return E_FAIL;
}
i++;
pMeth->Release();
}
mod->EndEnumMethodDefinitionsByName(h);
}
}
return S_OK;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a token. *
* *
\**********************************************************************/
void GetInfoFromModule (DWORD_PTR ModuleAddr, ULONG token, DWORD_PTR *ret)
{
switch (TypeFromToken(token))
{
case mdtMethodDef:
break;
case mdtTypeDef:
break;
case mdtTypeRef:
break;
case mdtFieldDef:
break;
default:
ExtOut("This token type is not supported\n");
return;
break;
}
CLRDATA_ADDRESS md = 0;
if (FAILED(g_sos->GetMethodDescFromToken(ModuleAddr, token, &md)) || !IsValidToken (ModuleAddr, token))
{
ExtOut("<invalid module token>\n");
return;
}
if (ret != NULL)
{
*ret = (DWORD_PTR)md;
return;
}
ExtOut("Token: %p\n", SOS_PTR(token));
switch (TypeFromToken(token))
{
case mdtFieldDef:
{
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
ExtOut("Field name: %S\n", g_mdName);
break;
}
case mdtMethodDef:
{
if (md)
{
DMLOut("MethodDesc: %s\n", DMLMethodDesc(md));
// Easiest to get full parameterized method name from ..::GetMethodName
if (g_sos->GetMethodDescName(md, mdNameLen, g_mdName, NULL) != S_OK)
{
// Fall back to just method name without parameters..
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
}
}
else
{
ExtOut("MethodDesc: <not loaded yet>\n");
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
}
ExtOut("Name: %S\n", g_mdName);
// Nice to have a little more data
if (md)
{
DacpMethodDescData MethodDescData;
if (MethodDescData.Request(g_sos, md) == S_OK)
{
if (MethodDescData.bHasNativeCode)
{
DMLOut("JITTED Code Address: %s\n", DMLIP(MethodDescData.NativeCodeAddr));
}
else
{
#ifndef FEATURE_PAL
if (IsDMLEnabled())
DMLOut("Not JITTED yet. Use <exec cmd=\"!bpmd -md %p\">!bpmd -md %p</exec> to break on run.\n",
SOS_PTR(md), SOS_PTR(md));
else
ExtOut("Not JITTED yet. Use !bpmd -md %p to break on run.\n", SOS_PTR(md));
#else
ExtOut("Not JITTED yet. Use 'bpmd -md %p' to break on run.\n", SOS_PTR(md));
#endif
}
}
else
{
ExtOut ("<Error getting MethodDesc information>\n");
}
}
else
{
ExtOut("Not JITTED yet.\n");
}
break;
}
case mdtTypeDef:
case mdtTypeRef:
{
if (md)
{
DMLOut("MethodTable: %s\n", DMLMethodTable(md));
DacpMethodTableData mtabledata;
if (mtabledata.Request(g_sos, md) == S_OK)
{
DMLOut("EEClass: %s\n", DMLClass(mtabledata.Class));
}
else
{
ExtOut("EEClass: <error getting EEClass>\n");
}
}
else
{
ExtOut("MethodTable: <not loaded yet>\n");
ExtOut("EEClass: <not loaded yet>\n");
}
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
ExtOut("Name: %S\n", g_mdName);
break;
}
default:
break;
}
return;
}
BOOL IsMTForFreeObj(DWORD_PTR pMT)
{
return (pMT == g_special_usefulGlobals.FreeMethodTable);
}
const char *EHTypeName(EHClauseType et)
{
if (et == EHFault)
return "FAULT";
else if (et == EHFinally)
return "FINALLY";
else if (et == EHFilter)
return "FILTER";
else if (et == EHTyped)
return "TYPED";
else
return "UNKNOWN";
}
// 2.x version
void DumpTieredNativeCodeAddressInfo_2x(struct DacpTieredVersionData_2x * pTieredVersionData, const UINT cTieredVersionData)
{
ExtOut("Code Version History:\n");
for(int i = cTieredVersionData - 1; i >= 0; --i)
{
const char *descriptor = NULL;
switch(pTieredVersionData[i].TieredInfo)
{
case DacpTieredVersionData_2x::TIERED_UNKNOWN:
default:
descriptor = "Unknown Tier";
break;
case DacpTieredVersionData_2x::NON_TIERED:
descriptor = "Non-Tiered";
break;
case DacpTieredVersionData_2x::TIERED_0:
descriptor = "Tier 0";
break;
case DacpTieredVersionData_2x::TIERED_1:
descriptor = "Tier 1";
break;
}
DMLOut(" CodeAddr: %s (%s)\n", DMLIP(pTieredVersionData[i].NativeCodeAddr), descriptor);
ExtOut(" NativeCodeVersion: %p\n", SOS_PTR(pTieredVersionData[i].NativeCodeVersionNodePtr));
}
}
void DumpTieredNativeCodeAddressInfo(struct DacpTieredVersionData * pTieredVersionData, const UINT cTieredVersionData,
ULONG rejitID, CLRDATA_ADDRESS ilAddr, CLRDATA_ADDRESS ilNodeAddr)
{
ExtOut(" ILCodeVersion: %p\n", SOS_PTR(ilNodeAddr));
ExtOut(" ReJIT ID: %d\n", rejitID);
DMLOut(" IL Addr: %s\n", DMLIL(ilAddr));
if (IsRuntimeVersionAtLeast(3)) {
for(int i = cTieredVersionData - 1; i >= 0; --i)
{
const char *descriptor = NULL;
switch(pTieredVersionData[i].OptimizationTier)
{
case DacpTieredVersionData::OptimizationTier_Unknown:
default:
descriptor = "Unknown Tier";
break;
case DacpTieredVersionData::OptimizationTier_MinOptJitted:
descriptor = "MinOptJitted";
break;
case DacpTieredVersionData::OptimizationTier_Optimized:
descriptor = "Optimized";
break;
case DacpTieredVersionData::OptimizationTier_QuickJitted:
descriptor = "QuickJitted";
break;
case DacpTieredVersionData::OptimizationTier_OptimizedTier1:
descriptor = "OptimizedTier1";
break;
case DacpTieredVersionData::OptimizationTier_ReadyToRun:
descriptor = "ReadyToRun";
break;
}
DMLOut(" CodeAddr: %s (%s)\n", DMLIP(pTieredVersionData[i].NativeCodeAddr), descriptor);
ExtOut(" NativeCodeVersion: %p\n", SOS_PTR(pTieredVersionData[i].NativeCodeVersionNodePtr));
}
}
else {
DumpTieredNativeCodeAddressInfo_2x((DacpTieredVersionData_2x*)pTieredVersionData, cTieredVersionData);
}
}
void DumpRejitData(CLRDATA_ADDRESS pMethodDesc, DacpReJitData * pReJitData)
{
int rejitID = (int)pReJitData->rejitID;
CLRDATA_ADDRESS ilAddr = 0;
CLRDATA_ADDRESS ilNodeAddr = 0;
struct DacpReJitData2 rejitData;
ReleaseHolder<ISOSDacInterface7> sos7;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface7), &sos7)) &&
SUCCEEDED(sos7->GetReJITInformation(pMethodDesc,
rejitID,
&rejitData)))
{
ilAddr = rejitData.il;
ilNodeAddr = rejitData.ilCodeVersionNodePtr;
}
struct DacpTieredVersionData codeAddrs[kcMaxTieredVersions];
int cCodeAddrs;
ReleaseHolder<ISOSDacInterface5> sos5;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface5), &sos5)) &&
SUCCEEDED(sos5->GetTieredVersions(pMethodDesc,
rejitID,
codeAddrs,
kcMaxTieredVersions,
&cCodeAddrs)))
{
DumpTieredNativeCodeAddressInfo(codeAddrs, cCodeAddrs, rejitID, ilAddr, ilNodeAddr);
}
}
// For !ip2md requests, this function helps us ensure that rejitted version corresponding
// to the specified IP always gets dumped. It may have already been dumped if it was the
// current rejit version (which is always dumped) or one of the reverted versions that we
// happened to dump before we clipped their number down to kcRejitDataRevertedMax.
BOOL ShouldDumpRejitDataRequested(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData)
{
if (pMethodDescData->rejitDataRequested.rejitID == 0)
return FALSE;
if (pMethodDescData->rejitDataRequested.rejitID == pMethodDescData->rejitDataCurrent.rejitID)
return FALSE;
for (ULONG i=0; i < cRevertedRejitData; i++)
{
if (pMethodDescData->rejitDataRequested.rejitID == pRevertedRejitData[i].rejitID)
return FALSE;
}
return TRUE;
}
void DumpAllRejitDataIfNecessary(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData)
{
// If there's no rejit info to output, then skip
if ((pMethodDescData->rejitDataCurrent.rejitID == 0) &&
(pMethodDescData->rejitDataRequested.rejitID == 0) &&
(cRevertedRejitData == 0))
{
return;
}
// Dump reverted rejit infos
for (ULONG i=0; i < cRevertedRejitData; i++)
{
DumpRejitData(pMethodDescData->MethodDescPtr, &pRevertedRejitData[i]);
}
// For !ip2md, ensure we dump the rejit version corresponding to the specified IP
// (if not already dumped)
if (ShouldDumpRejitDataRequested(pMethodDescData, pRevertedRejitData, cRevertedRejitData))
DumpRejitData(pMethodDescData->MethodDescPtr, &pMethodDescData->rejitDataRequested);
// If we maxed out the reverted versions we dumped, let user know there may be more
if (cRevertedRejitData == kcMaxRevertedRejitData)
ExtOut(" (... possibly more reverted versions ...)\n");
}
void DumpMDInfoFromMethodDescData(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData, BOOL fStackTraceFormat)
{
static WCHAR wszNameBuffer[1024]; // should be large enough
BOOL bFailed = FALSE;
if (g_sos->GetMethodDescName(pMethodDescData->MethodDescPtr, 1024, wszNameBuffer, NULL) != S_OK)
{
wcscpy_s(wszNameBuffer, _countof(wszNameBuffer), W("UNKNOWN"));
bFailed = TRUE;
}
if (!fStackTraceFormat)
{
ExtOut("Method Name: %S\n", wszNameBuffer);
DacpMethodTableData mtdata;
if (SUCCEEDED(mtdata.Request(g_sos, pMethodDescData->MethodTablePtr)))
{
DMLOut("Class: %s\n", DMLClass(mtdata.Class));
}
DMLOut("MethodTable: %s\n", DMLMethodTable(pMethodDescData->MethodTablePtr));
ExtOut("mdToken: %p\n", SOS_PTR(pMethodDescData->MDToken));
DMLOut("Module: %s\n", DMLModule(pMethodDescData->ModulePtr));
ExtOut("IsJitted: %s\n", pMethodDescData->bHasNativeCode ? "yes" : "no");
DMLOut("Current CodeAddr: %s\n", DMLIP(pMethodDescData->NativeCodeAddr));
int rejitID = (int)pMethodDescData->rejitDataCurrent.rejitID;
CLRDATA_ADDRESS ilAddr = 0;
CLRDATA_ADDRESS ilNodeAddr = 0;
ExtOut("Version History:\n");
struct DacpReJitData2 rejitData;
ReleaseHolder<ISOSDacInterface7> sos7;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface7), &sos7)))
{
if SUCCEEDED(sos7->GetReJITInformation(pMethodDescData->MethodDescPtr,
rejitID,
&rejitData))
{
ilAddr = rejitData.il;
ilNodeAddr = rejitData.ilCodeVersionNodePtr;
}
int pendingRejitID;
struct DacpReJitData2 pendingRejitData;
if (sos7->GetPendingReJITID(pMethodDescData->MethodDescPtr, &pendingRejitID) == S_OK &&
SUCCEEDED(sos7->GetReJITInformation(pMethodDescData->MethodDescPtr, pendingRejitID, &pendingRejitData)))
{
// Special case, there is no jitted code yet but still need to output the IL information
ExtOut(" ILCodeVersion: %p (pending)\n", SOS_PTR(pendingRejitData.ilCodeVersionNodePtr));
ExtOut(" ReJIT ID: %d\n", pendingRejitID);
DMLOut(" IL Addr: %s\n", DMLIL(pendingRejitData.il));
}
}
struct DacpTieredVersionData codeAddrs[kcMaxTieredVersions];
int cCodeAddrs;
ReleaseHolder<ISOSDacInterface5> sos5;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface5), &sos5)) &&
SUCCEEDED(sos5->GetTieredVersions(pMethodDescData->MethodDescPtr,
rejitID,
codeAddrs,
kcMaxTieredVersions,
&cCodeAddrs)))
{
DumpTieredNativeCodeAddressInfo(codeAddrs, cCodeAddrs, rejitID, ilAddr, ilNodeAddr);
}
DumpAllRejitDataIfNecessary(pMethodDescData, pRevertedRejitData, cRevertedRejitData);
}
else
{
if (!bFailed)
{
ExtOut("%S", wszNameBuffer);
}
else
{
// Only clutter the display with module/token for cases where we
// can't get the MethodDesc name for some reason.
DMLOut("Unknown MethodDesc (Module %s, mdToken %08x)",
DMLModule(pMethodDescData->ModulePtr),
pMethodDescData->MDToken);
}
}
}
void DumpMDInfo(DWORD_PTR dwMethodDescAddr, CLRDATA_ADDRESS dwRequestedIP /* = 0 */, BOOL fStackTraceFormat /* = FALSE */)
{
DacpMethodDescData MethodDescData;
DacpReJitData revertedRejitData[kcMaxRevertedRejitData];
ULONG cNeededRevertedRejitData;
if (g_sos->GetMethodDescData(
TO_CDADDR(dwMethodDescAddr),
dwRequestedIP,
&MethodDescData,
_countof(revertedRejitData),
revertedRejitData,
&cNeededRevertedRejitData) != S_OK)
{
ExtOut("%p is not a MethodDesc\n", SOS_PTR(dwMethodDescAddr));
return;
}
DumpMDInfoFromMethodDescData(&MethodDescData, revertedRejitData, cNeededRevertedRejitData, fStackTraceFormat);
}
void GetDomainList (DWORD_PTR *&domainList, int &numDomain)
{
DacpAppDomainStoreData adsData;
numDomain = 0;
if (adsData.Request(g_sos)!=S_OK)
{
return;
}
// Do prefast integer checks before the malloc.
size_t AllocSize;
LONG DomainAllocCount;
LONG NumExtraDomains = (adsData.sharedDomain != NULL) ? 2 : 1;
if (!ClrSafeInt<LONG>::addition(adsData.DomainCount, NumExtraDomains, DomainAllocCount) ||
!ClrSafeInt<size_t>::multiply(DomainAllocCount, sizeof(PVOID), AllocSize) ||
(domainList = new DWORD_PTR[DomainAllocCount]) == NULL)
{
return;
}
domainList[numDomain++] = (DWORD_PTR) adsData.systemDomain;
if (adsData.sharedDomain != NULL)
{
domainList[numDomain++] = (DWORD_PTR) adsData.sharedDomain;
}
CLRDATA_ADDRESS *pArray = new CLRDATA_ADDRESS[adsData.DomainCount];
if (pArray==NULL)
{
return;
}
if (g_sos->GetAppDomainList(adsData.DomainCount, pArray, NULL)!=S_OK)
{
delete [] pArray;
return;
}
for (int n=0;n<adsData.DomainCount;n++)
{
if (IsInterrupt())
break;
domainList[numDomain++] = (DWORD_PTR) pArray[n];
}
delete [] pArray;
}
HRESULT GetThreadList(DWORD_PTR **threadList, int *numThread)
{
_ASSERTE(threadList != NULL);
_ASSERTE(numThread != NULL);
if (threadList == NULL || numThread == NULL)
{
return E_FAIL;
}
*numThread = 0;
DacpThreadStoreData ThreadStore;
if ( ThreadStore.Request(g_sos) != S_OK)
{
ExtOut("Failed to request threads from the thread store.");
return E_FAIL;
}
*threadList = new DWORD_PTR[ThreadStore.threadCount];
if (*threadList == NULL)
{
ReportOOM();
return E_OUTOFMEMORY;
}
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread != NULL)
{
if (IsInterrupt())
return S_FALSE;
DacpThreadData Thread;
if (Thread.Request(g_sos, CurThread) != S_OK)
{
ExtOut("Failed to request Thread at %p\n", SOS_PTR(CurThread));
return E_FAIL;
}
(*threadList)[(*numThread)++] = (DWORD_PTR)CurThread;
CurThread = Thread.nextThread;
}
return S_OK;
}
CLRDATA_ADDRESS GetCurrentManagedThread ()
{
DacpThreadStoreData ThreadStore;
ThreadStore.Request(g_sos);
ULONG Tid;
g_ExtSystem->GetCurrentThreadSystemId(&Tid);
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread)
{
DacpThreadData Thread;
if (Thread.Request(g_sos, CurThread) != S_OK)
{
return NULL;
}
if (Thread.osThreadId == Tid)
{
return CurThread;
}
CurThread = Thread.nextThread;
}
return NULL;
}
void ReloadSymbolWithLineInfo()
{
_ASSERTE(g_pRuntime != nullptr);
#ifndef FEATURE_PAL
static BOOL bLoadSymbol = FALSE;
if (!bLoadSymbol)
{
ULONG Options;
g_ExtSymbols->GetSymbolOptions(&Options);
if (!(Options & SYMOPT_LOAD_LINES))
{
g_ExtSymbols->AddSymbolOptions(SYMOPT_LOAD_LINES);
if (SUCCEEDED(g_ExtSymbols->GetModuleByModuleName(MSCOREE_SHIM_A, 0, NULL, NULL)))
{
g_ExtSymbols->Reload("/f" MSCOREE_SHIM_A);
}
std::string reloadCommand;
reloadCommand.append("/f ");
reloadCommand.append(GetRuntimeDllName());
g_ExtSymbols->Reload(reloadCommand.c_str());
}
// reload mscoree.pdb and clrjit.pdb to get line info
bLoadSymbol = TRUE;
}
#endif
}
// Return 1 if the function is our stub
// Return MethodDesc if the function is managed
// Otherwise return 0
size_t FunctionType (size_t EIP)
{
ULONG64 base = 0;
ULONG ulLoaded, ulUnloaded, ulIndex;
// Get the number of loaded and unloaded modules
if (FAILED(g_ExtSymbols->GetNumberModules(&ulLoaded, &ulUnloaded)))
return 0;
if (SUCCEEDED(g_ExtSymbols->GetModuleByOffset(TO_CDADDR(EIP), 0, &ulIndex, &base)) && base != 0)
{
if (ulIndex < ulLoaded)
{
IMAGE_DOS_HEADER DosHeader;
if (g_ExtData->ReadVirtual(TO_CDADDR(base), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
return 0;
IMAGE_NT_HEADERS Header;
if (g_ExtData->ReadVirtual(TO_CDADDR(base + DosHeader.e_lfanew), &Header, sizeof(Header), NULL) != S_OK)
return 0;
// If there is no COMHeader, this can not be managed code.
if (Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress == 0)
return 0;
IMAGE_COR20_HEADER ComPlusHeader;
if (g_ExtData->ReadVirtual(TO_CDADDR(base + Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress),
&ComPlusHeader, sizeof(ComPlusHeader), NULL) != S_OK)
return 0;
// If there is no Precompiled image info, it can not be prejit code
if (ComPlusHeader.ManagedNativeHeader.VirtualAddress == 0) {
return 0;
}
}
}
CLRDATA_ADDRESS dwStartAddr = TO_CDADDR(EIP);
CLRDATA_ADDRESS pMD;
if (g_sos->GetMethodDescPtrFromIP(dwStartAddr, &pMD) != S_OK)
{
return 1;
}
return (size_t) pMD;
}
//
// Return true if major runtime version (logical product version like 2.1,
// 3.0 or 5.x). Currently only major versions of 3 or 5 are supported.
//
bool IsRuntimeVersion(DWORD major)
{
VS_FIXEDFILEINFO fileInfo;
if (SUCCEEDED(g_pRuntime->GetEEVersion(&fileInfo, nullptr, 0)))
{
return IsRuntimeVersion(fileInfo, major);
}
return false;
}
bool IsRuntimeVersion(VS_FIXEDFILEINFO& fileInfo, DWORD major)
{
switch (major)
{
case 5:
return HIWORD(fileInfo.dwFileVersionMS) == 5;
case 3:
return HIWORD(fileInfo.dwFileVersionMS) == 4 && LOWORD(fileInfo.dwFileVersionMS) == 700;
default:
_ASSERTE(FALSE);
break;
}
return false;
}
bool IsRuntimeVersionAtLeast(DWORD major)
{
VS_FIXEDFILEINFO fileInfo;
if (SUCCEEDED(g_pRuntime->GetEEVersion(&fileInfo, nullptr, 0)))
{
return IsRuntimeVersionAtLeast(fileInfo, major);
}
return false;
}
bool IsRuntimeVersionAtLeast(VS_FIXEDFILEINFO& fileInfo, DWORD major)
{
switch (major)
{
case 3:
if (HIWORD(fileInfo.dwFileVersionMS) == 4 && LOWORD(fileInfo.dwFileVersionMS) == 700)
{
return true;
}
// fall through
case 5:
if (HIWORD(fileInfo.dwFileVersionMS) >= 5)
{
return true;
}
// fall through
break;
default:
_ASSERTE(FALSE);
break;
}
return false;
}
// Returns true if there is a change in the data structures that SOS depends on like
// stress log structs (StressMsg, StressLogChunck, ThreadStressLog, etc), exception
// stack traces (StackTraceElement), the PredefinedTlsSlots enums, etc.
bool CheckBreakingRuntimeChange(int* pVersion)
{
bool result = false;
// Assume version 1 if no ISOSDacInterface9 (runtimes < 5.0)
int version = 1;
if (g_sos != nullptr)
{
ReleaseHolder<ISOSDacInterface9> sos9;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface9), &sos9)))
{
if (SUCCEEDED(sos9->GetBreakingChangeVersion(&version)))
{
if (version > SOS_BREAKING_CHANGE_VERSION)
{
ExtWarn("WARNING: SOS needs to be upgraded for this version of the runtime. Some commands may not work correctly.\n");
ExtWarn("For more information see https://go.microsoft.com/fwlink/?linkid=2135652\n");
ExtWarn("\n");
result = true;
}
}
}
}
if (pVersion != nullptr)
{
*pVersion = version;
}
return result;
}
#ifndef FEATURE_PAL
BOOL GetSOSVersion(VS_FIXEDFILEINFO *pFileInfo)
{
_ASSERTE(pFileInfo);
WCHAR wszFullPath[MAX_LONGPATH];
DWORD cchFullPath = GetModuleFileNameW(g_hInstance, wszFullPath, _countof(wszFullPath));
DWORD dwHandle = 0;
DWORD infoSize = GetFileVersionInfoSizeW(wszFullPath, &dwHandle);
if (infoSize)
{
ArrayHolder<BYTE> pVersionInfo = new BYTE[infoSize];
if (pVersionInfo)
{
if (GetFileVersionInfoW(wszFullPath, NULL, infoSize, pVersionInfo))
{
VS_FIXEDFILEINFO *pTmpFileInfo = NULL;
UINT uLen = 0;
if (VerQueryValue(pVersionInfo, "\\", (LPVOID *) &pTmpFileInfo, &uLen))
{
if (pFileInfo->dwFileVersionMS == (DWORD)-1) {
return FALSE;
}
*pFileInfo = *pTmpFileInfo; // Copy the info
return TRUE;
}
}
}
}
return FALSE;
}
#endif // !FEATURE_PAL
size_t ObjectSize(DWORD_PTR obj,BOOL fIsLargeObject)
{
DWORD_PTR dwMT;
MOVE(dwMT, obj);
return ObjectSize(obj, dwMT, FALSE, fIsLargeObject);
}
size_t ObjectSize(DWORD_PTR obj, DWORD_PTR mt, BOOL fIsValueClass, BOOL fIsLargeObject)
{
BOOL bContainsPointers;
size_t size = 0;
if (!GetSizeEfficient(obj, mt, fIsLargeObject, size, bContainsPointers))
{
return 0;
}
return size;
}
// This takes an array of values and sets every non-printable character
// to be a period.
void Flatten(__out_ecount(len) char *data, unsigned int len)
{
for (unsigned int i = 0; i < len; ++i)
if (data[i] < 32 || data[i] > 126)
data[i] = '.';
data[len] = 0;
}
void CharArrayContent(TADDR pos, ULONG num, bool widechar)
{
if (!pos || num <= 0)
return;
if (widechar)
{
ArrayHolder<WCHAR> data = new WCHAR[num+1];
if (!data)
{
ReportOOM();
return;
}
ULONG readLen = 0;
if (!SafeReadMemory(pos, data, num<<1, &readLen))
return;
Flatten(data.GetPtr(), readLen >> 1);
ExtOut("%S", data.GetPtr());
}
else
{
ArrayHolder<char> data = new char[num+1];
if (!data)
{
ReportOOM();
return;
}
ULONG readLen = 0;
if (!SafeReadMemory(pos, data, num, &readLen))
return;
_ASSERTE(readLen <= num);
Flatten(data, readLen);
ExtOut("%s", data.GetPtr());
}
}
void StringObjectContent(size_t obj, BOOL fLiteral, const int length)
{
DacpObjectData objData;
if (objData.Request(g_sos, TO_CDADDR(obj))!=S_OK)
{
ExtOut("<Invalid Object>");
return;
}
strobjInfo stInfo { 0, 0 };
if (MOVE(stInfo, obj) != S_OK)
{
ExtOut ("Error getting string data\n");
return;
}
if (objData.Size > 0x200000 || stInfo.m_StringLength > 0x200000)
{
ExtOut ("<String is invalid or too large to print>\n");
return;
}
ArrayHolder<WCHAR> pwszBuf = new WCHAR[stInfo.m_StringLength+1];
if (pwszBuf == NULL)
{
return;
}
DWORD_PTR dwAddr = (DWORD_PTR)pwszBuf.GetPtr();
if (g_sos->GetObjectStringData(TO_CDADDR(obj), stInfo.m_StringLength+1, pwszBuf, NULL)!=S_OK)
{
ExtOut("<Invalid Object>");
return;
}
if (!fLiteral)
{
pwszBuf[stInfo.m_StringLength] = L'\0';
ExtOut ("%S", pwszBuf.GetPtr());
}
else
{
ULONG32 count = stInfo.m_StringLength;
WCHAR buffer[256];
WCHAR out[512];
while (count)
{
DWORD toRead = 255;
if (count < toRead)
toRead = count;
ULONG bytesRead;
wcsncpy_s(buffer,_countof(buffer),(LPWSTR) dwAddr, toRead);
bytesRead = toRead*sizeof(WCHAR);
DWORD wcharsRead = bytesRead/2;
buffer[wcharsRead] = L'\0';
ULONG j,k=0;
for (j = 0; j < wcharsRead; j ++)
{
if (_iswprint (buffer[j])) {
out[k] = buffer[j];
k ++;
}
else
{
out[k++] = L'\\';
switch (buffer[j]) {
case L'\n':
out[k++] = L'n';
break;
case L'\0':
out[k++] = L'0';
break;
case L'\t':
out[k++] = L't';
break;
case L'\v':
out[k++] = L'v';
break;
case L'\b':
out[k++] = L'b';
break;
case L'\r':
out[k++] = L'r';
break;
case L'\f':
out[k++] = L'f';
break;
case L'\a':
out[k++] = L'a';
break;
case L'\\':
break;
case L'\?':
out[k++] = L'?';
break;
default:
out[k++] = L'?';
break;
}
}
}
out[k] = L'\0';
ExtOut ("%S", out);
count -= wcharsRead;
dwAddr += bytesRead;
}
}
}
#ifdef _TARGET_WIN64_
#include <limits.h>
__int64 str64hex(const char *ptr)
{
__int64 value = 0;
unsigned char nCount = 0;
if(ptr==NULL)
return 0;
// Ignore leading 0x if present
if (*ptr=='0' && toupper(*(ptr+1))=='X') {
ptr = ptr + 2;
}
while (1) {
char digit;
if (isdigit(*ptr)) {
digit = *ptr - '0';
} else if (isalpha(*ptr)) {
digit = (((char)toupper(*ptr)) - 'A') + 10;
if (digit >= 16) {
break; // terminate
}
} else {
break;
}
if (nCount>15) {
return _UI64_MAX; // would be an overflow
}
value = value << 4;
value |= digit;
ptr++;
nCount++;
}
return value;
}
#endif // _TARGET_WIN64_
BOOL GetValueForCMD (const char *ptr, const char *end, ARGTYPE type, size_t *value)
{
if (type == COSTRING) {
// Allocate memory for the length of the string. Whitespace terminates
// User must free the string data.
char *pszValue = NULL;
size_t dwSize = (end - ptr);
pszValue= new char[dwSize+1];
if (pszValue == NULL)
{
return FALSE;
}
strncpy_s(pszValue,dwSize+1,ptr,dwSize); // _TRUNCATE
*value = (size_t) pszValue;
} else {
char *last;
if (type == COHEX) {
#ifdef _TARGET_WIN64_
*value = str64hex(ptr);
#else
*value = strtoul(ptr,&last,16);
#endif
}
else {
#ifdef _TARGET_WIN64_
*value = _atoi64(ptr);
#else
*value = strtoul(ptr,&last,10);
#endif
}
#ifdef _TARGET_WIN64_
last = (char *) ptr;
// Ignore leading 0x if present
if (*last=='0' && toupper(*(last+1))=='X') {
last = last + 2;
}
while (isdigit(*last) || (toupper(*last)>='A' && toupper(*last)<='F')) {
last++;
}
#endif
if (last != end) {
return FALSE;
}
}
return TRUE;
}
void SetValueForCMD (void *vptr, ARGTYPE type, size_t value)
{
switch (type) {
case COBOOL:
*(BOOL*)vptr = (BOOL) value;
break;
case COSIZE_T:
case COSTRING:
case COHEX:
*(SIZE_T*)vptr = value;
break;
}
}
BOOL GetCMDOption(const char *string, CMDOption *option, size_t nOption,
CMDValue *arg, size_t maxArg, size_t *nArg)
{
const char *end;
const char *ptr = string;
BOOL endofOption = FALSE;
for (size_t n = 0; n < nOption; n ++)
{
if (IsInterrupt())
return FALSE;
option[n].hasSeen = FALSE;
}
if (nArg) {
*nArg = 0;
}
while (ptr[0] != '\0')
{
if (IsInterrupt())
return FALSE;
// skip any space
if (isspace (ptr[0])) {
while (isspace (ptr[0]))
{
if (IsInterrupt())
return FALSE;
ptr ++;
}
continue;
}
end = ptr;
// Arguments can be quoted with ". We'll remove the quotes and
// allow spaces to exist in the string.
BOOL bQuotedArg = FALSE;
if (ptr[0] == '\'' && ptr[1] != '-')
{
bQuotedArg = TRUE;
// skip quote
ptr++;
end++;
while (end[0] != '\'' && end[0] != '\0')
{
if (IsInterrupt())
return FALSE;
end ++;
}
if (end[0] != '\'')
{
// Error, th ere was a start quote but no end quote
ExtOut ("Missing quote in %s\n", ptr);
return FALSE;
}
}
else // whitespace terminates
{
while (!isspace(end[0]) && end[0] != '\0')
{
if (IsInterrupt())
return FALSE;
end ++;
}
}
#ifndef FEATURE_PAL
if (ptr[0] != '-' && ptr[0] != '/') {
#else
if (ptr[0] != '-') {
#endif
if (maxArg == 0) {
ExtOut ("Incorrect argument: %s\n", ptr);
return FALSE;
}
endofOption = TRUE;
if (*nArg >= maxArg) {
ExtOut ("Incorrect argument: %s\n", ptr);
return FALSE;
}
size_t value;
if (!GetValueForCMD (ptr,end,arg[*nArg].type,&value)) {
char oldChar = *end;
*(char *)end = '\0';
value = (size_t)GetExpression (ptr);
*(char *)end = oldChar;
/*
It is silly to do this, what if 0 is a valid expression for
the command?
if (value == 0) {
ExtOut ("Invalid argument: %s\n", ptr);
return FALSE;
}
*/
}
SetValueForCMD (arg[*nArg].vptr, arg[*nArg].type, value);
(*nArg) ++;
}
else if (endofOption) {
ExtOut ("Wrong option: %s\n", ptr);
return FALSE;
}
else {
char buffer[80];
if (end-ptr > 79) {
ExtOut ("Invalid option %s\n", ptr);
return FALSE;
}
strncpy_s (buffer,_countof(buffer), ptr, end-ptr);
size_t n;
for (n = 0; n < nOption; n ++)
{
if (IsInterrupt())
return FALSE;
if (_stricmp (buffer, option[n].name) == 0) {
if (option[n].hasSeen) {
ExtOut ("Invalid option: option specified multiple times: %s\n", buffer);
return FALSE;
}
option[n].hasSeen = TRUE;
if (option[n].hasValue) {
// skip any space
ptr = end;
if (isspace (ptr[0])) {
while (isspace (ptr[0]))
{
if (IsInterrupt())
return FALSE;
ptr ++;
}
}
if (ptr[0] == '\0') {
ExtOut ("Missing value for option %s\n", buffer);
return FALSE;
}
end = ptr;
while (!isspace(end[0]) && end[0] != '\0')
{
if (IsInterrupt())
return FALSE;
end ++;
}
size_t value;
if (!GetValueForCMD (ptr,end,option[n].type,&value)) {
char oldChar = *end;
*(char *)end = '\0';
value = (size_t)GetExpression (ptr);
*(char *)end = oldChar;
}
SetValueForCMD (option[n].vptr,option[n].type,value);
}
else {
SetValueForCMD (option[n].vptr,option[n].type,TRUE);
}
break;
}
}
if (n == nOption) {
ExtOut ("Unknown option: %s\n", buffer);
return FALSE;
}
}
ptr = end;
if (bQuotedArg)
{
ptr++;
}
}
return TRUE;
}
ReadVirtualCache g_special_rvCacheSpace;
ReadVirtualCache *rvCache = &g_special_rvCacheSpace;
void ResetGlobals(void)
{
// There are some globals used in SOS that exist for efficiency in one command,
// but should be reset because the next execution of an SOS command could be on
// another managed process. Reset them to a default state here, as this command
// is called on every SOS entry point.
g_sos->GetUsefulGlobals(&g_special_usefulGlobals);
g_special_mtCache.Clear();
g_special_rvCacheSpace.Clear();
Output::ResetIndent();
}
//---------------------------------------------------------------------------------------
//
// Loads private DAC interface, and points g_clrData to it.
//
// Return Value:
// HRESULT indicating success or failure
//
HRESULT LoadClrDebugDll(void)
{
_ASSERTE(g_pRuntime != nullptr);
HRESULT hr = g_pRuntime->GetClrDataProcess(&g_clrData);
if (FAILED(hr))
{
#ifdef FEATURE_PAL
return hr;
#else
// Fail if ExtensionApis wasn't initialized because we are hosted under dotnet-dump
if (Ioctl == nullptr) {
return hr;
}
// Try getting the DAC interface from dbgeng if the above fails on Windows
WDBGEXTS_CLR_DATA_INTERFACE Query;
Query.Iid = &__uuidof(IXCLRDataProcess);
if (!Ioctl(IG_GET_CLR_DATA_INTERFACE, &Query, sizeof(Query))) {
return hr;
}
g_clrData = (IXCLRDataProcess*)Query.Iface;
g_clrData->Flush();
#endif
}
else
{
g_clrData->AddRef();
g_clrData->Flush();
}
hr = g_clrData->QueryInterface(__uuidof(ISOSDacInterface), (void**)&g_sos);
if (FAILED(hr))
{
g_sos = NULL;
return hr;
}
return S_OK;
}
/// <summary>
/// Loads the runtime module symbols for the commands like dumplog that
/// lookup runtime symbols. This is done on-demand because it takes a
/// long time under windbg/cdb and not needed for most commands.
/// </summary>
void LoadRuntimeSymbols()
{
_ASSERTE(g_pRuntime != nullptr);
#ifndef FEATURE_PAL
ULONG64 moduleAddress = g_pRuntime->GetModuleAddress();
DEBUG_MODULE_PARAMETERS params;
HRESULT hr = g_ExtSymbols->GetModuleParameters(1, &moduleAddress, 0, ¶ms);
if (SUCCEEDED(hr))
{
if (params.SymbolType == SymDeferred)
{
PCSTR runtimeDllName = ::GetRuntimeDllName();
std::string reloadCommand;
reloadCommand.append("/f ");
reloadCommand.append(runtimeDllName);
g_ExtSymbols->Reload(reloadCommand.c_str());
g_ExtSymbols->GetModuleParameters(1, &moduleAddress, 0, ¶ms);
if (params.SymbolType != SymPdb && params.SymbolType != SymDia)
{
ExtOut("Symbols for %s not loaded. Some SOS commands may not work.\n", runtimeDllName);
}
}
}
#endif
}
typedef enum
{
GC_HEAP_INVALID = 0,
GC_HEAP_WKS = 1,
GC_HEAP_SVR = 2
} GC_HEAP_TYPE;
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find out if runtime is server build *
* *
\**********************************************************************/
DacpGcHeapData *g_pHeapData = NULL;
DacpGcHeapData g_HeapData;
BOOL InitializeHeapData()
{
if (g_pHeapData == NULL)
{
if (g_HeapData.Request(g_sos) != S_OK)
{
return FALSE;
}
g_pHeapData = &g_HeapData;
}
return TRUE;
}
BOOL IsServerBuild()
{
return InitializeHeapData() ? g_pHeapData->bServerMode : FALSE;
}
UINT GetMaxGeneration()
{
return InitializeHeapData() ? g_pHeapData->g_max_generation : 0;
}
UINT GetGcHeapCount()
{
return InitializeHeapData() ? g_pHeapData->HeapCount : 0;
}
BOOL GetGcStructuresValid()
{
// We don't want to use the cached HeapData, because this can change
// each time the program runs for a while.
DacpGcHeapData heapData;
HRESULT hr;
if ((hr = heapData.Request(g_sos)) != S_OK)
{
ExtOut("GetGcStructuresValid: request heap data FAILED %08x\n", hr);
return FALSE;
}
return heapData.bGcStructuresValid;
}
void GetAllocContextPtrs(AllocInfo *pallocInfo)
{
// gets the allocation contexts for all threads. This provides information about how much of
// the current allocation quantum has been allocated and the heap to which the quantum belongs.
// The allocation quantum is a fixed size chunk of zeroed memory from which allocations will come
// until it's filled. Each managed thread has its own allocation context.
pallocInfo->num = 0;
pallocInfo->array = NULL;
// get the thread store (See code:ClrDataAccess::RequestThreadStoreData for details)
DacpThreadStoreData ThreadStore;
if ( ThreadStore.Request(g_sos) != S_OK)
{
return;
}
int numThread = ThreadStore.threadCount;
if (numThread)
{
pallocInfo->array = new needed_alloc_context[numThread];
if (pallocInfo->array == NULL)
{
return;
}
}
// get details for each thread in the thread store
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread != NULL)
{
if (IsInterrupt())
return;
DacpThreadData Thread;
// Get information about the thread (we're getting the values of several of the
// fields of the Thread instance from the target) See code:ClrDataAccess::RequestThreadData for
// details
if (Thread.Request(g_sos, CurThread) != S_OK)
{
return;
}
if (Thread.allocContextPtr != 0)
{
// get a list of all the allocation contexts
int j;
for (j = 0; j < pallocInfo->num; j ++)
{
if (pallocInfo->array[j].alloc_ptr == (BYTE *) Thread.allocContextPtr)
break;
}
if (j == pallocInfo->num)
{
pallocInfo->num ++;
pallocInfo->array[j].alloc_ptr = (BYTE *) Thread.allocContextPtr;
pallocInfo->array[j].alloc_limit = (BYTE *) Thread.allocContextLimit;
}
}
CurThread = Thread.nextThread;
}
}
HRESULT ReadVirtualCache::Read(TADDR address, PVOID buffer, ULONG bufferSize, PULONG lpcbBytesRead)
{
// address can be any random ULONG64, as it can come from VerifyObjectMember(), and this
// can pass random pointer values in case of GC heap corruption
if (bufferSize == 0)
return S_OK;
if (bufferSize > CACHE_SIZE)
{
// Don't even try with the cache
return g_ExtData->ReadVirtual(TO_CDADDR(address), buffer, bufferSize, lpcbBytesRead);
}
if (!m_cacheValid || (address < m_startCache) || (address > (m_startCache + m_cacheSize - bufferSize)))
{
ULONG cbBytesRead = 0;
m_cacheValid = FALSE;
m_startCache = address;
// Avoid an int overflow
if (m_startCache + CACHE_SIZE < m_startCache)
m_startCache = (TADDR)(-CACHE_SIZE);
HRESULT hr = g_ExtData->ReadVirtual(TO_CDADDR(m_startCache), m_cache, CACHE_SIZE, &cbBytesRead);
if (hr != S_OK)
{
return hr;
}
m_cacheSize = cbBytesRead;
m_cacheValid = TRUE;
}
// If the address is within the cache, copy the cached memory to the input buffer
LONG_PTR cacheOffset = address - m_startCache;
if (cacheOffset >= 0 && cacheOffset < CACHE_SIZE)
{
int size = _min(bufferSize, m_cacheSize);
memcpy(buffer, (LPVOID)(m_cache + cacheOffset), size);
if (lpcbBytesRead != NULL)
{
*lpcbBytesRead = size;
}
}
else
{
return E_FAIL;
}
return S_OK;
}
HRESULT GetMTOfObject(TADDR obj, TADDR *mt)
{
if (!mt)
return E_POINTER;
// Read the MethodTable and if we succeed, get rid of the mark bits.
HRESULT hr = rvCache->Read(obj, mt, sizeof(TADDR), NULL);
if (SUCCEEDED(hr))
*mt &= ~3;
return hr;
}
#ifndef FEATURE_PAL
StressLogMem::~StressLogMem ()
{
MemRange * range = list;
while (range)
{
MemRange * temp = range->next;
delete range;
range = temp;
}
}
bool StressLogMem::Init (ULONG64 stressLogAddr, IDebugDataSpaces* memCallBack)
{
size_t ThreadStressLogAddr = NULL;
HRESULT hr = memCallBack->ReadVirtual(UL64_TO_CDA(stressLogAddr + offsetof (StressLog, logs)),
&ThreadStressLogAddr, sizeof (ThreadStressLogAddr), 0);
if (hr != S_OK)
{
return false;
}
while(ThreadStressLogAddr != NULL)
{
size_t ChunkListHeadAddr = NULL;
hr = memCallBack->ReadVirtual(TO_CDADDR(ThreadStressLogAddr + ThreadStressLog::OffsetOfListHead ()),
&ChunkListHeadAddr, sizeof (ChunkListHeadAddr), 0);
if (hr != S_OK || ChunkListHeadAddr == NULL)
{
return false;
}
size_t StressLogChunkAddr = ChunkListHeadAddr;
do
{
AddRange (StressLogChunkAddr, sizeof (StressLogChunk));
hr = memCallBack->ReadVirtual(TO_CDADDR(StressLogChunkAddr + offsetof (StressLogChunk, next)),
&StressLogChunkAddr, sizeof (StressLogChunkAddr), 0);
if (hr != S_OK)
{
return false;
}
if (StressLogChunkAddr == NULL)
{
return true;
}
} while (StressLogChunkAddr != ChunkListHeadAddr);
hr = memCallBack->ReadVirtual(TO_CDADDR(ThreadStressLogAddr + ThreadStressLog::OffsetOfNext ()),
&ThreadStressLogAddr, sizeof (ThreadStressLogAddr), 0);
if (hr != S_OK)
{
return false;
}
}
return true;
}
bool StressLogMem::IsInStressLog (ULONG64 addr)
{
MemRange * range = list;
while (range)
{
if (range->InRange (addr))
return true;
range = range->next;
}
return false;
}
#endif // !FEATURE_PAL
unsigned int Output::g_bSuppressOutput = 0;
unsigned int Output::g_Indent = 0;
bool Output::g_bDbgOutput = false;
bool Output::g_bDMLExposed = false;
unsigned int Output::g_DMLEnable = 0;
template <class T, int count, int size> const int StaticData<T, count, size>::Count = count;
template <class T, int count, int size> const int StaticData<T, count, size>::Size = size;
StaticData<char, 4, 1024> CachedString::cache;
CachedString::CachedString()
: mPtr(0), mRefCount(0), mIndex(~0), mSize(cache.Size)
{
Create();
}
CachedString::CachedString(const CachedString &rhs)
: mPtr(0), mRefCount(0), mIndex(~0), mSize(cache.Size)
{
Copy(rhs);
}
CachedString::~CachedString()
{
Clear();
}
const CachedString &CachedString::operator=(const CachedString &rhs)
{
Clear();
Copy(rhs);
return *this;
}
void CachedString::Copy(const CachedString &rhs)
{
if (rhs.IsOOM())
{
SetOOM();
}
else
{
mPtr = rhs.mPtr;
mIndex = rhs.mIndex;
mSize = rhs.mSize;
if (rhs.mRefCount)
{
mRefCount = rhs.mRefCount;
(*mRefCount)++;
}
else
{
// We only create count the first time we copy it, so
// we initialize it to 2.
mRefCount = rhs.mRefCount = new unsigned int(2);
if (!mRefCount)
SetOOM();
}
}
}
void CachedString::Clear()
{
if (!mRefCount || --*mRefCount == 0)
{
if (mIndex == -1)
{
if (mPtr)
delete [] mPtr;
}
else if (mIndex >= 0 && mIndex < cache.Count)
{
cache.InUse[mIndex] = false;
}
if (mRefCount)
delete mRefCount;
}
mPtr = 0;
mIndex = ~0;
mRefCount = 0;
mSize = cache.Size;
}
void CachedString::Create()
{
mIndex = -1;
mRefCount = 0;
// First try to find a string in the cache to use.
for (int i = 0; i < cache.Count; ++i)
if (!cache.InUse[i])
{
cache.InUse[i] = true;
mPtr = cache.Data[i];
mIndex = i;
break;
}
// We did not find a string to use, so we'll create a new one.
if (mIndex == -1)
{
mPtr = new char[cache.Size];
if (!mPtr)
SetOOM();
}
}
void CachedString::SetOOM()
{
Clear();
mIndex = -2;
}
void CachedString::Allocate(int size)
{
Clear();
mPtr = new char[size];
if (mPtr)
{
mSize = size;
mIndex = -1;
}
else
{
SetOOM();
}
}
size_t CountHexCharacters(CLRDATA_ADDRESS val)
{
size_t ret = 0;
while (val)
{
val >>= 4;
ret++;
}
return ret;
}
// SOS is single threaded so a global buffer doesn't need any locking
char g_printBuffer[8192];
//---------------------------------------------------------------------
// Because debuggers and hosts SOS runs on now output formatting always
// happens with the C++ runtime functions and not dbgeng. This means
// the special dbgeng formatting charaters are not supported: %N, %I,
// %ma, %mu, %msa, %msu, %y, %ly and %p takes an architecture size
// pointer (size_t) instead of always a 64bit one.
//---------------------------------------------------------------------
HRESULT
OutputVaList(
ULONG mask,
PCSTR format,
va_list args)
{
int length = _vsnprintf_s((char* const)&g_printBuffer, sizeof(g_printBuffer), _TRUNCATE, format, args);
if (length > 0)
{
return g_ExtControl->OutputVaList(mask, (char* const)&g_printBuffer, args);
}
return E_FAIL;
}
HRESULT
ControlledOutputVaList(
ULONG outputControl,
ULONG mask,
PCSTR format,
va_list args)
{
int length = _vsnprintf_s((char* const)&g_printBuffer, sizeof(g_printBuffer), _TRUNCATE, format, args);
if (length > 0)
{
return g_ExtControl->ControlledOutputVaList(outputControl, mask, (char* const)&g_printBuffer, args);
}
return E_FAIL;
}
HRESULT
OutputText(
ULONG mask,
PCSTR format,
...)
{
va_list args;
va_start (args, format);
HRESULT result = OutputVaList(mask, format, args);
va_end (args);
return result;
}
void WhitespaceOut(int count)
{
static const int FixedIndentWidth = 0x40;
static const char FixedIndentString[FixedIndentWidth+1] =
" ";
if (count <= 0)
return;
int mod = count & 0x3F;
count &= ~0x3F;
if (mod > 0)
OutputText(DEBUG_OUTPUT_NORMAL, "%.*s", mod, FixedIndentString);
for ( ; count > 0; count -= FixedIndentWidth)
OutputText(DEBUG_OUTPUT_NORMAL, FixedIndentString);
}
void DMLOut(PCSTR format, ...)
{
if (Output::IsOutputSuppressed())
return;
va_list args;
va_start(args, format);
ExtOutIndent();
if (IsDMLEnabled() && !Output::IsDMLExposed())
{
ControlledOutputVaList(DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL, format, args);
}
else
{
OutputVaList(DEBUG_OUTPUT_NORMAL, format, args);
}
va_end(args);
}
void IfDMLOut(PCSTR format, ...)
{
if (Output::IsOutputSuppressed() || !IsDMLEnabled())
return;
va_list args;
va_start(args, format);
ExtOutIndent();
g_ExtControl->ControlledOutputVaList(DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL, format, args);
va_end(args);
}
void ExtOut(PCSTR Format, ...)
{
if (Output::IsOutputSuppressed())
return;
va_list Args;
va_start(Args, Format);
ExtOutIndent();
OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
va_end(Args);
}
void ExtWarn(PCSTR Format, ...)
{
if (Output::IsOutputSuppressed())
return;
va_list Args;
va_start(Args, Format);
OutputVaList(DEBUG_OUTPUT_WARNING, Format, Args);
va_end(Args);
}
void ExtErr(PCSTR Format, ...)
{
va_list Args;
va_start(Args, Format);
OutputVaList(DEBUG_OUTPUT_ERROR, Format, Args);
va_end(Args);
}
/// <summary>
/// Internal trace output for extensions library
/// </summary>
void TraceError(PCSTR format, ...)
{
if (Output::g_bDbgOutput)
{
va_list args;
va_start(args, format);
OutputVaList(DEBUG_OUTPUT_ERROR, format, args);
va_end(args);
}
}
void ExtDbgOut(PCSTR Format, ...)
{
if (Output::g_bDbgOutput)
{
va_list Args;
va_start(Args, Format);
ExtOutIndent();
OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
va_end(Args);
}
}
const char * const DMLFormats[] =
{
NULL, // DML_None (do not use)
"<exec cmd=\"!DumpMT /d %s\">%s</exec>", // DML_MethodTable
"<exec cmd=\"!DumpMD /d %s\">%s</exec>", // DML_MethodDesc
"<exec cmd=\"!DumpClass /d %s\">%s</exec>", // DML_EEClass
"<exec cmd=\"!DumpModule /d %s\">%s</exec>", // DML_Module
"<exec cmd=\"!U /d %s\">%s</exec>", // DML_IP
"<exec cmd=\"!DumpObj /d %s\">%s</exec>", // DML_Object
"<exec cmd=\"!DumpDomain /d %s\">%s</exec>", // DML_Domain
"<exec cmd=\"!DumpAssembly /d %s\">%s</exec>", // DML_Assembly
"<exec cmd=\"~~[%s]s\">%s</exec>", // DML_ThreadID
"<exec cmd=\"!DumpVC /d %s %s\">%s</exec>", // DML_ValueClass
"<exec cmd=\"!DumpHeap /d -mt %s\">%s</exec>", // DML_DumpHeapMT
"<exec cmd=\"!ListNearObj /d %s\">%s</exec>", // DML_ListNearObj
"<exec cmd=\"!ThreadState %s\">%s</exec>", // DML_ThreadState
"<exec cmd=\"!PrintException /d %s\">%s</exec>",// DML_PrintException
"<exec cmd=\"!DumpRCW /d %s\">%s</exec>", // DML_RCWrapper
"<exec cmd=\"!DumpCCW /d %s\">%s</exec>", // DML_CCWrapper
"<exec cmd=\"!ClrStack -i %S %d\">%S</exec>", // DML_ManagedVar
"<exec cmd=\"!DumpAsync -addr %s -tasks -completed -fields -stacks -roots\">%s</exec>", // DML_Async
"<exec cmd=\"!DumpIL /i %s\">%s</exec>", // DML_IL
"<exec cmd=\"!DumpRCW -cw /d %s\">%s</exec>", // DML_ComWrapperRCW
"<exec cmd=\"!DumpCCW -cw /d %s\">%s</exec>", // DML_ComWrapperCCW
"<exec cmd=\"dps %s L%d\">%s</exec>", // DML_TaggedMemory
};
void ConvertToLower(__out_ecount(len) char *buffer, size_t len)
{
for (size_t i = 0; i < len && buffer[i]; ++i)
buffer[i] = (char)tolower(buffer[i]);
}
/* Build a hex display of addr.
*/
int GetHex(CLRDATA_ADDRESS addr, __out_ecount(len) char *out, size_t len, bool fill)
{
int count = sprintf_s(out, len, fill ? "%p" : "%x", (size_t)addr);
ConvertToLower(out, len);
return count;
}
CachedString Output::BuildHexValue(CLRDATA_ADDRESS addr, FormatType type, bool fill)
{
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
if (IsDMLEnabled())
{
char hex[POINTERSIZE_BYTES*2 + 1];
GetHex(addr, hex, _countof(hex), fill);
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hex, hex);
}
else
{
GetHex(addr, ret, ret.GetStrLen(), fill);
}
return ret;
}
CachedString Output::BuildHexValueWithLength(CLRDATA_ADDRESS addr, size_t len, FormatType type, bool fill)
{
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
if (IsDMLEnabled())
{
char hex[POINTERSIZE_BYTES*2 + 1];
GetHex(addr, hex, _countof(hex), fill);
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hex, len, hex);
}
else
{
GetHex(addr, ret, ret.GetStrLen(), fill);
}
return ret;
}
CachedString Output::BuildVCValue(CLRDATA_ADDRESS mt, CLRDATA_ADDRESS addr, FormatType type, bool fill)
{
_ASSERTE(type == DML_ValueClass);
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
if (IsDMLEnabled())
{
char hexaddr[POINTERSIZE_BYTES*2 + 1];
char hexmt[POINTERSIZE_BYTES*2 + 1];
GetHex(addr, hexaddr, _countof(hexaddr), fill);
GetHex(mt, hexmt, _countof(hexmt), fill);
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hexmt, hexaddr, hexaddr);
}
else
{
GetHex(addr, ret, ret.GetStrLen(), fill);
}
return ret;
}
CachedString Output::BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, __in_z LPCWSTR simpleName, FormatType type)
{
_ASSERTE(type == DML_ManagedVar);
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
// calculate the number of digits in frame (this assumes base-10 display of frames)
int numFrameDigits = 0;
if (frame > 0)
{
ULONG tempFrame = frame;
while (tempFrame > 0)
{
++numFrameDigits;
tempFrame /= 10;
}
}
else
{
numFrameDigits = 1;
}
size_t totalStringLength = strlen(DMLFormats[type]) + _wcslen(expansionName) + numFrameDigits + _wcslen(simpleName) + 1;
if (totalStringLength > ret.GetStrLen())
{
ret.Allocate(static_cast<int>(totalStringLength));
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
}
if (IsDMLEnabled())
{
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], expansionName, frame, simpleName);
}
else
{
sprintf_s(ret, ret.GetStrLen(), "%S", simpleName);
}
return ret;
}
CachedString Output::BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, int indexInArray, FormatType type)
{
WCHAR indexString[24];
swprintf_s(indexString, _countof(indexString), W("[%d]"), indexInArray);
return BuildManagedVarValue(expansionName, frame, indexString, type);
}
EnableDMLHolder::EnableDMLHolder(BOOL enable)
: mEnable(enable)
{
#ifndef FEATURE_PAL
// If the user has not requested that we use DML, it's still possible that
// they have instead specified ".prefer_dml 1". If enable is false,
// we will check here for .prefer_dml. Since this class is only used once
// per command issued to SOS, this should only check the setting once per
// sos command issued.
if (!mEnable && Output::g_DMLEnable <= 0)
{
ULONG opts;
HRESULT hr = g_ExtControl->GetEngineOptions(&opts);
mEnable = SUCCEEDED(hr) && (opts & DEBUG_ENGOPT_PREFER_DML) == DEBUG_ENGOPT_PREFER_DML;
}
if (mEnable)
{
Output::g_DMLEnable++;
}
#endif // FEATURE_PAL
}
EnableDMLHolder::~EnableDMLHolder()
{
#ifndef FEATURE_PAL
if (mEnable)
Output::g_DMLEnable--;
#endif
}
bool IsDMLEnabled()
{
return IsInitializedByDbgEng() && Output::g_DMLEnable > 0;
}
NoOutputHolder::NoOutputHolder(BOOL bSuppress)
: mSuppress(bSuppress)
{
if (mSuppress)
Output::g_bSuppressOutput++;
}
NoOutputHolder::~NoOutputHolder()
{
if (mSuppress)
Output::g_bSuppressOutput--;
}
//
// Code to support mapping RVAs to managed code line numbers.
//
//
// Retrieves the IXCLRDataMethodInstance* instance associated with the
// passed in native offset.
HRESULT
GetClrMethodInstance(
___in ULONG64 NativeOffset,
___out IXCLRDataMethodInstance** Method)
{
HRESULT Status;
CLRDATA_ENUM MethEnum;
Status = g_clrData->StartEnumMethodInstancesByAddress(NativeOffset, NULL, &MethEnum);
if (Status == S_OK)
{
Status = g_clrData->EnumMethodInstanceByAddress(&MethEnum, Method);
g_clrData->EndEnumMethodInstancesByAddress(MethEnum);
}
// Any alternate success is a true failure here.
return (Status == S_OK || FAILED(Status)) ? Status : E_NOINTERFACE;
}
//
// Enumerates over the IL address map associated with the passed in
// managed method, and returns the highest non-epilog offset.
HRESULT
GetLastMethodIlOffset(
___in IXCLRDataMethodInstance* Method,
___out PULONG32 MethodOffs)
{
HRESULT Status;
CLRDATA_IL_ADDRESS_MAP MapLocal[16];
CLRDATA_IL_ADDRESS_MAP* Map = MapLocal;
ULONG32 MapCount = _countof(MapLocal);
ULONG32 MapNeeded;
ULONG32 HighestOffset;
for (;;)
{
if ((Status = Method->GetILAddressMap(MapCount, &MapNeeded, Map)) != S_OK)
{
return Status;
}
if (MapNeeded <= MapCount)
{
break;
}
// Need more map entries.
if (Map != MapLocal)
{
// Already went around and the answer changed,
// which should not be possible.
delete[] Map;
return E_UNEXPECTED;
}
Map = new CLRDATA_IL_ADDRESS_MAP[MapNeeded];
if (!Map)
{
return E_OUTOFMEMORY;
}
MapCount = MapNeeded;
}
HighestOffset = 0;
for (size_t i = 0; i < MapNeeded; i++)
{
if (Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_NO_MAPPING &&
Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_PROLOG &&
Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_EPILOG &&
Map[i].ilOffset > HighestOffset)
{
HighestOffset = Map[i].ilOffset;
}
}
if (Map != MapLocal)
{
delete[] Map;
}
*MethodOffs = HighestOffset;
return S_OK;
}
//
// Convert a native offset (possibly already associated with a managed
// method identified by the passed in IXCLRDataMethodInstance) to a
// triplet (ImageInfo, MethodToken, MethodOffset) that can be used to
// represent an "IL offset".
HRESULT
ConvertNativeToIlOffset(
___in ULONG64 nativeOffset,
___in BOOL bAdjustOffsetForLineNumber,
___out IXCLRDataModule** ppModule,
___out mdMethodDef* methodToken,
___out PULONG32 methodOffs)
{
ToRelease<IXCLRDataMethodInstance> pMethodInst(NULL);
HRESULT Status;
if ((Status = GetClrMethodInstance(nativeOffset, &pMethodInst)) != S_OK)
{
ExtDbgOut("ConvertNativeToIlOffset(%p): GetClrMethodInstance FAILED %08x\n", nativeOffset, Status);
return Status;
}
if (bAdjustOffsetForLineNumber)
{
CLRDATA_ADDRESS startAddr;
if (pMethodInst->GetRepresentativeEntryAddress(&startAddr) == S_OK)
{
if (nativeOffset >= (startAddr + g_targetMachine->StackWalkIPAdjustOffset()))
{
nativeOffset -= g_targetMachine->StackWalkIPAdjustOffset();
}
}
}
if ((Status = pMethodInst->GetILOffsetsByAddress(nativeOffset, 1, NULL, methodOffs)) != S_OK)
{
ExtDbgOut("ConvertNativeToIlOffset(%p): GetILOffsetsByAddress FAILED %08x\n", nativeOffset, Status);
*methodOffs = 0;
}
else
{
switch((LONG)*methodOffs)
{
case CLRDATA_IL_OFFSET_NO_MAPPING:
return E_NOINTERFACE;
case CLRDATA_IL_OFFSET_PROLOG:
// Treat all of the prologue as part of
// the first source line.
*methodOffs = 0;
break;
case CLRDATA_IL_OFFSET_EPILOG:
// Back up until we find the last real
// IL offset.
if ((Status = GetLastMethodIlOffset(pMethodInst, methodOffs)) != S_OK)
{
return Status;
}
break;
}
}
return pMethodInst->GetTokenAndScope(methodToken, ppModule);
}
// Based on a native offset, passed in the first argument this function
// identifies the corresponding source file name and line number.
HRESULT
GetLineByOffset(
___in ULONG64 nativeOffset,
___out ULONG *pLinenum,
__out_ecount(cchFileName) WCHAR* pwszFileName,
___in ULONG cchFileName,
___in BOOL bAdjustOffsetForLineNumber /* = FALSE */)
{
HRESULT Status = S_OK;
ULONG32 methodToken;
ULONG32 methodOffs;
// Find the image, method token and IL offset that correspond to "nativeOffset"
ToRelease<IXCLRDataModule> pModule(NULL);
IfFailRet(ConvertNativeToIlOffset(nativeOffset, bAdjustOffsetForLineNumber, &pModule, &methodToken, &methodOffs));
ToRelease<IMetaDataImport> pMDImport(NULL);
Status = pModule->QueryInterface(IID_IMetaDataImport, (LPVOID *) &pMDImport);
if (FAILED(Status))
{
ExtDbgOut("GetLineByOffset(%p): QueryInterface(IID_IMetaDataImport) FAILED %08x\n", nativeOffset, Status);
}
SymbolReader symbolReader;
IfFailRet(symbolReader.LoadSymbols(pMDImport, pModule));
return symbolReader.GetLineByILOffset(methodToken, methodOffs, pLinenum, pwszFileName, cchFileName);
}
void TableOutput::ReInit(int numColumns, int defaultColumnWidth, Alignment alignmentDefault, int indent, int padding)
{
Clear();
mColumns = numColumns;
mDefaultWidth = defaultColumnWidth;
mIndent = indent;
mPadding = padding;
mCurrCol = 0;
mDefaultAlign = alignmentDefault;
}
void TableOutput::SetWidths(int columns, ...)
{
SOS_Assert(columns > 0);
SOS_Assert(columns <= mColumns);
AllocWidths();
va_list list;
va_start(list, columns);
for (int i = 0; i < columns; ++i)
mWidths[i] = va_arg(list, int);
va_end(list);
}
void TableOutput::SetColWidth(int col, int width)
{
SOS_Assert(col >= 0 && col < mColumns);
SOS_Assert(width >= 0);
AllocWidths();
mWidths[col] = width;
}
void TableOutput::SetColAlignment(int col, Alignment align)
{
SOS_Assert(col >= 0 && col < mColumns);
if (!mAlignments)
{
mAlignments = new Alignment[mColumns];
for (int i = 0; i < mColumns; ++i)
mAlignments[i] = mDefaultAlign;
}
mAlignments[col] = align;
}
void TableOutput::Clear()
{
if (mAlignments)
{
delete [] mAlignments;
mAlignments = 0;
}
if (mWidths)
{
delete [] mWidths;
mWidths = 0;
}
}
void TableOutput::AllocWidths()
{
if (!mWidths)
{
mWidths = new int[mColumns];
for (int i = 0; i < mColumns; ++i)
mWidths[i] = mDefaultWidth;
}
}
int TableOutput::GetColumnWidth(int col)
{
SOS_Assert(col < mColumns);
if (mWidths)
return mWidths[col];
return mDefaultWidth;
}
Alignment TableOutput::GetColAlign(int col)
{
SOS_Assert(col < mColumns);
if (mAlignments)
return mAlignments[col];
return mDefaultAlign;
}
const char *TableOutput::GetWhitespace(int amount)
{
static char WhiteSpace[256] = "";
static int count = 0;
if (count == 0)
{
count = _countof(WhiteSpace);
for (int i = 0; i < count-1; ++i)
WhiteSpace[i] = ' ';
WhiteSpace[count-1] = 0;
}
SOS_Assert(amount < count);
return &WhiteSpace[count-amount-1];
}
void TableOutput::OutputBlankColumns(int col)
{
if (col < mCurrCol)
{
ExtOut("\n");
mCurrCol = 0;
}
int whitespace = 0;
for (int i = mCurrCol; i < col; ++i)
whitespace += GetColumnWidth(i) + mPadding;
ExtOut(GetWhitespace(whitespace));
}
void TableOutput::OutputIndent()
{
if (mIndent)
ExtOut(GetWhitespace(mIndent));
}
#ifndef FEATURE_PAL
PEOffsetMemoryReader::PEOffsetMemoryReader(TADDR moduleBaseAddress) :
m_moduleBaseAddress(moduleBaseAddress),
m_refCount(1)
{}
HRESULT __stdcall PEOffsetMemoryReader::QueryInterface(REFIID riid, VOID** ppInterface)
{
if(riid == __uuidof(IDiaReadExeAtOffsetCallback))
{
*ppInterface = static_cast<IDiaReadExeAtOffsetCallback*>(this);
AddRef();
return S_OK;
}
else if(riid == __uuidof(IUnknown))
{
*ppInterface = static_cast<IUnknown*>(this);
AddRef();
return S_OK;
}
else
{
return E_NOINTERFACE;
}
}
ULONG __stdcall PEOffsetMemoryReader::AddRef()
{
return InterlockedIncrement((volatile LONG *) &m_refCount);
}
ULONG __stdcall PEOffsetMemoryReader::Release()
{
ULONG count = InterlockedDecrement((volatile LONG *) &m_refCount);
if(count == 0)
{
delete this;
}
return count;
}
// IDiaReadExeAtOffsetCallback implementation
HRESULT __stdcall PEOffsetMemoryReader::ReadExecutableAt(DWORDLONG fileOffset, DWORD cbData, DWORD* pcbData, BYTE data[])
{
return SafeReadMemory(m_moduleBaseAddress + fileOffset, data, cbData, pcbData) ? S_OK : E_FAIL;
}
PERvaMemoryReader::PERvaMemoryReader(TADDR moduleBaseAddress) :
m_moduleBaseAddress(moduleBaseAddress),
m_refCount(1)
{}
HRESULT __stdcall PERvaMemoryReader::QueryInterface(REFIID riid, VOID** ppInterface)
{
if(riid == __uuidof(IDiaReadExeAtRVACallback))
{
*ppInterface = static_cast<IDiaReadExeAtRVACallback*>(this);
AddRef();
return S_OK;
}
else if(riid == __uuidof(IUnknown))
{
*ppInterface = static_cast<IUnknown*>(this);
AddRef();
return S_OK;
}
else
{
return E_NOINTERFACE;
}
}
ULONG __stdcall PERvaMemoryReader::AddRef()
{
return InterlockedIncrement((volatile LONG *) &m_refCount);
}
ULONG __stdcall PERvaMemoryReader::Release()
{
ULONG count = InterlockedDecrement((volatile LONG *) &m_refCount);
if(count == 0)
{
delete this;
}
return count;
}
// IDiaReadExeAtOffsetCallback implementation
HRESULT __stdcall PERvaMemoryReader::ReadExecutableAtRVA(DWORD relativeVirtualAddress, DWORD cbData, DWORD* pcbData, BYTE data[])
{
return SafeReadMemory(m_moduleBaseAddress + relativeVirtualAddress, data, cbData, pcbData) ? S_OK : E_FAIL;
}
#endif // FEATURE_PAL
static void AddAssemblyName(WString& methodOutput, CLRDATA_ADDRESS mdesc)
{
DacpMethodDescData mdescData;
if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
{
DacpModuleData dmd;
if (SUCCEEDED(dmd.Request(g_sos, mdescData.ModulePtr)))
{
ToRelease<IXCLRDataModule> pModule;
if (SUCCEEDED(g_sos->GetModule(mdescData.ModulePtr, &pModule)))
{
ArrayHolder<WCHAR> wszFileName = new WCHAR[MAX_LONGPATH + 1];
ULONG32 nameLen = 0;
if (SUCCEEDED(pModule->GetFileName(MAX_LONGPATH, &nameLen, wszFileName)))
{
if (wszFileName[0] != W('\0'))
{
WCHAR *pJustName = _wcsrchr(wszFileName, GetTargetDirectorySeparatorW());
if (pJustName == NULL)
pJustName = wszFileName - 1;
methodOutput += (pJustName + 1);
methodOutput += W("!");
}
}
}
}
}
}
WString GetFrameFromAddress(TADDR frameAddr, IXCLRDataStackWalk *pStackWalk, BOOL bAssemblyName)
{
TADDR vtAddr;
MOVE(vtAddr, frameAddr);
WString frameOutput;
frameOutput += W("[");
if (SUCCEEDED(g_sos->GetFrameName(TO_CDADDR(vtAddr), mdNameLen, g_mdName, NULL)))
frameOutput += g_mdName;
else
frameOutput += W("Frame");
frameOutput += WString(W(": ")) + Pointer(frameAddr) + W("] ");
// Print the frame's associated function info, if it has any.
CLRDATA_ADDRESS mdesc = 0;
if (SUCCEEDED(g_sos->GetMethodDescPtrFromFrame(frameAddr, &mdesc)))
{
if (SUCCEEDED(g_sos->GetMethodDescName(mdesc, mdNameLen, g_mdName, NULL)))
{
if (bAssemblyName)
{
AddAssemblyName(frameOutput, mdesc);
}
frameOutput += g_mdName;
}
else
{
frameOutput += W("<unknown method>");
}
}
else if (pStackWalk)
{
// The Frame did not have direct function info, so try to get the method instance
// (in this case a MethodDesc), and read the name from it.
ToRelease<IXCLRDataFrame> frame;
if (SUCCEEDED(pStackWalk->GetFrame(&frame)))
{
ToRelease<IXCLRDataMethodInstance> methodInstance;
if (SUCCEEDED(frame->GetMethodInstance(&methodInstance)))
{
// GetName can return S_FALSE if mdNameLen is not large enough. However we are already
// passing a pretty big buffer in. If this returns S_FALSE (meaning the buffer is too
// small) then we should not output it anyway.
if (methodInstance->GetName(0, mdNameLen, NULL, g_mdName) == S_OK)
frameOutput += g_mdName;
}
}
}
return frameOutput;
}
WString MethodNameFromIP(CLRDATA_ADDRESS ip, BOOL bSuppressLines, BOOL bAssemblyName, BOOL bDisplacement, BOOL bAdjustIPForLineNumber)
{
ULONG linenum;
WString methodOutput;
CLRDATA_ADDRESS mdesc = 0;
if (FAILED(g_sos->GetMethodDescPtrFromIP(ip, &mdesc)))
{
methodOutput = W("<unknown>");
}
else
{
DacpMethodDescData mdescData;
if (SUCCEEDED(g_sos->GetMethodDescName(mdesc, mdNameLen, g_mdName, NULL)))
{
if (bAssemblyName)
{
AddAssemblyName(methodOutput, mdesc);
}
methodOutput += g_mdName;
if (bDisplacement)
{
if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
{
ULONG64 disp = (ip - mdescData.NativeCodeAddr);
if (disp)
{
methodOutput += W(" + ");
methodOutput += Decimal(disp);
}
}
}
}
else if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
{
DacpModuleData dmd;
BOOL bModuleNameWorked = FALSE;
ULONG64 addrInModule = ip;
if (SUCCEEDED(dmd.Request(g_sos, mdescData.ModulePtr)))
{
CLRDATA_ADDRESS peFileBase = 0;
if (SUCCEEDED(g_sos->GetPEFileBase(dmd.File, &peFileBase)))
{
if (peFileBase)
{
addrInModule = peFileBase;
}
}
}
ULONG Index;
ULONG64 moduleBase;
if (SUCCEEDED(g_ExtSymbols->GetModuleByOffset(UL64_TO_CDA(addrInModule), 0, &Index, &moduleBase)))
{
ArrayHolder<char> szModuleName = new char[MAX_LONGPATH+1];
if (SUCCEEDED(g_ExtSymbols->GetModuleNames(Index, moduleBase, NULL, 0, NULL, szModuleName, MAX_LONGPATH, NULL, NULL, 0, NULL)))
{
MultiByteToWideChar (CP_ACP, 0, szModuleName, MAX_LONGPATH, g_mdName, _countof(g_mdName));
methodOutput += g_mdName;
methodOutput += W("!");
}
}
methodOutput += W("<unknown method>");
}
else
{
methodOutput = W("<unknown>");
}
ArrayHolder<WCHAR> wszFileName = new WCHAR[MAX_LONGPATH];
if (!bSuppressLines &&
SUCCEEDED(GetLineByOffset(TO_CDADDR(ip), &linenum, wszFileName, MAX_LONGPATH, bAdjustIPForLineNumber)))
{
methodOutput += WString(W(" [")) + wszFileName + W(" @ ") + Decimal(linenum) + W("]");
}
}
return methodOutput;
}
HRESULT GetGCRefs(ULONG osID, SOSStackRefData **ppRefs, unsigned int *pRefCnt, SOSStackRefError **ppErrors, unsigned int *pErrCount)
{
if (ppRefs == NULL || pRefCnt == NULL)
return E_POINTER;
if (pErrCount)
*pErrCount = 0;
*pRefCnt = 0;
unsigned int count = 0;
ToRelease<ISOSStackRefEnum> pEnum;
if (FAILED(g_sos->GetStackReferences(osID, &pEnum)) || FAILED(pEnum->GetCount(&count)))
{
ExtOut("Failed to enumerate GC references.\n");
return E_FAIL;
}
*ppRefs = new SOSStackRefData[count];
if (FAILED(pEnum->Next(count, *ppRefs, pRefCnt)))
{
ExtOut("Failed to enumerate GC references.\n");
return E_FAIL;
}
SOS_Assert(count == *pRefCnt);
// Enumerate errors found. Any bad HRESULT recieved while enumerating errors is NOT a fatal error.
// Hence we return S_FALSE if we encounter one.
if (ppErrors && pErrCount)
{
ToRelease<ISOSStackRefErrorEnum> pErrors;
if (FAILED(pEnum->EnumerateErrors(&pErrors)))
{
ExtOut("Failed to enumerate GC reference errors.\n");
return S_FALSE;
}
if (FAILED(pErrors->GetCount(&count)))
{
ExtOut("Failed to enumerate GC reference errors.\n");
return S_FALSE;
}
*ppErrors = new SOSStackRefError[count];
if (FAILED(pErrors->Next(count, *ppErrors, pErrCount)))
{
ExtOut("Failed to enumerate GC reference errors.\n");
*pErrCount = 0;
return S_FALSE;
}
SOS_Assert(count == *pErrCount);
}
return S_OK;
}
InternalFrameManager::InternalFrameManager() : m_cInternalFramesActual(0), m_iInternalFrameCur(0) {}
HRESULT InternalFrameManager::Init(ICorDebugThread3 * pThread3)
{
_ASSERTE(pThread3 != NULL);
return pThread3->GetActiveInternalFrames(
_countof(m_rgpInternalFrame2),
&m_cInternalFramesActual,
&(m_rgpInternalFrame2[0]));
}
HRESULT InternalFrameManager::PrintPrecedingInternalFrames(ICorDebugFrame * pFrame)
{
HRESULT Status;
for (; m_iInternalFrameCur < m_cInternalFramesActual; m_iInternalFrameCur++)
{
BOOL bIsCloser = FALSE;
IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->IsCloserToLeaf(pFrame, &bIsCloser));
if (!bIsCloser)
{
// Current internal frame is now past pFrame, so we're done
return S_OK;
}
IfFailRet(PrintCurrentInternalFrame());
}
// Exhausted list of internal frames. Done!
return S_OK;
}
HRESULT InternalFrameManager::PrintCurrentInternalFrame()
{
_ASSERTE(m_iInternalFrameCur < m_cInternalFramesActual);
HRESULT Status;
CORDB_ADDRESS address;
IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->GetAddress(&address));
ToRelease<ICorDebugInternalFrame> pInternalFrame;
IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->QueryInterface(IID_ICorDebugInternalFrame, (LPVOID *) &pInternalFrame));
CorDebugInternalFrameType type;
IfFailRet(pInternalFrame->GetFrameType(&type));
LPCSTR szFrameType = NULL;
switch(type)
{
default:
szFrameType = "Unknown internal frame.";
break;
case STUBFRAME_M2U:
szFrameType = "Managed to Unmanaged transition";
break;
case STUBFRAME_U2M:
szFrameType = "Unmanaged to Managed transition";
break;
case STUBFRAME_APPDOMAIN_TRANSITION:
szFrameType = "AppDomain transition";
break;
case STUBFRAME_LIGHTWEIGHT_FUNCTION:
szFrameType = "Lightweight function";
break;
case STUBFRAME_FUNC_EVAL:
szFrameType = "Function evaluation";
break;
case STUBFRAME_INTERNALCALL:
szFrameType = "Internal call";
break;
case STUBFRAME_CLASS_INIT:
szFrameType = "Class initialization";
break;
case STUBFRAME_EXCEPTION:
szFrameType = "Exception";
break;
case STUBFRAME_SECURITY:
szFrameType = "Security";
break;
case STUBFRAME_JIT_COMPILATION:
szFrameType = "JIT Compilation";
break;
}
DMLOut("%p %s ", SOS_PTR(address), SOS_PTR(0));
ExtOut("[%s: %p]\n", szFrameType, SOS_PTR(address));
return S_OK;
}
#ifdef FEATURE_PAL
struct MemoryRegion
{
private:
uint64_t m_startAddress;
uint64_t m_endAddress;
CLRDATA_ADDRESS m_peFile;
BYTE* m_metadataMemory;
volatile LONG m_busy;
HRESULT CacheMetadata()
{
if (m_metadataMemory == nullptr)
{
HRESULT hr;
CLRDATA_ADDRESS baseAddress;
if (FAILED(hr = g_sos->GetPEFileBase(m_peFile, &baseAddress))) {
return hr;
}
ArrayHolder<WCHAR> imagePath = new WCHAR[MAX_LONGPATH];
if (FAILED(hr = g_sos->GetPEFileName(m_peFile, MAX_LONGPATH, imagePath.GetPtr(), NULL))) {
return hr;
}
IMAGE_DOS_HEADER DosHeader;
if (FAILED(hr = g_ExtData->ReadVirtual(baseAddress, &DosHeader, sizeof(DosHeader), NULL))) {
return hr;
}
IMAGE_NT_HEADERS Header;
if (FAILED(hr = g_ExtData->ReadVirtual(baseAddress + DosHeader.e_lfanew, &Header, sizeof(Header), NULL))) {
return hr;
}
// If there is no COMHeader, this can not be managed code.
if (Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress == 0) {
return E_ACCESSDENIED;
}
ULONG32 imageSize = Header.OptionalHeader.SizeOfImage;
ULONG32 timeStamp = Header.FileHeader.TimeDateStamp;
ULONG32 bufferSize = (ULONG32)Size();
ArrayHolder<BYTE> buffer = new NOTHROW BYTE[bufferSize];
if (buffer == nullptr) {
return E_OUTOFMEMORY;
}
ULONG32 actualSize = 0;
if (FAILED(hr = GetMetadataLocator(imagePath, timeStamp, imageSize, nullptr, 0, 0, bufferSize, buffer, &actualSize))) {
return hr;
}
m_metadataMemory = buffer.Detach();
}
return S_OK;
}
public:
MemoryRegion(uint64_t start, uint64_t end, CLRDATA_ADDRESS peFile) :
m_startAddress(start),
m_endAddress(end),
m_peFile(peFile),
m_metadataMemory(nullptr),
m_busy(0)
{
}
uint64_t StartAddress() const { return m_startAddress; }
uint64_t EndAddress() const { return m_endAddress; }
uint64_t Size() const { return m_endAddress - m_startAddress; }
CLRDATA_ADDRESS const PEFile() { return m_peFile; }
bool operator<(const MemoryRegion& rhs) const
{
return (m_startAddress < rhs.m_startAddress) && (m_endAddress <= rhs.m_startAddress);
}
// Returns true if "rhs" is wholly contained in this one
bool Contains(const MemoryRegion& rhs) const
{
return (m_startAddress <= rhs.m_startAddress) && (m_endAddress >= rhs.m_endAddress);
}
HRESULT ReadMetadata(CLRDATA_ADDRESS address, ULONG32 bufferSize, BYTE* buffer)
{
_ASSERTE((m_startAddress <= address) && (m_endAddress >= (address + bufferSize)));
HRESULT hr = E_ACCESSDENIED;
// Skip in-memory and dynamic modules or if CacheMetadata failed
if (m_peFile != 0)
{
if (InterlockedIncrement(&m_busy) == 1)
{
// Attempt to get the assembly metadata from local file or by downloading from a symbol server
hr = CacheMetadata();
if (FAILED(hr)) {
// If we can get the metadata from the assembly, mark this region to always fail.
m_peFile = 0;
}
}
InterlockedDecrement(&m_busy);
}
if (FAILED(hr)) {
return hr;
}
// Read the memory from the cached metadata blob
_ASSERTE(m_metadataMemory != nullptr);
uint64_t offset = address - m_startAddress;
memcpy(buffer, m_metadataMemory + offset, bufferSize);
return S_OK;
}
void Dispose()
{
if (m_metadataMemory != nullptr)
{
delete[] m_metadataMemory;
m_metadataMemory = nullptr;
}
}
};
std::set<MemoryRegion> g_metadataRegions;
bool g_metadataRegionsPopulated = false;
void FlushMetadataRegions()
{
for (const MemoryRegion& region : g_metadataRegions)
{
const_cast<MemoryRegion&>(region).Dispose();
}
g_metadataRegions.clear();
g_metadataRegionsPopulated = false;
}
void PopulateMetadataRegions()
{
g_metadataRegions.clear();
// Only populate the metadata regions if core dump
if (IsDumpFile())
{
int numModule;
ArrayHolder<DWORD_PTR> moduleList = ModuleFromName(NULL, &numModule);
if (moduleList != nullptr)
{
for (int i = 0; i < numModule; i++)
{
DacpModuleData moduleData;
if (SUCCEEDED(moduleData.Request(g_sos, moduleList[i])))
{
if (moduleData.metadataStart != 0)
{
MemoryRegion region(moduleData.metadataStart, moduleData.metadataStart + moduleData.metadataSize, moduleData.File);
g_metadataRegions.insert(region);
#ifdef DUMP_METADATA_INFO
ArrayHolder<WCHAR> name = new WCHAR[MAX_LONGPATH];
name[0] = '\0';
if (moduleData.File != 0)
{
g_sos->GetPEFileName(moduleData.File, MAX_LONGPATH, name.GetPtr(), NULL);
}
ExtOut("%016x %016x %016x %S\n", moduleData.metadataStart, moduleData.metadataStart + moduleData.metadataSize, moduleData.metadataSize, name.GetPtr());
#endif
}
}
}
}
else
{
ExtDbgOut("PopulateMetadataRegions ModuleFromName returns null\n");
}
}
}
HRESULT GetMetadataMemory(CLRDATA_ADDRESS address, ULONG32 bufferSize, BYTE* buffer)
{
// Populate the metadata memory region map
if (!g_metadataRegionsPopulated)
{
g_metadataRegionsPopulated = true;
PopulateMetadataRegions();
}
// Check if the memory address is in a metadata memory region
MemoryRegion region(address, address + bufferSize, 0);
const auto& found = g_metadataRegions.find(region);
if (found != g_metadataRegions.end() && found->Contains(region)) {
return const_cast<MemoryRegion&>(*found).ReadMetadata(address, bufferSize, buffer);
}
return E_ACCESSDENIED;
}
#endif // FEATURE_PAL
| 176,374
| 56,156
|
/*
***************************************************************************
*
* $Id$
*
*
***************************************************************************
*
*
*
*
***************************************************************************
*
* $Log$
* Revision 1.3 2007/05/22 09:01:42 akisiel
* Add the possibiloity to save cut settings in the ROOT file
*
* Revision 1.2 2007/05/21 10:38:25 akisiel
* More coding rule conformance
*
* Revision 1.1 2007/05/16 10:25:06 akisiel
* Making the directory structure of AliFemtoUser flat. All files go into one common directory
*
* Revision 1.4 2007/05/03 09:46:10 akisiel
* Fixing Effective C++ warnings
*
* Revision 1.3 2007/04/27 07:25:59 akisiel
* Make revisions needed for compilation from the main AliRoot tree
*
* Revision 1.1.1.1 2007/04/25 15:38:41 panos
* Importing the HBT code dir
*
* Revision 1.4 2007-04-03 16:00:08 mchojnacki
* Changes to iprove memory managing
*
* Revision 1.3 2007/03/13 15:30:03 mchojnacki
* adding reader for simulated data
*
* Revision 1.2 2007/03/08 14:58:03 mchojnacki
* adding some alice stuff
*
* Revision 1.1.1.1 2007/03/07 10:14:49 mchojnacki
* First version on CVS
*
**************************************************************************/
#include "AliFemtoESDTrackCut.h"
#include <cstdio>
#ifdef __ROOT__
/// \cond CLASSIMP
ClassImp(AliFemtoESDTrackCut);
/// \endcond
#endif
// electron
// 0.13 - 1.8
// 0 7.594129e-02 8.256141e-03
// 1 -5.535827e-01 8.170825e-02
// 2 1.728591e+00 3.104210e-01
// 3 -2.827893e+00 5.827802e-01
// 4 2.503553e+00 5.736207e-01
// 5 -1.125965e+00 2.821170e-01
// 6 2.009036e-01 5.438876e-02
// pion
// 0.13 - 2.0
// 0 1.063457e+00 8.872043e-03
// 1 -4.222208e-01 2.534402e-02
// 2 1.042004e-01 1.503945e-02
// kaon
// 0.18 - 2.0
// 0 -7.289406e-02 1.686074e-03
// 1 4.415666e-01 1.143939e-02
// 2 -2.996790e-01 1.840964e-02
// 3 6.704652e-02 7.783990e-03
// proton
// 0.26 - 2.0
// 0 -3.730200e-02 2.347311e-03
// 1 1.163684e-01 1.319316e-02
// 2 8.354116e-02 1.997948e-02
// 3 -4.608098e-02 8.336400e-03
AliFemtoESDTrackCut::AliFemtoESDTrackCut():
fCharge(0), // takes both charges 0
fLabel(false),
fStatus(0),
fPIDMethod(knSigma),
fNsigmaTPCTOF(kFALSE),
fNsigmaTPConly(kFALSE),
fNsigma(3.),
fminTPCclsF(0),
fminTPCncls(0),
fminITScls(0),
fMaxITSchiNdof(1000.0),
fMaxTPCchiNdof(1000.0),
fMaxSigmaToVertex(1000.0),
fNTracksPassed(0),
fNTracksFailed(0),
fRemoveKinks(kFALSE),
fRemoveITSFake(kFALSE),
fMostProbable(0),
fMaxImpactXY(1000.0),
fMinImpactXY(-1000.0),
fMaxImpactZ(1000.0),
fMaxImpactXYPtOff(1000.0),
fMaxImpactXYPtNrm(1000.0),
fMaxImpactXYPtPow(1000.0),
fMinPforTOFpid(0.0),
fMaxPforTOFpid(10000.0),
fMinPforTPCpid(0.0),
fMaxPforTPCpid(10000.0),
fMinPforITSpid(0.0),
fMaxPforITSpid(10000.0),
fElectronRejection(0)
{
// Default constructor
fPt[0]=0.0; fPt[1] = 100.0;//100
fRapidity[0]=-2; fRapidity[1]=2;//-2 2
fEta[0]=-2; fEta[1]=2;//-2 2
// all Probabilities range from [-1.0, 2.0]
fPidProbElectron[0] = fPidProbPion[0] = fPidProbKaon[0] = fPidProbProton[0] = fPidProbMuon[0]=-1.0;
fPidProbElectron[1] = fPidProbPion[1] = fPidProbKaon[1] = fPidProbProton[1] = fPidProbMuon[1]=2.0;
for (Int_t i = 0; i < 3; i++)
fCutClusterRequirementITS[i] = AliESDtrackCuts::kOff;
}
//------------------------------
AliFemtoESDTrackCut::~AliFemtoESDTrackCut()
{
/* noop */
}
//------------------------------
bool AliFemtoESDTrackCut::Pass(const AliFemtoTrack* track)
{
//cout<<"AliFemtoESDTrackCut::Pass"<<endl;
// test the particle and return
// true if it meets all the criteria
// false if it doesn't meet at least one of the criteria
float tMost[5];
if (fStatus && (track->Flags() & fStatus) != fStatus) {
return false;
}
if (fRemoveKinks && (track->KinkIndex(0) || track->KinkIndex(1) || track->KinkIndex(2))) {
return false;
}
if (fRemoveITSFake && track->ITSncls() < 0) {
return false;
}
if (fminTPCclsF > track->TPCnclsF()) {
return false;
}
if (fminTPCncls > track->TPCncls()) {
return false;
}
if (fminITScls > track->ITSncls()) {
return false;
}
if (fMaxImpactXY < TMath::Abs(track->ImpactD())) {
return false;
}
if (fMinImpactXY > TMath::Abs(track->ImpactD())) {
return false;
}
if (fMaxImpactZ < TMath::Abs(track->ImpactZ())) {
return false;
}
if (fMaxSigmaToVertex < track->SigmaToVertex()) {
return false;
}
if (track->ITSncls() > 0 && (track->ITSchi2() / track->ITSncls()) > fMaxITSchiNdof) {
return false;
}
if (track->TPCncls() > 0 && (track->TPCchi2() / track->TPCncls()) > fMaxTPCchiNdof) {
return false;
}
// ITS cluster requirenments
for (Int_t i = 0; i < 3; i++) {
if (!CheckITSClusterRequirement(fCutClusterRequirementITS[i], track->HasPointOnITSLayer(i * 2), track->HasPointOnITSLayer(i*2+1))) {
return false;
}
}
if (fLabel) {
if (track->Label() < 0) {
fNTracksFailed++;
return false;
}
}
if (fCharge != 0 && (track->Charge() != fCharge)) {
fNTracksFailed++;
return false;
}
Bool_t tTPCPidIn = (track->Flags() & AliFemtoTrack::kTPCpid) > 0;
Bool_t tITSPidIn = (track->Flags() & AliFemtoTrack::kITSpid) > 0;
Bool_t tTOFPidIn = (track->Flags() & AliFemtoTrack::kTOFpid) > 0;
const double momentum = track->P().Mag();
if (fMinPforTOFpid > 0
&& fMinPforTOFpid < momentum && momentum < fMaxPforTOFpid
&& !tTOFPidIn) {
fNTracksFailed++;
return false;
}
if (fMinPforTPCpid > 0
&& fMinPforTPCpid < momentum && momentum < fMaxPforTPCpid
&& !tTPCPidIn) {
fNTracksFailed++;
return false;
}
if (fMinPforITSpid > 0
&& fMinPforITSpid < momentum && momentum < fMaxPforITSpid
&& !tITSPidIn) {
fNTracksFailed++;
return false;
}
float tEnergy = ::sqrt(track->P().Mag2() + fMass * fMass);
float tRapidity = 0;
if (tEnergy-track->P().z() != 0 && (tEnergy + track->P().z()) / (tEnergy-track->P().z()) > 0)
tRapidity = 0.5 * ::log((tEnergy + track->P().z())/(tEnergy-track->P().z()));
float tPt = track->P().Perp();
float tEta = track->P().PseudoRapidity();
if (fMaxImpactXYPtOff < 999.0) {
if ((fMaxImpactXYPtOff + fMaxImpactXYPtNrm*TMath::Power(tPt, fMaxImpactXYPtPow)) < TMath::Abs(track->ImpactD())) {
fNTracksFailed++;
return false;
}
}
if ((tRapidity < fRapidity[0]) || (tRapidity > fRapidity[1])) {
fNTracksFailed++;
return false;
}
if ((tEta < fEta[0]) || (tEta > fEta[1])) {
fNTracksFailed++;
return false;
}
if ((tPt < fPt[0]) || (tPt > fPt[1])) {
fNTracksFailed++;
return false;
}
// cout << "Track has pids: "
// << track->PidProbElectron() << " "
// << track->PidProbMuon() << " "
// << track->PidProbPion() << " "
// << track->PidProbKaon() << " "
// << track->PidProbProton() << " "
// << track->PidProbElectron()+track->PidProbMuon()+track->PidProbPion()+track->PidProbKaon()+track->PidProbProton() << endl;
if ((track->PidProbElectron() < fPidProbElectron[0]) || (track->PidProbElectron() > fPidProbElectron[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbPion() < fPidProbPion[0]) || (track->PidProbPion() > fPidProbPion[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbKaon() < fPidProbKaon[0]) || (track->PidProbKaon() > fPidProbKaon[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbProton() < fPidProbProton[0]) || (track->PidProbProton() > fPidProbProton[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbMuon() < fPidProbMuon[0]) || (track->PidProbMuon() > fPidProbMuon[1])) {
fNTracksFailed++;
return false;
}
//****N Sigma Method -- electron rejection****
if (fElectronRejection)
if (!IsElectron(track->NSigmaTPCE(),track->NSigmaTPCPi(),track->NSigmaTPCK(), track->NSigmaTPCP()))
return false;
if (fMostProbable) {
int imost=0;
tMost[0] = track->PidProbElectron()*PidFractionElectron(track->P().Mag());
tMost[1] = 0.0;
tMost[2] = track->PidProbPion()*PidFractionPion(track->P().Mag());
tMost[3] = track->PidProbKaon()*PidFractionKaon(track->P().Mag());
tMost[4] = track->PidProbProton()*PidFractionProton(track->P().Mag());
float ipidmax = 0.0;
//****N Sigma Method****
if (fPIDMethod==0) {
// Looking for pions
if (fMostProbable == 2) {
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi())) {
imost = 2;
}
}
else if (fMostProbable == 3) {
if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK())){
imost = 3;
}
}
else if (fMostProbable == 4) { // proton nsigma-PID required contour adjusting (in LHC10h)
if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP())
// && (TMath::Abs(track->NSigmaTPCP()) < TMath::Abs(track->NSigmaTPCPi()))
// && (TMath::Abs(track->NSigmaTPCP()) < TMath::Abs(track->NSigmaTPCK()))
// && (TMath::Abs(track->NSigmaTOFP()) < TMath::Abs(track->NSigmaTOFPi()))
// && (TMath::Abs(track->NSigmaTOFP()) < TMath::Abs(track->NSigmaTOFK()))
// && IsProtonTPCdEdx(track->P().Mag(), track->TPCsignal())
) {
imost = 4;
}
}
else if (fMostProbable == 13) {
if (IsDeuteronNSigma(track->P().Mag(),track->MassTOF(), fNsigmaMass, track->NSigmaTPCD(), track->NSigmaTOFD()))
imost = 13;
if ((track->P().Mag() < 1) &&!(IsDeuteronTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
}
else if (fMostProbable == 14) {
if (IsTritonNSigma(track->P().Mag(), track->NSigmaTPCT(), track->NSigmaTOFT())){
imost = 14;
}
}
else if (fMostProbable == 15) {
if ( IsHe3NSigma(track->P().Mag(), track->NSigmaTPCH(), track->NSigmaTOFH())
)
imost = 15;
}
else if (fMostProbable == 16) {
if ( IsAlphaNSigma(track->P().Mag(), track->NSigmaTPCA(), track->NSigmaTOFA())
)
imost = 16;
}
else if (fMostProbable == 5) { // no-protons
if ( !IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 5;
}
else if (fMostProbable == 6) { //pions OR kaons OR protons
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 6;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = 6;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 6;
}
else if (fMostProbable == 7) { // pions OR kaons OR protons OR electrons or or or
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 7;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = 7;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 7;
else if (TMath::Abs(track->NSigmaTPCE())<3)
imost = 7;
}
else if (fMostProbable == 8) { // TOF matching
if (track->NSigmaTOFPi() != -1000 || track->Pt()<0.5){
imost = 8;
}
}
else if (fMostProbable == 9) { // Other: no kaons, no pions, no protons
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = -1;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = -1;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = -1;
else if (track->NSigmaTOFPi() != -1000 || track->Pt()<0.5){
imost = 9;
}
}
if (fMostProbable == 10) {//cut on Nsigma in pT not p
if (IsPionNSigma(track->Pt(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 10;
}
else if (fMostProbable == 11) {//cut on Nsigma in pT not p
if (IsKaonNSigma(track->Pt(), track->NSigmaTPCK(), track->NSigmaTOFK())){
imost = 11;
}
}
else if (fMostProbable == 12) { //cut on Nsigma in pT not p
if ( IsProtonNSigma(track->Pt(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 12;
}
}
//****Contour Method****
if (fPIDMethod==1) {
for (int ip=0; ip<5; ip++) {
if (tMost[ip] > ipidmax) {
ipidmax = tMost[ip];
imost = ip;
}
}
// Looking for pions
if (fMostProbable == 2) {
if (imost == 2) {
// Using the TPC to reject non-pions
if (!(IsPionTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
}
if (0) {
// Using the TOF to reject non-pions
if (track->P().Mag() < 0.6) {
if (tTOFPidIn)
if (!IsPionTOFTime(track->P().Mag(), track->TOFpionTime()))
imost = 0;
}
else {
if (tTOFPidIn) {
if (!IsPionTOFTime(track->P().Mag(), track->TOFpionTime()))
imost = 0;
}
else {
imost = 0;
}
}
}
}
}
// Looking for kaons
else if (fMostProbable == 3) {
// if (imost == 3) {
// Using the TPC to reject non-kaons
if (track->P().Mag() < 0.6) {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
} else {
imost = 3;
}
if (1) {
// Using the TOF to reject non-kaons
if (tTOFPidIn)
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
}
}
else {
if (1) {
if (tTOFPidIn) {
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
else
imost = 3;
}
else {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else
imost = 3;
}
}
}
// }
}
// Looking for protons
else if (fMostProbable == 4) {
// if (imost == 3) {
// Using the TPC to reject non-kaons
if (track->P().Mag() < 0.8) {
if (!(IsProtonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else imost = 4;
if (0) {
// Using the TOF to reject non-kaons
if (tTOFPidIn)
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
}
}
else {
if (0) {
if (tTOFPidIn) {
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
else
imost = 3;
}
else {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else
imost = 3;
}
}
}
}
/**********************************/
else if (fMostProbable == 13) {
// if (imost == 3) {
// Using the TPC to reject non-deuterons
if (track->P().Mag() < 1) {
if (!(IsDeuteronTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
} else {
imost = 13;
}
}
}
/*************************************/
}
if (imost != fMostProbable) {
return false;
}
}
//fan
//cout<<"****** Go Through the cut ******"<<endl;
// cout<<fLabel<<" Label="<<track->Label()<<endl;
// cout<<fCharge<<" Charge="<<track->Charge()<<endl;
// cout<<fPt[0]<<" < Pt ="<<Pt<<" <"<<fPt[1]<<endl;
//cout<<fRapidity[0]<<" < Rapidity ="<<tRapidity<<" <"<<fRapidity[1]<<endl;
//cout<<fPidProbElectron[0]<<" < e="<<track->PidProbElectron()<<" <"<<fPidProbElectron[1]<<endl;
//cout<<fPidProbPion[0]<<" < pi="<<track->PidProbPion()<<" <"<<fPidProbPion[1]<<endl;
//cout<<fPidProbKaon[0]<<" < k="<<track->PidProbKaon()<<" <"<<fPidProbKaon[1]<<endl;
//cout<<fPidProbProton[0]<<" < p="<<track->PidProbProton()<<" <"<<fPidProbProton[1]<<endl;
//cout<<fPidProbMuon[0]<<" < mi="<<track->PidProbMuon()<<" <"<<fPidProbMuon[1]<<endl;
fNTracksPassed++ ;
return true;
}
//------------------------------
AliFemtoString AliFemtoESDTrackCut::Report()
{
// Prepare report from the execution
string tStemp;
char tCtemp[100];
snprintf(tCtemp , 100, "Particle mass:\t%E\n",this->Mass());
tStemp=tCtemp;
snprintf(tCtemp , 100, "Particle charge:\t%d\n",fCharge);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle pT:\t%E - %E\n",fPt[0],fPt[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle rapidity:\t%E - %E\n",fRapidity[0],fRapidity[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle eta:\t%E - %E\n",fEta[0],fEta[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Number of tracks which passed:\t%ld Number which failed:\t%ld\n",fNTracksPassed,fNTracksFailed);
tStemp += tCtemp;
AliFemtoString returnThis = tStemp;
return returnThis;
}
TList *AliFemtoESDTrackCut::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
char buf[200];
snprintf(buf, 200, "AliFemtoESDTrackCut.mass=%f", this->Mass());
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.charge=%i", fCharge);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobpion.minimum=%f", fPidProbPion[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobpion.maximum=%f", fPidProbPion[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobkaon.minimum=%f", fPidProbKaon[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobkaon.maximum=%f", fPidProbKaon[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobproton.minimum=%f", fPidProbProton[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobproton.maximum=%f", fPidProbProton[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobelectron.minimum=%f", fPidProbElectron[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobelectron.maximum=%f", fPidProbElectron[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobMuon.minimum=%f", fPidProbMuon[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobMuon.maximum=%f", fPidProbMuon[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.minimumtpcclusters=%i", fminTPCclsF);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.minimumitsclusters=%i", fminTPCclsF);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pt.minimum=%f", fPt[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pt.maximum=%f", fPt[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.rapidity.minimum=%f", fRapidity[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.rapidity.maximum=%f", fRapidity[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.removekinks=%i", fRemoveKinks);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxitschindof=%f", fMaxITSchiNdof);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxtpcchindof=%f", fMaxTPCchiNdof);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxsigmatovertex=%f", fMaxSigmaToVertex);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maximpactxy=%f", fMaxImpactXY);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maximpactz=%f", fMaxImpactZ);
tListSetttings->AddLast(new TObjString(buf));
if (fMostProbable) {
if (fMostProbable == 2)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Pion");
if (fMostProbable == 3)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Kaon");
if (fMostProbable == 4)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Proton");
tListSetttings->AddLast(new TObjString(buf));
}
return tListSetttings;
}
void AliFemtoESDTrackCut::SetRemoveKinks(const bool& flag)
{
fRemoveKinks = flag;
}
void AliFemtoESDTrackCut::SetRemoveITSFake(const bool& flag)
{
fRemoveITSFake = flag;
}
// electron
// 0.13 - 1.8
// 0 7.594129e-02 8.256141e-03
// 1 -5.535827e-01 8.170825e-02
// 2 1.728591e+00 3.104210e-01
// 3 -2.827893e+00 5.827802e-01
// 4 2.503553e+00 5.736207e-01
// 5 -1.125965e+00 2.821170e-01
// 6 2.009036e-01 5.438876e-02
float AliFemtoESDTrackCut::PidFractionElectron(float mom) const
{
// Provide a parameterized fraction of electrons dependent on momentum
if (mom<0.13)
return (7.594129e-02
-5.535827e-01*0.13
+1.728591e+00*0.13*0.13
-2.827893e+00*0.13*0.13*0.13
+2.503553e+00*0.13*0.13*0.13*0.13
-1.125965e+00*0.13*0.13*0.13*0.13*0.13
+2.009036e-01*0.13*0.13*0.13*0.13*0.13*0.13);
if (mom>1.8)
return (7.594129e-02
-5.535827e-01*1.8
+1.728591e+00*1.8*1.8
-2.827893e+00*1.8*1.8*1.8
+2.503553e+00*1.8*1.8*1.8*1.8
-1.125965e+00*1.8*1.8*1.8*1.8*1.8
+2.009036e-01*1.8*1.8*1.8*1.8*1.8*1.8);
return (7.594129e-02
-5.535827e-01*mom
+1.728591e+00*mom*mom
-2.827893e+00*mom*mom*mom
+2.503553e+00*mom*mom*mom*mom
-1.125965e+00*mom*mom*mom*mom*mom
+2.009036e-01*mom*mom*mom*mom*mom*mom);
}
// pion
// 0.13 - 2.0
// 0 1.063457e+00 8.872043e-03
// 1 -4.222208e-01 2.534402e-02
// 2 1.042004e-01 1.503945e-02
float AliFemtoESDTrackCut::PidFractionPion(float mom) const
{
// Provide a parameterized fraction of pions dependent on momentum
if (mom<0.13)
return ( 1.063457e+00
-4.222208e-01*0.13
+1.042004e-01*0.0169);
if (mom>2.0)
return ( 1.063457e+00
-4.222208e-01*2.0
+1.042004e-01*4.0);
return ( 1.063457e+00
-4.222208e-01*mom
+1.042004e-01*mom*mom);
}
// kaon
// 0.18 - 2.0
// 0 -7.289406e-02 1.686074e-03
// 1 4.415666e-01 1.143939e-02
// 2 -2.996790e-01 1.840964e-02
// 3 6.704652e-02 7.783990e-03
float AliFemtoESDTrackCut::PidFractionKaon(float mom) const
{
// Provide a parameterized fraction of kaons dependent on momentum
if (mom<0.18)
return (-7.289406e-02
+4.415666e-01*0.18
-2.996790e-01*0.18*0.18
+6.704652e-02*0.18*0.18*0.18);
if (mom>2.0)
return (-7.289406e-02
+4.415666e-01*2.0
-2.996790e-01*2.0*2.0
+6.704652e-02*2.0*2.0*2.0);
return (-7.289406e-02
+4.415666e-01*mom
-2.996790e-01*mom*mom
+6.704652e-02*mom*mom*mom);
}
// proton
// 0.26 - 2.0
// 0 -3.730200e-02 2.347311e-03
// 1 1.163684e-01 1.319316e-02
// 2 8.354116e-02 1.997948e-02
// 3 -4.608098e-02 8.336400e-03
float AliFemtoESDTrackCut::PidFractionProton(float mom) const
{
// Provide a parameterized fraction of protons dependent on momentum
if (mom<0.26) return 0.0;
if (mom>2.0)
return (-3.730200e-02
+1.163684e-01*2.0
+8.354116e-02*2.0*2.0
-4.608098e-02*2.0*2.0*2.0);
return (-3.730200e-02
+1.163684e-01*mom
+8.354116e-02*mom*mom
-4.608098e-02*mom*mom*mom);
}
void AliFemtoESDTrackCut::SetMomRangeTOFpidIs(const float& minp, const float& maxp)
{
fMinPforTOFpid = minp;
fMaxPforTOFpid = maxp;
}
void AliFemtoESDTrackCut::SetMomRangeTPCpidIs(const float& minp, const float& maxp)
{
fMinPforTPCpid = minp;
fMaxPforTPCpid = maxp;
}
void AliFemtoESDTrackCut::SetMomRangeITSpidIs(const float& minp, const float& maxp)
{
fMinPforITSpid = minp;
fMaxPforITSpid = maxp;
}
bool AliFemtoESDTrackCut::IsPionTPCdEdx(float mom, float dEdx)
{
// double a1 = -95.4545, b1 = 86.5455;
// double a2 = 0.0, b2 = 56.0;
double a1 = -343.75, b1 = 168.125;
double a2 = 0.0, b2 = 65.0;
if (mom < 0.32) {
if (dEdx < a1*mom+b1) return true;
}
if (dEdx < a2*mom+b2) return true;
return false;
}
bool AliFemtoESDTrackCut::IsKaonTPCdEdx(float mom, float dEdx)
{
// double a1 = -547.0; double b1 = 297.0;
// double a2 = -125.0; double b2 = 145.0;
// double a3 = -420.0; double b3 = 357.0;
// double a4 = -110.0; double b4 = 171.0;
// double b5 = 72.0;
// if (mom<0.2) return false;
// if (mom<0.36) {
// if (dEdx < a1*mom+b1) return false;
// if (dEdx > a3*mom+b3) return false;
// }
// else if (mom<0.6) {
// if (dEdx < a2*mom+b2) return false;
// if (dEdx > a3*mom+b3) return false;
// }
// else if (mom<0.9) {
// if (dEdx > a4*mom+b4) return false;
// if (dEdx < b5) return false;
// }
// else
// return false;
// // else {
// // if (dEdx > b5) return false;
// // }
// return true;
double a1 = -268.896; double b1 = 198.669;
double a2 = -49.0012; double b2 = 88.7214;
if (mom<0.2) return false;
if (mom>0.3 && mom<0.5) {
if (dEdx < a1*mom+b1) return false;
}
else if (mom<1.2) {
if (dEdx < a2*mom+b2) return false;
}
return true;
}
bool AliFemtoESDTrackCut::IsDeuteronTPCdEdx(float mom, float dEdx)
{
double a1 = -250.0, b1 = 400.0;
double a2 = 0.0, b2 = 30.0;
if (mom < 1) {
if (dEdx < a1*mom+b1) return false;
}
//if (dEdx < a2*mom+b2) return true;
return true;
}
bool AliFemtoESDTrackCut::IsProtonTPCdEdx(float mom, float dEdx)
{
double a1 = -1800.0; double b1 = 940.0;
double a2 = -500.0; double b2 = 420.0;
double a3 = -216.7; double b3 = 250.0;
if (mom<0.2) return false;
if (mom>0.3 && mom<0.4) {
if (dEdx < a1*mom+b1) return false;
}
else if (mom<0.6) {
if (dEdx < a2*mom+b2) return false;
}
else if (mom<0.9) {
if (dEdx < a3*mom+b3) return false;
}
return true;
}
bool AliFemtoESDTrackCut::IsPionTOFTime(float mom, float ttof)
{
double a1 = -427.0; double b1 = 916.0;
double a2 = 327.0; double b2 = -888.0;
if (mom<0.3) return kFALSE;
if (mom>2.0) return kFALSE;
if (ttof > a1*mom+b1) return kFALSE;
if (ttof < a2*mom+b2) return kFALSE;
return kTRUE;
}
bool AliFemtoESDTrackCut::IsKaonTOFTime(float mom, float ttof)
{
double a1 = 000.0; double b1 = -500.0;
double a2 = 000.0; double b2 = 500.0;
double a3 = 850.0; double b3 = -1503.0;
double a4 = -1637.0; double b4 = 3621.0;
if (mom<0.3) return kFALSE;
if (mom>2.06) return kFALSE;
if (mom<1.2) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a1*mom+b1) return kFALSE;
}
if (mom<1.9) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
if (mom<2.06) {
if (ttof > a4*mom+b4) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
return kTRUE;
}
bool AliFemtoESDTrackCut::IsProtonTOFTime(float mom, float ttof)
{
double a1 = 000.0; double b1 = -915.0;
double a2 = 000.0; double b2 = 600.0;
double a3 = 572.0; double b3 = -1715.0;
if (mom<0.3) return kFALSE;
if (mom>3.0) return kFALSE;
if (mom<1.4) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a1*mom+b1) return kFALSE;
}
if (mom<3.0) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
return kTRUE;
}
bool AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma(float mom, float nsigmaK)
{
// cout<<" AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma "<<mom<<" "<<nsigmaK<<endl;
if (mom<0.35 && TMath::Abs(nsigmaK)<5.0) return true;
if (mom>=0.35 && mom<0.5 && TMath::Abs(nsigmaK)<3.0) return true;
if (mom>=0.5 && mom<0.7 && TMath::Abs(nsigmaK)<2.0) return true;
return false;
}
bool AliFemtoESDTrackCut::IsKaonTOFNSigma(float mom, float nsigmaK)
{
// cout<<" AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma "<<mom<<" "<<nsigmaK<<endl;
//fan
// if (mom<1.5 && TMath::Abs(nsigmaK)<3.0) return true;
if (mom>=1.5 && TMath::Abs(nsigmaK)<2.0) return true;
return false;
}
/*
bool AliFemtoESDTrackCut::IsKaonNSigma(float mom, float nsigmaTPCK, float nsigmaTOFK)
{
if (mom<0.5)
{
if (TMath::Abs(nsigmaTPCK)<2.0)
{
return true;
}
else
{
return false;
}
}
if (mom>=0.5)
{
if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
else
{
return false;
}
}
// if (mom>1.5 || mom<0.15) return false;
}
*/
//old
bool AliFemtoESDTrackCut::IsKaonNSigma(float mom, float nsigmaTPCK, float nsigmaTOFK)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if (TMath::Hypot( nsigmaTOFK, nsigmaTPCK ) < fNsigma)
return true;
}
else {
if (TMath::Abs(nsigmaTPCK) < fNsigma)
return true;
}
}
else {
if (mom<0.4)
{
if (nsigmaTOFK<-999.)
{
if (TMath::Abs(nsigmaTPCK)<2.0) return true;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
}
else if (mom>=0.4 && mom<=0.6)
{
if (nsigmaTOFK < -999.)
{
if (TMath::Abs(nsigmaTPCK)<2.0) return true;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
}
else if (nsigmaTOFK < -999.)
{
return false;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsPionNSigma(float mom, float nsigmaTPCPi, float nsigmaTOFPi)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
return TMath::Hypot( nsigmaTOFPi, nsigmaTPCPi ) < fNsigma;
}
return TMath::Abs(nsigmaTPCPi) < fNsigma;
}
if (mom < 0.65) {
if (nsigmaTOFPi < -999.) {
if (mom < 0.35 && TMath::Abs(nsigmaTPCPi)<3.0) return true;
else if (mom<0.5 && mom>=0.35 && TMath::Abs(nsigmaTPCPi)<3.0) return true;
else if (mom>=0.5 && TMath::Abs(nsigmaTPCPi)<2.0) return true;
else return false;
}
else if (TMath::Abs(nsigmaTOFPi)<3.0 && TMath::Abs(nsigmaTPCPi)<3.0) {
return true;
}
}
else if (nsigmaTOFPi < -999.) {
return false;
}
else if (mom<1.5 && TMath::Abs(nsigmaTOFPi)<3.0 && TMath::Abs(nsigmaTPCPi)<5.0) {
return true;
}
else if (mom>=1.5 && TMath::Abs(nsigmaTOFPi)<2.0 && TMath::Abs(nsigmaTPCPi)<5.0) {
return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsProtonNSigma(float mom, float nsigmaTPCP, float nsigmaTOFP)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP ) < fNsigma)
return true;
} else if (TMath::Abs(nsigmaTPCP) < fNsigma) {
return true;
}
}
else if (fNsigmaTPConly) {
if (TMath::Abs(nsigmaTPCP) < fNsigma)
return true;
}
else {
if (mom > 0.8 && mom < 2.5) {
if ( TMath::Abs(nsigmaTPCP) < 3.0 && TMath::Abs(nsigmaTOFP) < 3.0)
return true;
}
else if (mom > 2.5) {
if ( TMath::Abs(nsigmaTPCP) < 3.0 && TMath::Abs(nsigmaTOFP) < 2.0)
return true;
}
else {
if (TMath::Abs(nsigmaTPCP) < 3.0)
return true;
}
}
return false;
}
/***********************************************************************/
bool AliFemtoESDTrackCut::IsDeuteronNSigma(float mom, float massTOFPDG,float sigmaMass, float nsigmaTPCD, float nsigmaTOFD)
{
double massPDGD=1.8756;
if (fNsigmaTPCTOF) {
if (mom > 1) { //if TOF avaliable: && (nsigmaTOFD != -1000) --> always TOF
//if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if ((TMath::Hypot( nsigmaTOFD, nsigmaTPCD ) < fNsigma) && (TMath::Abs(massTOFPDG-massPDGD*massPDGD)<sigmaMass))
return true;
}
else {
if (TMath::Abs(nsigmaTPCD) < fNsigma)
return true;
}
}
return false;
}
bool AliFemtoESDTrackCut::IsTritonNSigma(float mom, float nsigmaTPCT, float nsigmaTOFT)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<2 && TMath::Abs(nsigmaTPCT)<fNsigma) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsHe3NSigma(float mom, float nsigmaTPCH, float nsigmaTOFH)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<3 && TMath::Abs(nsigmaTPCH)<fNsigma) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsAlphaNSigma(float mom, float nsigmaTPCA, float nsigmaTOFA)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<3 && TMath::Abs(nsigmaTPCA)<fNsigma) return true;
}
return false;
}
//
/*********************************************************************/
void AliFemtoESDTrackCut::SetPIDMethod(ReadPIDMethodType newMethod)
{
fPIDMethod = newMethod;
}
void AliFemtoESDTrackCut::SetNsigmaTPCTOF(Bool_t nsigma)
{
fNsigmaTPCTOF = nsigma;
}
void AliFemtoESDTrackCut::SetNsigmaTPConly(Bool_t nsigma)
{
fNsigmaTPConly = nsigma;
}
void AliFemtoESDTrackCut::SetNsigma(Double_t nsigma)
{
fNsigma = nsigma;
}
void AliFemtoESDTrackCut::SetNsigmaMass(Double_t nsigma)
{
fNsigmaMass = nsigma;
}
void AliFemtoESDTrackCut::SetClusterRequirementITS(AliESDtrackCuts::Detector det, AliESDtrackCuts::ITSClusterRequirement req)
{
fCutClusterRequirementITS[det] = req;
}
Bool_t AliFemtoESDTrackCut::CheckITSClusterRequirement(AliESDtrackCuts::ITSClusterRequirement req, Bool_t clusterL1, Bool_t clusterL2)
{
// checks if the cluster requirement is fullfilled (in this case: return kTRUE)
switch (req) {
case AliESDtrackCuts::kOff: return kTRUE;
case AliESDtrackCuts::kNone: return !clusterL1 && !clusterL2;
case AliESDtrackCuts::kAny: return clusterL1 || clusterL2;
case AliESDtrackCuts::kFirst: return clusterL1;
case AliESDtrackCuts::kOnlyFirst: return clusterL1 && !clusterL2;
case AliESDtrackCuts::kSecond: return clusterL2;
case AliESDtrackCuts::kOnlySecond: return clusterL2 && !clusterL1;
case AliESDtrackCuts::kBoth: return clusterL1 && clusterL2;
}
return kFALSE;
}
bool AliFemtoESDTrackCut::IsElectron(float nsigmaTPCE, float nsigmaTPCPi,float nsigmaTPCK, float nsigmaTPCP)
{
if (TMath::Abs(nsigmaTPCE)<3 && TMath::Abs(nsigmaTPCPi)>3 && TMath::Abs(nsigmaTPCK)>3 && TMath::Abs(nsigmaTPCP)>3)
return false;
else
return true;
}
| 36,032
| 16,614
|
#ifndef RBX_FLOAT_HPP
#define RBX_FLOAT_HPP
#include "builtin/class.hpp"
#include "builtin/object.hpp"
#include "type_info.hpp"
/* Begin borrowing from MRI 1.8.6 stable */
#if defined(__FreeBSD__) && __FreeBSD__ < 4
#include <floatingpoint.h>
#endif
#include <math.h>
#include <float.h>
namespace rubinius {
class Array;
class String;
class Float : public Numeric {
public:
const static object_type type = FloatType;
double val;
static void init(STATE);
static Float* create(STATE, double val);
static Float* create(STATE, float val);
static Float* create(STATE, native_int val);
static Float* coerce(STATE, Object* value);
double to_double(STATE) { return val; }
void into_string(STATE, char* buf, size_t sz);
static Float* from_cstr(STATE, const char* str, Object* strict);
// Rubinius.primitive! :float_add
Float* add(STATE, Float* other);
// Rubinius.primitive! :float_add
Float* add(STATE, Integer* other);
// Rubinius.primitive! :float_sub
Float* sub(STATE, Float* other);
// Rubinius.primitive! :float_sub
Float* sub(STATE, Integer* other);
// Rubinius.primitive! :float_mul
Float* mul(STATE, Float* other);
// Rubinius.primitive! :float_mul
Float* mul(STATE, Integer* other);
// Rubinius.primitive! :float_pow
Object* fpow(STATE, Float* other);
// Rubinius.primitive! :float_pow
Float* fpow(STATE, Integer* other);
// Rubinius.primitive! :float_div
Float* div(STATE, Float* other);
// Rubinius.primitive! :float_div
Float* div(STATE, Integer* other);
// Rubinius.primitive! :float_mod
Float* mod(STATE, Float* other);
// Rubinius.primitive! :float_mod
Float* mod(STATE, Integer* other);
// Rubinius.primitive! :float_divmod
Array* divmod(STATE, Float* other);
// Rubinius.primitive! :float_divmod
Array* divmod(STATE, Integer* other);
// Rubinius.primitive :float_neg
Float* neg(STATE);
// Rubinius.primitive! :float_equal
Object* equal(STATE, Float* other);
// Rubinius.primitive! :float_equal
Object* equal(STATE, Integer* other);
// Rubinius.primitive! :float_eql
Object* eql(STATE, Float* other);
// Rubinius.primitive! :float_eql
Object* eql(STATE, Integer* other);
// Rubinius.primitive! :float_compare
Object* compare(STATE, Float* other);
// Rubinius.primitive! :float_compare
Object* compare(STATE, Integer* other);
// Rubinius.primitive! :float_gt
Object* gt(STATE, Float* other);
// Rubinius.primitive! :float_gt
Object* gt(STATE, Integer* other);
// Rubinius.primitive! :float_ge
Object* ge(STATE, Float* other);
// Rubinius.primitive! :float_ge
Object* ge(STATE, Integer* other);
// Rubinius.primitive! :float_lt
Object* lt(STATE, Float* other);
// Rubinius.primitive! :float_lt
Object* lt(STATE, Integer* other);
// Rubinius.primitive! :float_le
Object* le(STATE, Float* other);
// Rubinius.primitive! :float_le
Object* le(STATE, Integer* other);
// Rubinius.primitive :float_isinf
Object* fisinf(STATE);
// Rubinius.primitive :float_isnan
Object* fisnan(STATE);
// Rubinius.primitive :float_round
Integer* fround(STATE);
// Rubinius.primitive :float_to_i
Integer* to_i(STATE);
// Rubinius.primitive :float_to_s_formatted
String* to_s_formatted(STATE, String* format);
// Rubinius.primitive :float_to_s_minimal
String* to_s_minimal(STATE);
// Rubinius.primitive :float_to_packed
String* to_packed(STATE, Object* want_double);
static int radix() { return FLT_RADIX; }
static int rounds() { return FLT_ROUNDS; }
static double min() { return DBL_MIN; }
static double max() { return DBL_MAX; }
static int min_exp() { return DBL_MIN_EXP; }
static int max_exp() { return DBL_MAX_EXP; }
static int min_10_exp() { return DBL_MIN_10_EXP; }
static int max_10_exp() { return DBL_MAX_10_EXP; }
static int dig() { return DBL_DIG; }
static int mant_dig() { return DBL_MANT_DIG; }
static double epsilon() { return DBL_EPSILON; }
class Info : public TypeInfo {
public:
Info(object_type type)
: TypeInfo(type)
{
allow_user_allocate = false;
}
virtual void mark(Object* t, ObjectMark& mark);
virtual void show(STATE, Object* self, int level);
virtual void show_simple(STATE, Object* self, int level);
virtual void auto_mark(Object* obj, ObjectMark& mark) {}
};
};
}
#endif
| 4,595
| 1,609
|
/*
* SignObjectImplementation.cpp
*
* Created on: Nov 20, 2010
* Author: crush
*/
#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h"
#include "server/zone/objects/building/BuildingObject.h"
int SignObjectImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
switch (selectedID) {
case 20: //Read Sign
sendSignNameTo(player);
break;
default:
return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
return 0;
}
void SignObjectImplementation::sendSignNameTo(CreatureObject* player) {
ManagedReference<SuiMessageBox*> suiBox = new SuiMessageBox(player, SuiWindowType::NONE);
suiBox->setPromptTitle("@sui:swg"); //Star Wars Galaxies
suiBox->setPromptText(getDisplayedName());
player->sendMessage(suiBox->generateMessage());
}
void SignObjectImplementation::initializeChildObject(SceneObject* controllerObject) {
if (controllerObject == nullptr)
return;
attachedObject = controllerObject;
if (controllerObject->isBuildingObject())
(cast<BuildingObject*>(controllerObject))->setSignObject(_this.getReferenceUnsafeStaticCast());
}
| 1,253
| 412
|
// license:BSD-3-Clause
// copyright-holders:Fabio Priuli
/***********************************************************************************************************
NES/Famicom cartridge emulation for C&E PCBs
Here we emulate the following PCBs
* C&E Decathlon [mapper 244]
* C&E Feng Shen Bang [mapper 246]
* C&E Sheng Huo Lie Zhuan [mapper 240]
***********************************************************************************************************/
#include "emu.h"
#include "cne.h"
#ifdef NES_PCB_DEBUG
#define VERBOSE 1
#else
#define VERBOSE 0
#endif
#define LOG_MMC(x) do { if (VERBOSE) logerror x; } while (0)
//-------------------------------------------------
// constructor
//-------------------------------------------------
DEFINE_DEVICE_TYPE(NES_CNE_DECATHL, nes_cne_decathl_device, "nes_cne_deca", "NES Cart C&E Decathlon PCB")
DEFINE_DEVICE_TYPE(NES_CNE_FSB, nes_cne_fsb_device, "nes_cne_fsb", "NES Cart C&E Feng Shen Bang PCB")
DEFINE_DEVICE_TYPE(NES_CNE_SHLZ, nes_cne_shlz_device, "nes_cne_shlz", "NES Cart C&E Sheng Huo Lie Zhuan PCB")
nes_cne_decathl_device::nes_cne_decathl_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_CNE_DECATHL, tag, owner, clock)
{
}
nes_cne_fsb_device::nes_cne_fsb_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_CNE_FSB, tag, owner, clock)
{
}
nes_cne_shlz_device::nes_cne_shlz_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_CNE_SHLZ, tag, owner, clock)
{
}
void nes_cne_decathl_device::device_start()
{
common_start();
}
void nes_cne_decathl_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0);
chr8(0, m_chr_source);
}
void nes_cne_fsb_device::device_start()
{
common_start();
}
void nes_cne_fsb_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0xff);
chr8(0, m_chr_source);
}
void nes_cne_shlz_device::device_start()
{
common_start();
}
void nes_cne_shlz_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0);
chr8(0, m_chr_source);
}
/*-------------------------------------------------
mapper specific handlers
-------------------------------------------------*/
/*-------------------------------------------------
C & E Bootleg Board for Decathlon
Games: Decathlon
Pretty simple mapper: writes to 0x8065-0x80a4 set prg32 to
offset & 3; writes to 0x80a5-0x80e4 set chr8 to offset & 7
iNES: mapper 244
In MESS: Supported.
-------------------------------------------------*/
void nes_cne_decathl_device::write_h(offs_t offset, uint8_t data)
{
LOG_MMC(("cne_decathl_w, offset: %04x, data: %02x\n", offset, data));
if (offset < 0x0065)
return;
if (offset < 0x00a5)
{
prg32((offset - 0x0065) & 0x03);
return;
}
if (offset < 0x00e5)
{
chr8((offset - 0x00a5) & 0x07, CHRROM);
}
}
/*-------------------------------------------------
C & E Bootleg Board for Fong Shen Bang
Games: Fong Shen Bang - Zhu Lu Zhi Zhan
Simple mapper: writes to 0x6000-0x67ff set PRG and CHR banks.
Namely, 0x6000->0x6003 select resp. prg8_89, prg8_ab, prg8_cd
and prg8_ef. 0x6004->0x6007 select resp. crh2_0, chr2_2,
chr2_4 and chr2_6. In 0x6800-0x7fff lies WRAM. Battery backed?
iNES: mapper 246
In MESS: Supported.
-------------------------------------------------*/
void nes_cne_fsb_device::write_m(offs_t offset, uint8_t data)
{
LOG_MMC(("cne_fsb write_m, offset: %04x, data: %02x\n", offset, data));
if (offset < 0x0800)
{
switch (offset & 0x0007)
{
case 0x0000:
prg8_89(data);
break;
case 0x0001:
prg8_ab(data);
break;
case 0x0002:
prg8_cd(data);
break;
case 0x0003:
prg8_ef(data);
break;
case 0x0004:
chr2_0(data, CHRROM);
break;
case 0x0005:
chr2_2(data, CHRROM);
break;
case 0x0006:
chr2_4(data, CHRROM);
break;
case 0x0007:
chr2_6(data, CHRROM);
break;
}
}
else
m_battery[offset] = data;
}
uint8_t nes_cne_fsb_device::read_m(offs_t offset)
{
LOG_MMC(("cne_fsb read_m, offset: %04x\n", offset));
if (offset >= 0x0800)
return m_battery[offset];
return 0xff;
}
/*-------------------------------------------------
C & E Bootleg Board for Sheng Huo Lie Zhuan
Games: Jing Ke Xin Zhuan, Sheng Huo Lie Zhuan
Simple Mapper: writes to 0x4020-0x5fff sets prg32 to
data>>4 and chr8 to data&f. We currently do not map
writes to 0x4020-0x40ff (to do: verify if this produces
issues)
iNES: mapper 240
In MESS: Supported.
-------------------------------------------------*/
void nes_cne_shlz_device::write_l(offs_t offset, uint8_t data)
{
LOG_MMC(("cne_shlz write_l, offset: %04x, data: %02x\n", offset, data));
prg32(data >> 4);
chr8(data & 0x0f, CHRROM);
}
| 4,919
| 2,234
|
// Performs the given work function on the data element of the tree and
// on each child.
template<class Function>
void tree::for_all(Function& action)
{
// Perform the action on each child.
parallel_for_each(begin(_children), end(_children), [&](tree& child) {
child.for_all(action);
});
// Perform the action on this node.
action(*this);
}
| 399
| 114
|
#include <bits/stdc++.h>
#include <limits.h>
using namespace std;
#define pb(a) push_back(a)
#define mp(a,b) make_pair(a,b)
#define inf INT_MAX
int waitTime(int period, int tempo)
{
return(period - tempo % period);
}
void dijkstra(vector<vector<pair<int, int> > > graph, int **cost, int start, int period)
{
for (int i = 0; i < period; i ++)
cost[start][i] = 0;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
pq.push({cost[start][0], start});
while (!pq.empty())
{
int tempo = pq.top().first, v = pq.top().second; pq.pop();
for (auto u : graph[v])
{
if (u.second == 0 || tempo % u.second == 0)
{
if (tempo + 1 < cost[u.first][(tempo + 1) % period])
{
cost[u.first][(tempo + 1) % period] = tempo + 1;
pq.push({tempo + 1, u.first});
}
}
else
{
int timeToWait = waitTime(u.second, tempo);
if (tempo + timeToWait + 1 < cost[u.first][(tempo + timeToWait + 1) % period])
{
cost[u.first][(tempo + timeToWait + 1) % period] = tempo + timeToWait + 1;
pq.push({tempo + timeToWait + 1, u.first});
}
}
}
}
}
int main()
{
int run = 0, tests; scanf("%d", &tests);
while (run < tests)
{
int y, x; scanf("%d %d", &y, &x);
vector<vector<pair<int, int> > > graph(y*x);
int totalSize = y*x;
for (int i = 0; i < totalSize; i ++)
{
char line[10];
scanf("%s", line);
for (int j = 0; line[j] != '\0'; j ++)
{
if (line[j] == 'N')
graph[i].pb(mp(i - x, 0));
else if (line[j] == 'E')
graph[i].pb(mp(i + 1, 0));
else if (line[j] == 'S')
graph[i].pb(mp(i + x, 0));
else // 'W'
graph[i].pb(mp(i - 1, 0));
}
}
int portals, period; scanf("%d %d", &portals, &period);
for (int i = 0; i < portals; i ++)
{
int ui, uj, vi, vj; scanf("%d %d %d %d", &ui, &uj, &vi, &vj);
graph[ui*x + uj].pb(mp(vi*x + vj, period));
}
int **cost = (int**) malloc(totalSize * sizeof(int*));
for (int i = 0; i < totalSize; i ++)
{
cost[i] = (int*) malloc(period * sizeof(int));
for (int j = 0; j < period; j ++)
cost[i][j] = inf;
}
dijkstra(graph, cost, 0, period);
int smallestTime = inf;
for (int i = 0; i < period; i ++)
smallestTime = min(smallestTime, cost[totalSize - 1][i]);
printf("%d: %d\n", run, smallestTime);
free(cost);
run ++;
}
return(0);
}
| 2,545
| 1,050
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
namespace dsp
{
class ProcessorChainTest : public UnitTest
{
template <int AddValue>
struct MockProcessor
{
void prepare (const ProcessSpec&) noexcept { isPrepared = true; }
void reset() noexcept { isReset = true; }
template <typename Context>
void process (const Context& context) noexcept
{
bufferWasClear = context.getInputBlock().getSample (0, 0) == 0;
if (! context.isBypassed)
context.getOutputBlock().add (AddValue);
}
bool isPrepared = false;
bool isReset = false;
bool bufferWasClear = false;
};
public:
ProcessorChainTest()
: UnitTest ("ProcessorChain", UnitTestCategories::dsp) {}
void runTest() override
{
beginTest ("After calling setBypass, processor is bypassed");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
setBypassed<0> (chain, true);
expect (isBypassed<0> (chain));
setBypassed<0> (chain, false);
expect (! isBypassed<0> (chain));
setBypassed<1> (chain, true);
expect (isBypassed<1> (chain));
setBypassed<1> (chain, false);
expect (! isBypassed<1> (chain));
}
beginTest ("After calling prepare, all processors are prepared");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
expect (! get<0> (chain).isPrepared);
expect (! get<1> (chain).isPrepared);
chain.prepare (ProcessSpec{});
expect (get<0> (chain).isPrepared);
expect (get<1> (chain).isPrepared);
}
beginTest ("After calling reset, all processors are reset");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
expect (! get<0> (chain).isReset);
expect (! get<1> (chain).isReset);
chain.reset();
expect (get<0> (chain).isReset);
expect (get<1> (chain).isReset);
}
beginTest ("After calling process, all processors contribute to processing");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
AudioBuffer<float> buffer (1, 1);
AudioBlock<float> block (buffer);
ProcessContextReplacing<float> context (block);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 3.0f);
expect (get<0> (chain).bufferWasClear);
expect (! get<1> (chain).bufferWasClear);
setBypassed<0> (chain, true);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 2.0f);
expect (get<0> (chain).bufferWasClear);
expect (get<1> (chain).bufferWasClear);
setBypassed<1> (chain, true);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 0.0f);
expect (get<0> (chain).bufferWasClear);
expect (get<1> (chain).bufferWasClear);
setBypassed<0> (chain, false);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 1.0f);
expect (get<0> (chain).bufferWasClear);
expect (! get<1> (chain).bufferWasClear);
}
beginTest ("Chains with trailing items that only support replacing contexts can be built");
{
AudioBuffer<float> inBuf (1, 1), outBuf (1, 1);
juce::dsp::AudioBlock<float> in (inBuf), out (outBuf);
struct OnlyReplacing
{
void prepare (const juce::dsp::ProcessSpec&) {}
void process (const juce::dsp::ProcessContextReplacing<float>& c)
{
c.getOutputBlock().multiplyBy (2.0f);
}
void reset() {}
};
{
juce::dsp::ProcessorChain<juce::dsp::Gain<float>, OnlyReplacing, OnlyReplacing> c;
juce::dsp::ProcessContextNonReplacing<float> context (in, out);
get<0> (c).setGainLinear (1.0f);
c.prepare (ProcessSpec{});
inBuf.setSample (0, 0, 1.0f);
c.process (context);
expectEquals (outBuf.getSample (0, 0), 4.0f);
}
}
}
};
static ProcessorChainTest processorChainUnitTest;
} // namespace dsp
} // namespace juce
| 5,608
| 1,692
|
//
// composed_3.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff 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)
//
#include <asio/bind_executor.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// In this composed operation we repackage an existing operation, but with a
// different completion handler signature. The asynchronous operation
// requirements are met by delegating responsibility to the underlying
// operation.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler,
tcp::socket& socket, const char* message) const
{
// The async_write operation has a completion handler signature of:
//
// void(std::error_code error, std::size n)
//
// This differs from our operation's signature in that it is also passed
// the number of bytes transferred as an argument of type std::size_t. We
// will adapt our completion handler to async_write's completion handler
// signature by using std::bind, which drops the additional argument.
//
// However, it is essential to the correctness of our composed operation
// that we preserve the executor of the user-supplied completion handler.
// The std::bind function will not do this for us, so we must do this by
// first obtaining the completion handler's associated executor (defaulting
// to the I/O executor - in this case the executor of the socket - if the
// completion handler does not have its own) ...
auto executor = asio::get_associated_executor(
completion_handler, socket.get_executor());
// ... and then binding this executor to our adapted completion handler
// using the asio::bind_executor function.
asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
asio::bind_executor(executor,
std::bind(std::forward<CompletionHandler>(
completion_handler), std::placeholders::_1)));
}
};
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of CompletionToken type and the completion handler's signature. When the
// completion token is a simple callback, the return type is always void.
// In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would be also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>.
-> typename asio::async_result<
typename std::decay<CompletionToken>::type,
void(std::error_code)>::return_type
{
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n",
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "Testing future\r\n", asio::use_future);
io_context.run();
// Get the result of the operation.
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_future();
}
| 7,363
| 1,971
|
#include "msgpass/VarSyncMng.h"
#include "msgpass/PackTransfer.h"
#include <arcane/IParallelMng.h>
#include <arcane/MeshVariableScalarRef.h>
#include <arcane/MeshVariableArrayRef.h>
#include <arcane/VariableBuildInfo.h>
#include <thread>
#include <mpi.h>
/*---------------------------------------------------------------------------*/
/* Equivalent à un var.synchronize() où var est une variable globale */
/* (i.e. non multi-mat) en utilisant des comms non-bloquantes dans des taches*/
/*---------------------------------------------------------------------------*/
template<typename MeshVariableRefT>
void VarSyncMng::globalSynchronizeDevThr(MeshVariableRefT var)
{
if (m_nb_nei==0) {
return;
}
using ItemType = typename MeshVariableRefT::ItemType;
using DataType = typename MeshVariableRefT::DataType;
SyncItems<ItemType>* sync_items = getSyncItems<ItemType>();
auto nb_owned_item_idx_pn = sync_items->nbOwnedItemIdxPn();
auto nb_ghost_item_idx_pn = sync_items->nbGhostItemIdxPn();
auto owned_item_idx_pn = sync_items->ownedItemIdxPn();
auto ghost_item_idx_pn = sync_items->ghostItemIdxPn();
// Pour un ItemType donné, combien de DataType sont utilisés ? => degree
Integer degree = get_var_degree(var);
m_sync_buffers->resetBuf();
// On prévoit une taille max du buffer qui va contenir tous les messages
m_sync_buffers->addEstimatedMaxSz<DataType>(nb_owned_item_idx_pn, degree);
m_sync_buffers->addEstimatedMaxSz<DataType>(nb_ghost_item_idx_pn, degree);
// Le buffer de tous les messages est réalloué si pas assez de place
m_sync_buffers->allocIfNeeded();
// On récupère les adresses et tailles des buffers d'envoi et de réception
// sur l'HOTE (_h et LM_HostMem)
auto buf_snd_h = m_sync_buffers->multiBufView<DataType>(nb_owned_item_idx_pn, degree, 0);
auto buf_rcv_h = m_sync_buffers->multiBufView<DataType>(nb_ghost_item_idx_pn, degree, 0);
// On récupère les adresses et tailles des buffers d'envoi et de réception
// sur le DEVICE (_d et LM_DevMem)
auto buf_snd_d = m_sync_buffers->multiBufView<DataType>(nb_owned_item_idx_pn, degree, 1);
auto buf_rcv_d = m_sync_buffers->multiBufView<DataType>(nb_ghost_item_idx_pn, degree, 1);
#define USE_MPI_REQUEST
#ifdef USE_MPI_REQUEST
//#warning "USE_MPI_REQUEST"
using RequestType = MPI_Request;
#else
using RequestType = Parallel::Request;
#endif
// L'échange proprement dit des valeurs de var
Integer tag=1000;
UniqueArray<RequestType> requests(2*m_nb_nei);
IntegerUniqueArray msg_types(2*m_nb_nei); // nature des messages
// On amorce les réceptions
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
Int32 rank_nei = m_neigh_ranks[inei]; // le rang du inei-ième voisin
// On amorce la réception
auto byte_buf_rcv_h = buf_rcv_h.byteBuf(inei); // le buffer de réception pour inei
#ifdef USE_MPI_REQUEST
MPI_Irecv(byte_buf_rcv_h.data(), byte_buf_rcv_h.size(), MPI_BYTE, rank_nei, tag,
MPI_COMM_WORLD, &(requests[inei]));
#else
requests[inei] = m_pm->recv(byte_buf_rcv_h, rank_nei, /*blocking=*/false);
#endif
msg_types[inei] = inei+1; // >0 pour la réception
}
// La tâche à effectuer pour un voisin
auto lbd_sender = [&](Integer inei, RunQueue& queue) {
Int32 rank_nei = m_neigh_ranks[inei]; // le rang du inei-ième voisin
auto byte_buf_snd_d = buf_snd_d.byteBuf(inei); // le buffer d'envoi pour inei sur le DEVICE
auto byte_buf_snd_h = buf_snd_h.byteBuf(inei); // le buffer d'envoi pour inei sur l'HOTE
// "byte_buf_snd_d <= var"
async_pack_var2buf(owned_item_idx_pn[inei], var, byte_buf_snd_d, queue);
// transfert buf_snd_d[inei] => buf_snd_h[inei]
async_transfer(byte_buf_snd_h, byte_buf_snd_d, queue);
// attendre que la copie sur l'hôte soit terminée pour envoyer les messages
queue.barrier();
// On amorce les envois
#ifdef USE_MPI_REQUEST
MPI_Isend(byte_buf_snd_h.data(), byte_buf_snd_h.size(), MPI_BYTE, rank_nei, tag,
MPI_COMM_WORLD, &(requests[m_nb_nei+inei]));
#else
requests[m_nb_nei+inei] = m_pm->send(byte_buf_snd_h, rank_nei, /*blocking=*/false);
#endif
msg_types[m_nb_nei+inei] = -inei-1; // <0 pour l'envoi
};
//#define USE_THR_SENDER
#ifdef USE_THR_SENDER
#warning "USE_THR_SENDER"
UniqueArray<std::thread*> thr_sender(m_nb_nei);
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
thr_sender[inei] =
new std::thread(lbd_sender, inei, std::ref(m_neigh_queues->queue(inei)));
}
// On attend la fin de tous les threads
for(auto thr : thr_sender) {
thr->join();
delete thr;
}
#else
// On lance en SEQUENTIEL
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
lbd_sender(inei, m_neigh_queues->queue(inei));
}
#endif
// Tache qui unpack les données du buffer reçues par un voisin inei
// copie de var_dev dans buf_dev
// puis transfert buf_dev => buf_hst
auto lbd_unpacker = [&](Integer inei, RunQueue& queue) {
auto byte_buf_rcv_h = buf_rcv_h.byteBuf(inei); // buffer des données reçues sur l'HOTE
auto byte_buf_rcv_d = buf_rcv_d.byteBuf(inei); // buffer des données reçues à transférer sur le DEVICE
// transfert buf_rcv_h[inei] => buf_rcv_d[inei]
async_transfer(byte_buf_rcv_d, byte_buf_rcv_h, queue);
// "var <= buf_rcv_d[inei]"
async_unpack_buf2var(ghost_item_idx_pn[inei], byte_buf_rcv_d, var, queue);
// attendre que les copies soient terminées sur GPU
queue.barrier();
};
UniqueArray<std::thread*> thr_unpacker;
ARCANE_ASSERT(2*m_nb_nei==requests.size(),
("Le nb de requetes n'est pas egal à 2 fois le nb de voisins"));
UniqueArray<RequestType> requests2(2*m_nb_nei);
IntegerUniqueArray msg_types2(2*m_nb_nei);
UniqueArray<bool> is_done_req(2*m_nb_nei);
#ifdef USE_MPI_REQUEST
IntegerUniqueArray array_of_indices(2*m_nb_nei);
#endif
// On utilise des vues pour éviter de réallouer en permanence des tableaux
ArrayView<RequestType> pending_requests(requests.view());
ArrayView<Integer> pending_types(msg_types.view());
ArrayView<RequestType> upd_pending_requests(requests2.view());
ArrayView<Integer> upd_pending_types(msg_types2.view());
ArrayView<RequestType> tmp_pending_requests;
ArrayView<Integer> tmp_pending_types;
Integer nb_iter_wait_some = 0;
Integer nb_pending_rcv = m_nb_nei;
while(nb_pending_rcv>0) {
Integer nb_pending_req = pending_requests.size();
// On dimenensionne is_done_requests au nb de requêtes d'avant waitSomeRequests
// et on initialise à false
ArrayView<bool> is_done_requests(is_done_req.subView(0, nb_pending_req));
for(Integer ireq=0 ; ireq<nb_pending_req ; ++ireq) {
is_done_requests[ireq]=false;
}
// Attente de quelques requetes
#ifdef USE_MPI_REQUEST
Integer nb_req_done=0;
MPI_Waitsome(pending_requests.size(), pending_requests.data(),
&nb_req_done, array_of_indices.data(), MPI_STATUSES_IGNORE);
IntegerArrayView done_indexes(array_of_indices.subView(0, nb_req_done));
#else
IntegerUniqueArray done_indexes = m_pm->waitSomeRequests(pending_requests);
#endif
for(Integer idone_req : done_indexes) {
if (pending_types[idone_req] > 0) { // >0 signifie que c'est une requête de reception
nb_pending_rcv--; // on une requete de reception en moins
// On récupère l'indice du voisin
Integer inei = pending_types[idone_req]-1;
ARCANE_ASSERT(inei>=0 && inei<m_nb_nei, ("Mauvais indice de voisin"));
// Maintenant qu'on a reçu le buffer pour le inei-ième voisin,
// on unpack les donnees dans un thread
//#define USE_THR_UNPACKER
#ifdef USE_THR_UNPACKER
#warning "USE_THR_UNPACKER"
thr_unpacker.add(
new std::thread(lbd_unpacker, inei, std::ref(m_neigh_queues->queue(inei)))
);
#else
lbd_unpacker(inei, m_neigh_queues->queue(inei));
#endif
}
is_done_requests[idone_req] = true;
}
// Il faut créer le nouveau tableau de requêtes pending dans upd_*
Integer upd_nb_pending_req=0;
for(Integer ireq=0 ; ireq<nb_pending_req ; ++ireq) {
if (!is_done_requests[ireq]) {
upd_pending_requests[upd_nb_pending_req]=pending_requests[ireq];
upd_pending_types [upd_nb_pending_req]=pending_types[ireq];
upd_nb_pending_req++;
}
}
// On échange les vues pour qu'à l'itération suivante
// pending_requests pointe vers upd_pending_types
tmp_pending_requests = upd_pending_requests.subView(0, upd_nb_pending_req);
upd_pending_requests = pending_requests;
pending_requests = tmp_pending_requests;
tmp_pending_types = upd_pending_types.subView(0, upd_nb_pending_req);
upd_pending_types = pending_types;
pending_types = tmp_pending_types;
nb_iter_wait_some++;
#if 0
std::ostringstream ostr;
ostr << "P=" << m_pm->commRank()
<< ", iter_wait_some=" << nb_iter_wait_some
<< ", nb_done=" << done_indexes.size();
std::cout << ostr.str() << std::endl;
#endif
}
// Ici, toutes les requetes de receptions sont forcement terminées
// (condition de la boucle while précédente)
// Mais il peut rester encore des requetes d'envoi en cours
if (pending_requests.size()) {
// Normalement, il ne reste que des requêtes d'envois
ARCANE_ASSERT(pending_requests.size()<=m_nb_nei,
("Il ne peut pas rester un nb de requetes d'envoi supérieur au nb de voisins"));
for(Integer msg_type : pending_types) {
ARCANE_ASSERT(msg_type<0,
("Un message d'envoi doit avoir un type négatif ce qui n'est pas le cas"));
}
#if 0
std::ostringstream ostr;
ostr << "P=" << m_pm->commRank()
<< ", WaitAll pending_requests.size()=" << pending_requests.size();
std::cout << ostr.str() << std::endl;
#endif
#ifdef USE_MPI_REQUEST
MPI_Waitall(pending_requests.size(), pending_requests.data(), MPI_STATUSES_IGNORE);
#else
m_pm->waitAllRequests(pending_requests);
#endif
}
#ifdef USE_THR_UNPACKER
#warning "USE_THR_UNPACKER : join"
// On attend la fin de tous les threads unpackers
for(auto thr : thr_unpacker) {
thr->join();
delete thr;
}
#endif
}
/*---------------------------------------------------------------------------*/
/* INSTANCIATIONS STATIQUES */
/*---------------------------------------------------------------------------*/
#define INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(__MeshVariableRefT__) \
template void VarSyncMng::globalSynchronizeDevThr(__MeshVariableRefT__ var)
INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(VariableCellReal);
INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(VariableNodeReal3);
| 10,641
| 4,110
|
/*!
* @file Adafruit_BMP280.cpp
*
* This is a library for the BMP280 orientation sensor
*
* Designed specifically to work with the Adafruit BMP280 Sensor.
*
* Pick one up today in the adafruit shop!
* ------> https://www.adafruit.com/product/2651
*
* These sensors use I2C to communicate, 2 pins are required to interface.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* K.Townsend (Adafruit Industries)
*
* BSD license, all text above must be included in any redistribution
*/
#include "Adafruit_BMP280.h"
#include "Arduino.h"
#include <Wire.h>
/*!
* @brief BMP280 constructor using i2c
* @param *theWire
* optional wire
*/
Adafruit_BMP280::Adafruit_BMP280(TwoWire *theWire)
: _cs(-1), _mosi(-1), _miso(-1), _sck(-1) {
_wire = theWire;
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
Adafruit_BMP280::~Adafruit_BMP280(void) {
delete temp_sensor;
delete pressure_sensor;
}
/*!
* @brief BMP280 constructor using hardware SPI
* @param cspin
* cs pin number
* @param theSPI
* optional SPI object
*/
Adafruit_BMP280::Adafruit_BMP280(int8_t cspin, SPIClass *theSPI)
: _cs(cspin), _mosi(-1), _miso(-1), _sck(-1) {
_spi = theSPI;
}
/*!
* @brief BMP280 constructor using bitbang SPI
* @param cspin
* The pin to use for CS/SSEL.
* @param mosipin
* The pin to use for MOSI.
* @param misopin
* The pin to use for MISO.
* @param sckpin
* The pin to use for SCK.
*/
Adafruit_BMP280::Adafruit_BMP280(int8_t cspin, int8_t mosipin, int8_t misopin,
int8_t sckpin)
: _cs(cspin), _mosi(mosipin), _miso(misopin), _sck(sckpin) {}
/*!
* Initialises the sensor.
* @param addr
* The I2C address to use (default = 0x77)
* @param chipid
* The expected chip ID (used to validate connection).
* @return True if the init was successful, otherwise false.
*/
bool Adafruit_BMP280::begin(uint8_t addr, uint8_t chipid) {
_i2caddr = addr;
if (_cs == -1) {
// i2c
_wire->begin();
} else {
digitalWrite(_cs, HIGH);
pinMode(_cs, OUTPUT);
if (_sck == -1) {
// hardware SPI
_spi->begin();
} else {
// software SPI
pinMode(_sck, OUTPUT);
pinMode(_mosi, OUTPUT);
pinMode(_miso, INPUT);
}
}
if (read8(BMP280_REGISTER_CHIPID) != chipid)
return false;
readCoefficients();
// write8(BMP280_REGISTER_CONTROL, 0x3F); /* needed? */
setSampling();
delay(100);
return true;
}
/*!
* Sets the sampling config for the device.
* @param mode
* The operating mode of the sensor.
* @param tempSampling
* The sampling scheme for temp readings.
* @param pressSampling
* The sampling scheme for pressure readings.
* @param filter
* The filtering mode to apply (if any).
* @param duration
* The sampling duration.
*/
void Adafruit_BMP280::setSampling(sensor_mode mode,
sensor_sampling tempSampling,
sensor_sampling pressSampling,
sensor_filter filter,
standby_duration duration) {
_measReg.mode = mode;
_measReg.osrs_t = tempSampling;
_measReg.osrs_p = pressSampling;
_configReg.filter = filter;
_configReg.t_sb = duration;
write8(BMP280_REGISTER_CONFIG, _configReg.get());
write8(BMP280_REGISTER_CONTROL, _measReg.get());
}
uint8_t Adafruit_BMP280::spixfer(uint8_t x) {
if (_sck == -1)
return _spi->transfer(x);
// software spi
// Serial.println("Software SPI");
uint8_t reply = 0;
for (int i = 7; i >= 0; i--) {
reply <<= 1;
digitalWrite(_sck, LOW);
digitalWrite(_mosi, x & (1 << i));
digitalWrite(_sck, HIGH);
if (digitalRead(_miso))
reply |= 1;
}
return reply;
}
/**************************************************************************/
/*!
@brief Writes an 8 bit value over I2C/SPI
*/
/**************************************************************************/
void Adafruit_BMP280::write8(byte reg, byte value) {
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->write((uint8_t)value);
_wire->endTransmission();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg & ~0x80); // write, bit 7 low
spixfer(value);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
}
/*!
* @brief Reads an 8 bit value over I2C/SPI
* @param reg
* selected register
* @return value from selected register
*/
uint8_t Adafruit_BMP280::read8(byte reg) {
uint8_t value;
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, (byte)1);
value = _wire->read();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
return value;
}
/*!
* @brief Reads a 16 bit value over I2C/SPI
*/
uint16_t Adafruit_BMP280::read16(byte reg) {
uint16_t value;
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, (byte)2);
value = (_wire->read() << 8) | _wire->read();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = (spixfer(0) << 8) | spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
return value;
}
uint16_t Adafruit_BMP280::read16_LE(byte reg) {
uint16_t temp = read16(reg);
return (temp >> 8) | (temp << 8);
}
/*!
* @brief Reads a signed 16 bit value over I2C/SPI
*/
int16_t Adafruit_BMP280::readS16(byte reg) { return (int16_t)read16(reg); }
int16_t Adafruit_BMP280::readS16_LE(byte reg) {
return (int16_t)read16_LE(reg);
}
/*!
* @brief Reads a 24 bit value over I2C/SPI
*/
uint32_t Adafruit_BMP280::read24(byte reg) {
uint32_t value;
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, (byte)3);
value = _wire->read();
value <<= 8;
value |= _wire->read();
value <<= 8;
value |= _wire->read();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = spixfer(0);
value <<= 8;
value |= spixfer(0);
value <<= 8;
value |= spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
return value;
}
/*!
* @brief Reads the factory-set coefficients
*/
void Adafruit_BMP280::readCoefficients() {
_bmp280_calib.dig_T1 = read16_LE(BMP280_REGISTER_DIG_T1);
_bmp280_calib.dig_T2 = readS16_LE(BMP280_REGISTER_DIG_T2);
_bmp280_calib.dig_T3 = readS16_LE(BMP280_REGISTER_DIG_T3);
_bmp280_calib.dig_P1 = read16_LE(BMP280_REGISTER_DIG_P1);
_bmp280_calib.dig_P2 = readS16_LE(BMP280_REGISTER_DIG_P2);
_bmp280_calib.dig_P3 = readS16_LE(BMP280_REGISTER_DIG_P3);
_bmp280_calib.dig_P4 = readS16_LE(BMP280_REGISTER_DIG_P4);
_bmp280_calib.dig_P5 = readS16_LE(BMP280_REGISTER_DIG_P5);
_bmp280_calib.dig_P6 = readS16_LE(BMP280_REGISTER_DIG_P6);
_bmp280_calib.dig_P7 = readS16_LE(BMP280_REGISTER_DIG_P7);
_bmp280_calib.dig_P8 = readS16_LE(BMP280_REGISTER_DIG_P8);
_bmp280_calib.dig_P9 = readS16_LE(BMP280_REGISTER_DIG_P9);
}
/*!
* Reads the temperature from the device.
* @return The temperature in degress celcius.
*/
float Adafruit_BMP280::readTemperature() {
int32_t var1, var2;
int32_t adc_T = read24(BMP280_REGISTER_TEMPDATA);
adc_T >>= 4;
var1 = ((((adc_T >> 3) - ((int32_t)_bmp280_calib.dig_T1 << 1))) *
((int32_t)_bmp280_calib.dig_T2)) >>
11;
var2 = (((((adc_T >> 4) - ((int32_t)_bmp280_calib.dig_T1)) *
((adc_T >> 4) - ((int32_t)_bmp280_calib.dig_T1))) >>
12) *
((int32_t)_bmp280_calib.dig_T3)) >>
14;
t_fine = var1 + var2;
float T = (t_fine * 5 + 128) >> 8;
return T / 100;
}
/*!
* Reads the barometric pressure from the device.
* @return Barometric pressure in Pa.
*/
float Adafruit_BMP280::readPressure() {
int64_t var1, var2, p;
// Must be done first to get the t_fine variable set up
readTemperature();
int32_t adc_P = read24(BMP280_REGISTER_PRESSUREDATA);
adc_P >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)_bmp280_calib.dig_P6;
var2 = var2 + ((var1 * (int64_t)_bmp280_calib.dig_P5) << 17);
var2 = var2 + (((int64_t)_bmp280_calib.dig_P4) << 35);
var1 = ((var1 * var1 * (int64_t)_bmp280_calib.dig_P3) >> 8) +
((var1 * (int64_t)_bmp280_calib.dig_P2) << 12);
var1 =
(((((int64_t)1) << 47) + var1)) * ((int64_t)_bmp280_calib.dig_P1) >> 33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576 - adc_P;
p = (((p << 31) - var2) * 3125) / var1;
var1 = (((int64_t)_bmp280_calib.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
var2 = (((int64_t)_bmp280_calib.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)_bmp280_calib.dig_P7) << 4);
return (float)p / 256;
}
/*!
* @brief Calculates the approximate altitude using barometric pressure and the
* supplied sea level hPa as a reference.
* @param seaLevelhPa
* The current hPa at sea level.
* @return The approximate altitude above sea level in meters.
*/
float Adafruit_BMP280::readAltitude(float seaLevelhPa) {
float altitude;
float pressure = readPressure(); // in Si units for Pascal
pressure /= 100;
altitude = 44330 * (1.0 - pow(pressure / seaLevelhPa, 0.1903));
return altitude;
}
/*!
* Calculates the pressure at sea level (in hPa) from the specified altitude
* (in meters), and atmospheric pressure (in hPa).
* @param altitude Altitude in meters
* @param atmospheric Atmospheric pressure in hPa
* @return The approximate pressure
*/
float Adafruit_BMP280::seaLevelForAltitude(float altitude, float atmospheric) {
// Equation taken from BMP180 datasheet (page 17):
// http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
// Note that using the equation from wikipedia can give bad results
// at high altitude. See this thread for more information:
// http://forums.adafruit.com/viewtopic.php?f=22&t=58064
return atmospheric / pow(1.0 - (altitude / 44330.0), 5.255);
}
/*!
* @brief Take a new measurement (only possible in forced mode)
* !!!todo!!!
*/
/*
void Adafruit_BMP280::takeForcedMeasurement()
{
// If we are in forced mode, the BME sensor goes back to sleep after each
// measurement and we need to set it to forced mode once at this point, so
// it will take the next measurement and then return to sleep again.
// In normal mode simply does new measurements periodically.
if (_measReg.mode == MODE_FORCED) {
// set to forced mode, i.e. "take next measurement"
write8(BMP280_REGISTER_CONTROL, _measReg.get());
// wait until measurement has been completed, otherwise we would read
// the values from the last measurement
while (read8(BMP280_REGISTER_STATUS) & 0x08)
delay(1);
}
}
*/
/*!
* @brief Resets the chip via soft reset
*/
void Adafruit_BMP280::reset(void) {
write8(BMP280_REGISTER_SOFTRESET, MODE_SOFT_RESET_CODE);
}
/*!
@brief Gets the most recent sensor event from the hardware status register.
@return Sensor status as a byte.
*/
uint8_t Adafruit_BMP280::getStatus(void) {
return read8(BMP280_REGISTER_STATUS);
}
/*!
@brief Gets an Adafruit Unified Sensor object for the temp sensor component
@return Adafruit_Sensor pointer to temperature sensor
*/
Adafruit_Sensor *Adafruit_BMP280::getTemperatureSensor(void) {
return temp_sensor;
}
/*!
@brief Gets an Adafruit Unified Sensor object for the pressure sensor
component
@return Adafruit_Sensor pointer to pressure sensor
*/
Adafruit_Sensor *Adafruit_BMP280::getPressureSensor(void) {
return pressure_sensor;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data for the BMP280's temperature sensor
*/
/**************************************************************************/
void Adafruit_BMP280_Temp::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy(sensor->name, "BMP280", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name) - 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
sensor->min_delay = 0;
sensor->max_value = -40.0; /* Temperature range -40 ~ +85 C */
sensor->min_value = +85.0;
sensor->resolution = 0.01; /* 0.01 C */
}
/**************************************************************************/
/*!
@brief Gets the temperature as a standard sensor event
@param event Sensor event object that will be populated
@returns True
*/
/**************************************************************************/
bool Adafruit_BMP280_Temp::getEvent(sensors_event_t *event) {
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
event->timestamp = millis();
event->temperature = _theBMP280->readTemperature();
return true;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data for the BMP280's pressure sensor
*/
/**************************************************************************/
void Adafruit_BMP280_Pressure::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy(sensor->name, "BMP280", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name) - 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_PRESSURE;
sensor->min_delay = 0;
sensor->max_value = 300.0; /* 300 ~ 1100 hPa */
sensor->min_value = 1100.0;
sensor->resolution = 0.012; /* 0.12 hPa relative */
}
/**************************************************************************/
/*!
@brief Gets the pressure as a standard sensor event
@param event Sensor event object that will be populated
@returns True
*/
/**************************************************************************/
bool Adafruit_BMP280_Pressure::getEvent(sensors_event_t *event) {
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_PRESSURE;
event->timestamp = millis();
event->pressure = _theBMP280->readPressure() / 100; // convert Pa to hPa
return true;
}
| 15,750
| 6,374
|
/*
By: facug91
From: http://coj.uci.cu/24h/problem.xhtml?abb=2972
Name: Tobby and Sequence
Number: 2972
Date: 11/07/2014
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <iterator>
#include <utility>
#include <list>
#include <stack>
#include <iomanip>
#include <bitset>
#define MAX_INT 2147483647
#define MAX_LONG 9223372036854775807ll
#define MAX_ULONG 18446744073709551615ull
#define MAX_DBL 1.7976931348623158e+308
#define EPS 1e-9
#define _log2(x) log(x) * 1.44269504088896340736
//const long double PI = 2*acos(0);
#define INF 1000000000
using namespace std;
int n, seq[1005];
int main () {
int t, i, j;
seq[0] = 1;
for (i=1; i<1005; i++)
seq[i] = seq[i-1]+i+1;
reverse(seq, seq+1005);
while (scanf("%d", &n) != EOF) {
printf("%d", seq[0]);
for (i=1; i<n; i++)
printf(" %d", seq[i]);
printf("\n");
}
return 0;
}
| 1,095
| 586
|
// Copyright Dan Corrigan 2020 All Rights Reserved.
#include "OVFPPluginStyle.h"
#include "OVFPPlugin.h"
#include "Framework/Application/SlateApplication.h"
#include "Styling/SlateStyleRegistry.h"
#include "Slate/SlateGameResources.h"
#include "Interfaces/IPluginManager.h"
TSharedPtr< FSlateStyleSet > FOVFPPluginStyle::StyleInstance = NULL;
void FOVFPPluginStyle::Initialize()
{
if (!StyleInstance.IsValid())
{
StyleInstance = Create();
FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
}
}
void FOVFPPluginStyle::Shutdown()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
ensure(StyleInstance.IsUnique());
StyleInstance.Reset();
}
FName FOVFPPluginStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("OVFPPluginStyle"));
return StyleSetName;
}
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
TSharedRef< FSlateStyleSet > FOVFPPluginStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable(new FSlateStyleSet("OVFPPluginStyle"));
Style->SetContentRoot(IPluginManager::Get().FindPlugin("OVFPPlugin")->GetBaseDir() / TEXT("Resources"));
Style->Set("OVFPPlugin.PluginAction", new IMAGE_BRUSH(TEXT("ButtonIcon_40x"), Icon40x40));
return Style;
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
void FOVFPPluginStyle::ReloadTextures()
{
if (FSlateApplication::IsInitialized())
{
FSlateApplication::Get().GetRenderer()->ReloadTextureResources();
}
}
const ISlateStyle& FOVFPPluginStyle::Get()
{
return *StyleInstance;
}
| 2,232
| 853
|
#include "ThreadTask.h"
#include "MyVulkanManager.h"
#include "ShaderQueueSuit_CommonTexLight.h"
void ThreadTask::doTask()
{
MyVulkanManager::init_vulkan_instance();
MyVulkanManager::enumerate_vulkan_phy_devices();
MyVulkanManager::create_vulkan_devices();
MyVulkanManager::create_vulkan_CommandBuffer();
MyVulkanManager::init_queue();
MyVulkanManager::create_vulkan_swapChain();
MyVulkanManager::create_vulkan_DepthBuffer();
MyVulkanManager::create_vulkan_SelfColorBuffer();
MyVulkanManager::create_render_pass_screen();
MyVulkanManager::create_render_pass_self();
MyVulkanManager::create_frame_buffer_screen();
MyVulkanManager::create_frame_buffer_self();
MyVulkanManager::init_texture();
MyVulkanManager::createDrawableObject();
MyVulkanManager::initPipeline();
MyVulkanManager::createFence();
MyVulkanManager::initPresentInfo();
MyVulkanManager::initMatrixAndLight();
MyVulkanManager::drawObject();
MyVulkanManager::destroyPipeline();
MyVulkanManager::destroyDrawableObject();
MyVulkanManager::destroy_textures();
MyVulkanManager::destroy_vulkan_SelfColorBuffer();
MyVulkanManager::destroy_frame_buffer();
MyVulkanManager::destroy_render_pass_self();
MyVulkanManager::destroy_render_pass_screen();
MyVulkanManager::destroy_vulkan_DepthBuffer();
MyVulkanManager::destroy_vulkan_swapChain();
MyVulkanManager::destroy_vulkan_CommandBuffer();
MyVulkanManager::destroy_vulkan_devices();
MyVulkanManager::destroy_vulkan_instance();
}
ThreadTask::ThreadTask()
{
}
ThreadTask:: ~ThreadTask()
{
}
| 1,615
| 542
|
#include <vnl/vnl_matrix_fixed.hxx>
VNL_MATRIX_FIXED_INSTANTIATE(double,2,8);
| 78
| 41
|
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 02 Feb 2014
* 13 Oct 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!
#include <iostream>
#include <string>
template<typename Arr>
void print(const Arr& a)
{
for(const auto& elem : a)
std::cout << elem << std::endl;
}
int main()
{
std::string p[] = {"ssss","aaa","ssssss"};
char c[] = {'a','b','c','d'};
int i[] = {1};
print(i);
print(c);
print(p);
std::cout << "\nexit normally\n";
return 0;
}
| 919
| 310
|
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <algorithm>
#include <memory>
#include <set>
#include <vector>
#include "ops/op_utils.h"
#include "ops/dynamic_resize_nearest_neighbor.h"
#include "utils/check_convert_utils.h"
#include "abstract/ops/primitive_infer_map.h"
#include "mindapi/src/helper.h"
namespace mindspore {
namespace ops {
namespace {
abstract::ShapePtr DynamicResizeNearestNeighborInferShape(const PrimitivePtr &primitive,
const std::vector<AbstractBasePtr> &input_args) {
MS_EXCEPTION_IF_NULL(primitive);
auto prim_name = primitive->name();
auto x_shape_ptr = CheckAndConvertUtils::GetTensorInputShape(prim_name, input_args, 0);
auto x_shape = x_shape_ptr->shape();
const int64_t shape_size = 4;
const int64_t size_size = 2;
(void)CheckAndConvertUtils::CheckInteger("the dimension of input_x", SizeToLong(x_shape.size()), kEqual, shape_size,
prim_name);
auto size = input_args[1];
MS_EXCEPTION_IF_NULL(size);
auto size_v = size->BuildValue();
MS_EXCEPTION_IF_NULL(size_v);
std::vector<int64_t> size_value;
std::vector<int64_t> output_shape;
std::vector<int64_t> min_shape;
std::vector<int64_t> max_shape;
std::vector<int64_t> min_size;
std::vector<int64_t> max_size;
if (size->isa<abstract::AbstractTensor>()) {
if (size_v->isa<tensor::Tensor>()) {
size_value = CheckAndConvertUtils::CheckTensorIntValue("size", size_v, prim_name);
} else {
size_value.push_back(-1);
size_value.push_back(-1);
auto min_value = size->cast<abstract::AbstractTensorPtr>()->get_min_value();
auto max_value = size->cast<abstract::AbstractTensorPtr>()->get_max_value();
if (!min_value || !max_value) {
MS_EXCEPTION(ValueError) << "For 'ResizeNearestNeighbor', inputs['size'] min or max value is can not be empty.";
}
min_size = GetValue<std::vector<int64_t>>(min_value);
max_size = GetValue<std::vector<int64_t>>(max_value);
if (min_size.size() != size_size || max_size.size() != size_size) {
MS_EXCEPTION(ValueError)
<< "For 'ResizeNearestNeighbor', inputs['size'] min and max value size must be 2, but got min: "
<< min_size.size() << ", max: " << max_size.size() << ".";
}
}
} else if (size->isa<abstract::AbstractTuple>()) {
size_value = CheckAndConvertUtils::CheckIntOrTupleInt("size", size_v, prim_name);
}
(void)CheckAndConvertUtils::CheckInteger("the dimension of size", SizeToLong(size_value.size()), kEqual, size_size,
prim_name);
output_shape.push_back(x_shape[0]);
output_shape.push_back(x_shape[1]);
output_shape.push_back(size_value[0]);
output_shape.push_back(size_value[1]);
if (!x_shape_ptr->IsDynamic() && min_size.empty()) {
return std::make_shared<abstract::Shape>(output_shape);
} else if (x_shape_ptr->IsDynamic() && min_size.empty()) {
auto x_min_shape = x_shape_ptr->min_shape();
auto x_max_shape = x_shape_ptr->max_shape();
min_shape.push_back(x_min_shape[0]);
min_shape.push_back(x_min_shape[1]);
min_shape.push_back(size_value[0]);
min_shape.push_back(size_value[1]);
max_shape.push_back(x_max_shape[0]);
max_shape.push_back(x_max_shape[1]);
max_shape.push_back(size_value[0]);
max_shape.push_back(size_value[1]);
} else if (!x_shape_ptr->IsDynamic() && !min_size.empty()) {
min_shape.push_back(x_shape[0]);
min_shape.push_back(x_shape[1]);
min_shape.push_back(min_size[0]);
min_shape.push_back(min_size[1]);
max_shape.push_back(x_shape[0]);
max_shape.push_back(x_shape[1]);
max_shape.push_back(max_size[0]);
max_shape.push_back(max_size[1]);
} else {
auto x_min_shape = x_shape_ptr->min_shape();
auto x_max_shape = x_shape_ptr->max_shape();
min_shape.push_back(x_min_shape[0]);
min_shape.push_back(x_min_shape[1]);
min_shape.push_back(min_size[0]);
min_shape.push_back(min_size[1]);
max_shape.push_back(x_max_shape[0]);
max_shape.push_back(x_max_shape[1]);
max_shape.push_back(max_size[0]);
max_shape.push_back(max_size[1]);
}
return std::make_shared<abstract::Shape>(output_shape, min_shape, max_shape);
}
TypePtr DynamicResizeNearestNeighborInferType(const PrimitivePtr &prim,
const std::vector<AbstractBasePtr> &input_args) {
auto valid_types = common_valid_types;
valid_types.insert(kComplex128);
valid_types.insert(kComplex64);
return CheckAndConvertUtils::CheckTensorTypeValid("x", input_args[0]->BuildType(), valid_types, prim->name());
}
} // namespace
MIND_API_OPERATOR_IMPL(DynamicResizeNearestNeighbor, BaseOperator);
AbstractBasePtr DynamicResizeNearestNeighborInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive,
const std::vector<AbstractBasePtr> &input_args) {
auto prim_name = primitive->name();
const int64_t input_num = 2;
(void)CheckAndConvertUtils::CheckInteger("infer", SizeToLong(CheckAndConvertUtils::GetRemoveMonadAbsNum(input_args)),
kEqual, input_num, prim_name);
auto res = abstract::MakeAbstract(DynamicResizeNearestNeighborInferShape(primitive, input_args),
DynamicResizeNearestNeighborInferType(primitive, input_args));
return res;
}
REGISTER_PRIMITIVE_EVAL_IMPL(DynamicResizeNearestNeighbor, prim::kPrimDynamicResizeNearestNeighbor,
DynamicResizeNearestNeighborInfer, nullptr, true);
} // namespace ops
} // namespace mindspore
| 6,263
| 2,165
|
#include "cilk.hpp"
#include "raycast.hpp"
int main() {
taskparts::benchmark_cilk([&] { // benchmark
benchmark();
}, [&] { // setup
gen_input();
}, [&] { // teardown
// later: write results to outfile
}, [&] { // reset
reset();
});
return 0;
}
| 277
| 106
|
// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided 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 <stack>
#include <string_view>
#include "../common.hh"
#include "../harness.hh"
// [ADDR] https://leetcode.com/problems/valid-parentheses/description
//
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
// determine if the input string is valid.
//
// An input string is valid if:
//
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
// Note that an empty string is also considered valid.
//
// Example 1:
//
// Input: "()"
// Output: true
// Example 2:
//
// Input: "()[]{}"
// Output: true
// Example 3:
//
// Input: "(]"
// Output: false
// Example 4:
//
// Input: "([)]"
// Output: false
// Example 5:
//
// Input: "{[]}"
// Output: true
class ValidParentheses final : public Singleton<ValidParentheses> {
inline bool is_lparen(char c) const noexcept {
return c == '(' || c == '[' || c == '{';
}
inline bool is_rparen(char c) const noexcept {
return c == ')' || c == ']' || c == '}';
}
bool is_match(char c, char expected) const noexcept {
switch (c) {
case ')': return expected == '(';
case ']': return expected == '[';
case '}': return expected == '{';
}
return false;
}
bool is_valid(std::string_view s) const {
std::stack<char> stack;
for (char c : s) {
if (is_lparen(c)) {
stack.push(c);
}
else if (is_rparen(c)) {
char top = stack.top();
stack.pop();
if (!is_match(c, top))
return false;
}
else {
return false;
}
}
return stack.empty();
}
public:
void run() {
HARNESS_TRUE(is_valid("()"));
HARNESS_TRUE(is_valid("()[]{}"));
HARNESS_TRUE(!is_valid("(]"));
HARNESS_TRUE(!is_valid("([)]"));
HARNESS_TRUE(is_valid("{[]}"));
}
};
HARNESS_TEST(ValidParentheses, harness::FakeTester) {
ValidParentheses::get_instance().run();
}
| 3,292
| 1,176
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: contractimpl.cpp
//
// Keeps track of contract implementations, used primarily in stub dispatch.
//
//
//
// ============================================================================
#include "common.h" // Precompiled header
#include "contractimpl.h"
#include "virtualcallstub.h"
#include "decodemd.h"
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif
#if defined(_DEBUG)
DummyGlobalContract ___contract;
#endif
#ifdef LOGGING
//----------------------------------------------------------------------------
StubDispatchStats g_sdStats = {0};
#endif // LOGGING
#ifndef DACCESS_COMPILE
//----------------------------------------------------------------------------
MethodDesc * DispatchSlot::GetMethodDesc()
{
WRAPPER_NO_CONTRACT;
if (IsNull())
return NULL;
else
return MethodTable::GetMethodDescForSlotAddress(GetTarget());
}
//------------------------------------------------------------------------
void TypeIDMap::Init(UINT32 idStartValue, UINT32 idIncrementValue, BOOL fUseFatTokensForUniqueness)
{
STANDARD_VM_CONTRACT;
LockOwner lock = {&m_lock, IsOwnerOfCrst};
m_idMap.Init(11, TRUE, &lock);
m_mtMap.Init(11, TRUE, &lock);
m_idProvider.Init(idStartValue, idIncrementValue);
m_entryCount = 0;
m_fUseFatIdsForUniqueness = fUseFatTokensForUniqueness;
}
#endif // !DACCESS_COMPILE
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
UINT32 TypeIDMap::LookupTypeID(PTR_MethodTable pMT)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
PRECONDITION(CheckPointer(GetThread()));
if (GetThread()->PreemptiveGCDisabled()) { GC_NOTRIGGER; } else { GC_TRIGGERS; }
} CONTRACTL_END;
UINT32 id = (UINT32) m_mtMap.LookupValue((UPTR)dac_cast<TADDR>(pMT), 0);
_ASSERTE(!m_fUseFatIdsForUniqueness || !pMT->RequiresFatDispatchTokens() || (DispatchToken::RequiresDispatchTokenFat(id, 0)));
return id;
}
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
PTR_MethodTable TypeIDMap::LookupType(UINT32 id)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
PRECONDITION(CheckPointer(GetThread()));
if (GetThread()->PreemptiveGCDisabled()) { GC_NOTRIGGER; } else { GC_TRIGGERS; }
PRECONDITION(id <= TypeIDProvider::MAX_TYPE_ID);
} CONTRACTL_END;
if (!m_idProvider.OwnsID(id))
return NULL;
UPTR ret = m_idMap.LookupValue((UPTR)id, 0);
if (ret == static_cast<UPTR>(INVALIDENTRY))
return NULL;
ret <<= 1;
return PTR_MethodTable(ret);
}
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, assigns the ID and
// returns the new ID.
UINT32 TypeIDMap::GetTypeID(PTR_MethodTable pMT)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
// Lookup the value.
UINT32 id = LookupTypeID(pMT);
#ifndef DACCESS_COMPILE
// If the value is not in the table, take the lock, get a new ID, and
// insert the new pair.
if (id == TypeIDProvider::INVALID_TYPE_ID)
{
// Take the lock
CrstHolder lh(&m_lock);
// Check to see if someone beat us to the punch
id = LookupTypeID(pMT);
if (id != TypeIDProvider::INVALID_TYPE_ID)
{
return id;
}
// Get the next ID
if (m_fUseFatIdsForUniqueness && pMT->RequiresFatDispatchTokens())
{
id = GetNextFatID();
}
else
{
id = GetNextID();
}
CONSISTENCY_CHECK(id <= TypeIDProvider::MAX_TYPE_ID);
// Insert the pair, with lookups in both directions
CONSISTENCY_CHECK((((UPTR)pMT) & 0x1) == 0);
m_idMap.InsertValue((UPTR)id, (UPTR)pMT >> 1);
m_mtMap.InsertValue((UPTR)pMT, (UPTR)id);
m_entryCount++;
CONSISTENCY_CHECK(GetThread()->GetDomain()->IsCompilationDomain() ||
(LookupType(id) == pMT));
}
#else // DACCESS_COMPILE
if (id == TypeIDProvider::INVALID_TYPE_ID)
DacError(E_FAIL);
#endif // DACCESS_COMPILE
// Return the ID for this type.
return id;
} // TypeIDMap::GetTypeID
#ifndef DACCESS_COMPILE
//------------------------------------------------------------------------
// If TRUE, it points to a matching entry.
// If FALSE, it is at the insertion point.
BOOL
DispatchMapBuilder::Find(
DispatchMapTypeID typeID,
UINT32 slotNumber,
Iterator & it)
{
WRAPPER_NO_CONTRACT;
for (; it.IsValid(); it.Next())
{
if (typeID == it.GetTypeID())
{
if (slotNumber == it.GetSlotNumber())
{
return TRUE;
}
if (slotNumber < it.GetSlotNumber())
{
return FALSE;
}
}
else if (typeID < it.GetTypeID())
{
return FALSE;
}
}
return FALSE;
} // DispatchMapBuilder::Find
//------------------------------------------------------------------------
// If TRUE, contains such an entry.
// If FALSE, no such entry exists.
BOOL DispatchMapBuilder::Contains(DispatchMapTypeID typeID, UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
Iterator it(this);
return Find(typeID, slotNumber, it);
}
//------------------------------------------------------------------------
void
DispatchMapBuilder::InsertMDMapping(
DispatchMapTypeID typeID,
UINT32 slotNumber,
MethodDesc * pMDTarget,
BOOL fIsMethodImpl)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
// Find a matching entry, or move the iterator to insertion point.
Iterator it(this);
BOOL fFound = Find(typeID, slotNumber, it);
// If we find an existing matching entry, fail.
if (fFound)
{
_ASSERTE(false);
COMPlusThrowHR(COR_E_TYPELOAD);
}
// Create and initialize a new entry
DispatchMapBuilderNode * pNew = NewEntry();
pNew->Init(typeID, slotNumber, pMDTarget);
if (fIsMethodImpl)
pNew->SetIsMethodImpl();
// Insert at the point of the iterator
pNew->m_next = NULL;
if (it.IsValid())
{
pNew->m_next = it.EntryNode();
}
*(it.EntryNodePtr()) = pNew;
m_cEntries++;
} // DispatchMapBuilder::InsertMDMapping
//--------------------------------------------------------------------
UINT32 DispatchMapBuilder::Iterator::GetTargetSlot()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(IsValid());
if (GetTargetMD() != NULL)
{
return EntryNode()->m_pMDTarget->GetSlot();
}
else
{
return 0;
}
}
//------------------------------------------------------------------------
DispatchMapBuilderNode * DispatchMapBuilder::NewEntry()
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM());
} CONTRACTL_END;
return new (m_pAllocator) DispatchMapBuilderNode();
}
//----------------------------------------------------------------------------
DispatchMap::DispatchMap(
BYTE * pMap,
UINT32 cbMap)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(CheckPointer(pMap));
memcpyNoGCRefs(m_rgMap, pMap, cbMap);
}
//----------------------------------------------------------------------------
// This mapping consists of a list of the following entries.
// <type, [<slot, (index | slot)>]>. This is implemented as
//
// flag: 0 if the map is a part of a JIT'd module
// 1 if the map is a part of an NGEN'd module.
// count: number of types that have entries
// {
// type: The ID current type being mapped
// count: Number of subentries for the current type
// bool: Whether or not the target slot/index values can be negative.
// {
// slot: The slot of type that is being mapped
// index/slot: This is a slot mapping for the current type. The implementation search is
// modified to <this, slot> and the search is restarted from the initial type.
// }
// }
void
DispatchMap::CreateEncodedMapping(
MethodTable * pMT,
DispatchMapBuilder * pMapBuilder,
StackingAllocator * pAllocator,
BYTE ** ppbMap,
UINT32 * pcbMap)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pMapBuilder));
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(CheckPointer(ppbMap));
PRECONDITION(CheckPointer(pcbMap));
} CONTRACTL_END;
/////////////////////////////////
// Phase 1 - gather entry counts
UINT32 cNumTypes = 0;
UINT32 cNumEntries = 0;
{
DispatchMapBuilder::Iterator it(pMapBuilder);
// We don't want to record overrides or methodImpls in the dispatch map since
// we have vtables to track this information.
it.SkipThisTypeEntries();
if (it.IsValid())
{
DispatchMapTypeID curType = DispatchMapTypeID::FromUINT32(INVALIDENTRY);
do
{
cNumEntries++;
if (curType != it.GetTypeID())
{
cNumTypes++;
curType = it.GetTypeID();
}
}
while (it.Next());
}
}
/////////////////////////////////
// Phase 2 - allocate space
// Now that we have stats about the overall absolute maximum map size, we can allocate
// some working space for createing the encoded map in.
// Sizes: flag==UINT32, typeID==UINT32, slot==UINT32, index/slot==UINT32
S_UINT32 scbMap = S_UINT32(sizeof(UINT32)) +
S_UINT32(cNumTypes) * S_UINT32(sizeof(UINT32)) +
S_UINT32(cNumEntries) * S_UINT32((sizeof(UINT32) + sizeof(UINT32)));
BYTE * pbMap = (BYTE *)pAllocator->Alloc(scbMap);
/////////////////////////////////
// Phase 3 - encode the map
{
// Create the encoder over the newly allocated memory
Encoder e(pbMap);
// Encode the count of type entries
e.Encode((unsigned)cNumTypes);
// Start encoding the map
DispatchMapBuilder::Iterator it(pMapBuilder);
it.SkipThisTypeEntries();
INT32 curType = -1;
INT32 prevType;
INT32 deltaType;
while (it.IsValid())
{
// Encode the type ID
prevType = curType;
curType = (INT32)it.GetTypeID().ToUINT32();
deltaType = curType - prevType - ENCODING_TYPE_DELTA;
CONSISTENCY_CHECK(0 <= deltaType);
e.Encode((unsigned)deltaType);
// Variables for slot delta calculations
BOOL fHasNegatives = FALSE;
// Source slot
INT32 curSlot = -1;
INT32 prevSlot = -1;
// Target slot for virtual mappings
INT32 curTargetSlot = -1;
INT32 prevTargetSlot = -1;
// Count and encode the number of sub entries for this type
UINT32 cSubEntries = 0;
DispatchMapBuilder::Iterator subIt(it);
do
{
prevTargetSlot = curTargetSlot;
curTargetSlot = (INT32)subIt.GetTargetSlot();
INT32 deltaTargetSlot = curTargetSlot - prevTargetSlot - ENCODING_TARGET_SLOT_DELTA;
if (deltaTargetSlot < 0)
{
fHasNegatives = TRUE;
}
cSubEntries++;
}
while (subIt.Next() && (subIt.GetTypeID().ToUINT32() == (UINT32)curType));
e.Encode((unsigned)cSubEntries);
e.Encode((unsigned)fHasNegatives);
e.ContainsNegatives(fHasNegatives);
// Iterate each subentry and encode it
curTargetSlot = -1;
do
{
// Only virtual targets can be mapped virtually.
CONSISTENCY_CHECK((it.GetTargetMD() == NULL) ||
it.GetTargetMD()->IsVirtual());
// Encode the slot
prevSlot = curSlot;
curSlot = it.GetSlotNumber();
INT32 deltaSlot = curSlot - prevSlot - ENCODING_SLOT_DELTA;
CONSISTENCY_CHECK(0 <= deltaSlot);
e.Encode((unsigned)deltaSlot);
// Calculate and encode the target slot delta
prevTargetSlot = curTargetSlot;
curTargetSlot = (INT32)it.GetTargetSlot();
INT32 delta = curTargetSlot - prevTargetSlot - ENCODING_TARGET_SLOT_DELTA;
if (fHasNegatives)
{
e.EncodeSigned((signed)delta);
}
else
{
CONSISTENCY_CHECK(0 <= delta);
e.Encode((unsigned)delta);
}
}
while (it.Next() && it.GetTypeID().ToUINT32() == (UINT32)curType);
} // while (it.IsValid())
// Finish and finalize the map, and set the out params.
e.Done();
*pcbMap = e.Contents(ppbMap);
}
#ifdef _DEBUG
// Let's verify the mapping
{
EncodedMapIterator itMap(*ppbMap);
DispatchMapBuilder::Iterator itBuilder(pMapBuilder);
itBuilder.SkipThisTypeEntries();
while (itMap.IsValid())
{
CONSISTENCY_CHECK(itBuilder.IsValid());
DispatchMapEntry * pEntryMap = itMap.Entry();
CONSISTENCY_CHECK(pEntryMap->GetTypeID() == itBuilder.GetTypeID());
CONSISTENCY_CHECK(pEntryMap->GetTargetSlotNumber() == itBuilder.GetTargetSlot());
itMap.Next();
itBuilder.Next();
}
CONSISTENCY_CHECK(!itBuilder.IsValid());
}
#endif //_DEBUG
} // DispatchMap::CreateEncodedMapping
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
//------------------------------------------------------------------------
void DispatchMap::Save(DataImage * image)
{
STANDARD_VM_CONTRACT;
CONSISTENCY_CHECK(!image->IsStored(this));
UINT32 cbMap = GetMapSize();
UINT32 cbObj = GetObjectSize(cbMap);
image->StoreInternedStructure(
this,
cbObj,
DataImage::ITEM_DISPATCH_MAP,
sizeof(void *));
#ifdef LOGGING
g_sdStats.m_cNGENDispatchMap++;
g_sdStats.m_cbNGENDispatchMap += cbObj;
#endif //LOGGING
}
//------------------------------------------------------------------------
void DispatchMap::Fixup(DataImage *image)
{
STANDARD_VM_CONTRACT;
}
#endif //FEATURE_NATIVE_IMAGE_GENERATION
#endif //!DACCESS_COMPILE
//------------------------------------------------------------------------
UINT32 DispatchMap::GetMapSize()
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
EncodedMapIterator it(this);
for (; it.IsValid(); it.Next())
{
}
CONSISTENCY_CHECK(dac_cast<TADDR>(it.m_d.End()) > PTR_HOST_MEMBER_TADDR(DispatchMap, this, m_rgMap));
return (UINT32)(dac_cast<TADDR>(it.m_d.End()) - PTR_HOST_MEMBER_TADDR(DispatchMap, this, m_rgMap));
}
#ifdef DACCESS_COMPILE
//------------------------------------------------------------------------
void DispatchMap::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
DAC_ENUM_DTHIS();
EMEM_OUT(("MEM: %p DispatchMap\n", dac_cast<TADDR>(this)));
DacEnumMemoryRegion(PTR_HOST_MEMBER_TADDR(DispatchMap,this,m_rgMap), GetMapSize());
}
#endif // DACCESS_COMPILE
//--------------------------------------------------------------------
void DispatchMap::EncodedMapIterator::Invalidate()
{
LIMITED_METHOD_DAC_CONTRACT;
m_numTypes = 0;
m_curType = 0;
m_numEntries = 0;
m_curEntry = 0;
}
//--------------------------------------------------------------------
void DispatchMap::EncodedMapIterator::Init(PTR_BYTE pbMap)
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pbMap, NULL_OK));
SUPPORTS_DAC;
} CONTRACTL_END;
if (pbMap != NULL)
{
// Initialize the map decoder
m_d.Init(pbMap);
m_numTypes = m_d.Next();
m_curType = -1;
m_curTypeId = DispatchMapTypeID::FromUINT32(static_cast<UINT32>(-1));
m_numEntries = 0;
m_curEntry = -1;
m_curTargetSlot = static_cast<UINT32>(-1);
}
else
{
Invalidate();
}
Next();
}
//--------------------------------------------------------------------
DispatchMap::EncodedMapIterator::EncodedMapIterator(MethodTable * pMT)
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
SUPPORTS_DAC;
} CONTRACTL_END;
if (pMT->HasDispatchMap())
{
DispatchMap * pMap = pMT->GetDispatchMap();
Init(PTR_BYTE(PTR_HOST_MEMBER_TADDR(DispatchMap, pMap, m_rgMap)));
}
else
{
Init(NULL);
}
}
//--------------------------------------------------------------------
// This should be used only when a dispatch map needs to be used
// separately from its MethodTable.
DispatchMap::EncodedMapIterator::EncodedMapIterator(DispatchMap * pMap)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
PTR_BYTE pBytes = NULL;
if (pMap != NULL)
{
pBytes = PTR_BYTE(PTR_HOST_MEMBER_TADDR(DispatchMap, pMap,m_rgMap));
}
Init(pBytes);
}
//--------------------------------------------------------------------
DispatchMap::EncodedMapIterator::EncodedMapIterator(PTR_BYTE pbMap)
{
LIMITED_METHOD_CONTRACT;
Init(pbMap);
}
//--------------------------------------------------------------------
BOOL DispatchMap::EncodedMapIterator::Next()
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
SUPPORTS_DAC;
} CONTRACTL_END;
if (!IsValid())
{
return FALSE;
}
m_curEntry++;
if (m_curEntry == m_numEntries)
{
m_curType++;
if (m_curType == m_numTypes)
{
return FALSE;
}
m_curTypeId =
DispatchMapTypeID::FromUINT32(
(UINT32)((INT32)m_curTypeId.ToUINT32() +
(INT32)m_d.Next() +
ENCODING_TYPE_DELTA));
_ASSERTE(!m_curTypeId.IsThisClass());
m_curEntry = 0;
m_numEntries = m_d.Next();
m_fCurTypeHasNegativeEntries = (BOOL)m_d.Next();
m_curSlot = static_cast<UINT32>(-1);
m_curTargetSlot = static_cast<UINT32>(-1);
CONSISTENCY_CHECK(m_numEntries != 0);
}
// Now gather enough info to initialize the dispatch entry
// Get the source slot
m_curSlot = (UINT32)((INT32)m_curSlot + (INT32)m_d.Next() + ENCODING_SLOT_DELTA);
// If virtual, get the target virtual slot number
m_curTargetSlot =
(UINT32)((INT32)m_curTargetSlot +
ENCODING_TARGET_SLOT_DELTA +
(INT32)(m_fCurTypeHasNegativeEntries ? m_d.NextSigned() : m_d.Next()));
m_e.InitVirtualMapping(m_curTypeId, m_curSlot, m_curTargetSlot);
CONSISTENCY_CHECK(IsValid());
return TRUE;
} // DispatchMap::EncodedMapIterator::Next
//--------------------------------------------------------------------
DispatchMap::Iterator::Iterator(MethodTable * pMT)
: m_mapIt(pMT)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
}
//--------------------------------------------------------------------
BOOL DispatchMap::Iterator::IsValid()
{
WRAPPER_NO_CONTRACT;
return m_mapIt.IsValid();
}
//--------------------------------------------------------------------
BOOL DispatchMap::Iterator::Next()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(!m_mapIt.Entry()->GetTypeID().IsThisClass());
if (m_mapIt.IsValid())
{
m_mapIt.Next();
CONSISTENCY_CHECK(!m_mapIt.IsValid() || !m_mapIt.Entry()->GetTypeID().IsThisClass());
}
return IsValid();
}
//--------------------------------------------------------------------
DispatchMapEntry * DispatchMap::Iterator::Entry()
{
/*
CONTRACTL {
INSTANCE_CHECK;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(IsValid());
} CONTRACTL_END;
*/
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(IsValid());
DispatchMapEntry * pEntry = NULL;
if (m_mapIt.IsValid())
{
pEntry = m_mapIt.Entry();
}
CONSISTENCY_CHECK(CheckPointer(pEntry));
return pEntry;
}
| 21,098
| 6,898
|
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "token.h"
#include "instructions.h"
CInstrTable::CInstrTable()
{
currInstr = 0;
}
CInstrTable::~CInstrTable()
{
}
int CInstrTable::AddInstr(char *name,int token,int numParams)
{
if(strlen(name) >= MAX_INSTR_NAME)
return -1;
InstrLookup *func = (InstrLookup*)malloc(sizeof(InstrLookup));
strcpy(func->name,name);
func->token = token;
func->numParam = numParams;
func->opList = (Operand*)malloc((sizeof(Operand)) * numParams);
instr.push_back(func);
return currInstr++;
}
void CInstrTable::SetInstrOp(int instrIndex,int opIndex,int values)
{
InstrLookup* f = instr[instrIndex];
f->opList[opIndex].type = values;
}
InstrLookup* CInstrTable::GetInstrByIndex(int index)
{
for (int i=0; i<currInstr;i++)
{
if (i == index)
return instr[i];
}
return NULL;
}
InstrLookup* CInstrTable::GetInstrByName(char *name)
{
for (int i=0; i<currInstr;i++)
{
if (strcmp(instr[i]->name, name) == 0)
return instr[i];
}
return NULL;
}
bool CInstrTable::IsValidInstr(char *name)
{
char *t;
for (int i=0; i<currInstr;i++)
{
t = instr[i]->name;
if (strcmp(t, name) == 0)
return true;
}
return false;
}
| 1,236
| 559
|
/*
* ModbusReadCoils.cpp
*
* Created on: 09.02.2016
* Author: lode
*/
#include "ModbusReadCoils.h"
namespace Modbus
{
ReadCoils2Array::ReadCoils2Array(unsigned* array, uint16_t numOfBits, TxnReturnPath* rp)
: ReadBits2Array(FunctionCode, array, numOfBits, rp)
{}
//ReadCoils2Array::~ReadCoils2Array()
//{
// // Auto-generated destructor stub
//}
} /* namespace Modbus */
| 388
| 161
|
#include "nalu.h"
//#include <cmath>
#include "math.h"
Nalu::Nalu(int input_dim, int out_dim, float *weight, float *gate) :
weights_(weight),
gate_(gate),
Layer ( input_dim, out_dim)
{}
void Nalu::process(float* input,float* output) {
for(int i = 0; i < out_dim_; i++) {
float lin = 0;
float log_ = 0;
float gate = 0;
for(int j = 0; j < input_dim_; j++) {
gate += gate_[i * input_dim_ + j] * input[j];
lin += weights_[i * input_dim_ + j] * input[j];
log_ += weights_[i * input_dim_ + j] * log(fabs(input[j])+0.00001);
}
gate = 0.5*tanh(gate)+1;
output[i] = gate * lin + (1-gate) * exp(log_);
}
}
void Nalu::free() {
delete [] weights_;
delete [] gate_;
}
| 779
| 308
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_RUNTIME_CORE_HPP
#define KAGOME_RUNTIME_CORE_HPP
#include <outcome/outcome.hpp>
#include <vector>
#include "primitives/authority.hpp"
#include "primitives/block.hpp"
#include "primitives/block_id.hpp"
#include "primitives/common.hpp"
#include "primitives/transaction_validity.hpp"
#include "primitives/version.hpp"
namespace kagome::runtime {
/**
* Core represents mandatory part of runtime api
*/
class Core {
public:
virtual ~Core() = default;
/**
* @brief Returns the version of the runtime
* @return runtime version
*/
virtual outcome::result<primitives::Version> version(
const boost::optional<primitives::BlockHash> &block_hash) = 0;
/**
* @brief Executes the given block
* @param block block to execute
*/
virtual outcome::result<void> execute_block(
const primitives::Block &block) = 0;
/**
* @brief Initialize a block with the given header.
* @param header header used for block initialization
*/
virtual outcome::result<void> initialise_block(
const primitives::BlockHeader &header) = 0;
/**
* Get current authorities
* @return collection of authorities
*/
virtual outcome::result<std::vector<primitives::AuthorityId>> authorities(
const primitives::BlockId &block_id) = 0;
};
} // namespace kagome::runtime
#endif // KAGOME_RUNTIME_CORE_HPP
| 1,523
| 490
|
/*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include "../../simdebug.h"
#include "../../simconst.h"
#include "../../bauer/vehikelbauer.h"
#include "../sound_desc.h"
#include "../vehicle_desc.h"
#include "../intro_dates.h"
#include "vehicle_reader.h"
#include "../obj_node_info.h"
#include "../../network/pakset_info.h"
void vehicle_reader_t::register_obj(obj_desc_t *&data)
{
vehicle_desc_t *desc = static_cast<vehicle_desc_t *>(data);
vehicle_builder_t::register_desc(desc);
obj_for_xref(get_type(), desc->get_name(), data);
checksum_t *chk = new checksum_t();
desc->calc_checksum(chk);
pakset_info_t::append(desc->get_name(), get_type(), chk);
}
bool vehicle_reader_t::successfully_loaded() const
{
return vehicle_builder_t::successfully_loaded();
}
obj_desc_t *vehicle_reader_t::read_node(FILE *fp, obj_node_info_t &node)
{
ALLOCA(char, desc_buf, node.size);
vehicle_desc_t *desc = new vehicle_desc_t();
// Read data
fread(desc_buf, node.size, 1, fp);
char * p = desc_buf;
// old versions of PAK files have no version stamp.
// But we know, the higher most bit was always cleared.
const uint16 v = decode_uint16(p);
int version = v & 0x8000 ? v & 0x7FFF : 0;
// Whether the read file is from Simutrans-Extended
//@author: jamespetts
const bool extended = version > 0 ? v & EX_VER : false;
uint16 extended_version = 0;
if(extended)
{
// Extended version to start at 0 and increment.
version = version & EX_VER ? version & 0x3FFF : 0;
while(version > 0x100)
{
version -= 0x100;
extended_version ++;
}
extended_version -= 1;
}
way_constraints_of_vehicle_t way_constraints;
if(version == 1) {
// Versioned node, version 1
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
}
else if(version == 2) {
// Versioned node, version 2
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
}
else if (version==3 || version==4 || version==5) {
// Versioned node, version 3 with retire date
// version 4 identical, just other values for the waytype
// version 5 just uses the new scheme for data calculation
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
}
else if (version==6) {
// version 5 just 32 bit for power and 16 Bit for gear
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
}
else if (version==7) {
// different length of cars ...
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
}
else if (version==8) {
// multiple freight images...
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version <= 6)
{
desc->classes = 1;
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
desc->can_lead_from_rear = decode_uint8(p);
desc->comfort = new uint8[1];
desc->comfort[0] = decode_uint8(p);
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
if(extended_version == 1)
{
desc->base_fixed_cost = decode_uint16(p);
}
else if(extended_version >= 2)
{
desc->base_fixed_cost = decode_uint32(p);
}
else
{
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
}
if(extended_version >= 3)
{
desc->tractive_effort = decode_uint16(p);
}
else
{
desc->tractive_effort = 0;
}
if(extended_version >=4)
{
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
}
else
{
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
}
if(extended_version >= 5)
{
desc->livery_image_type = decode_uint8(p);
}
else
{
desc->livery_image_type = 0;
}
if(extended_version >= 6)
{
// With minimum and maximum loading times in seconds
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
}
else
{
desc->min_loading_time_seconds = desc->max_loading_time_seconds = 65535;
}
desc->is_tall = false;
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else if (version==9) {
// new: fixed_cost (previously Extended only), loading_time, axle_load
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
if(extended_version == 0)
{
// The new Standard datum for loading times is read here.
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
}
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->axle_load = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
if(extended_version == 0)
{
// Extended has this as a 32-bit integer, and reads it later.
desc->base_fixed_cost = decode_uint16(p);
}
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version <= 7)
{
desc->classes = 1;
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
desc->can_lead_from_rear = decode_uint8(p);
desc->comfort = new uint8[1];
desc->comfort[0] = decode_uint8(p);
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
if(extended_version == 1)
{
desc->base_fixed_cost = decode_uint16(p);
}
else if(extended_version >= 2)
{
desc->base_fixed_cost = decode_uint32(p);
}
else
{
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
}
if(extended_version >= 3)
{
desc->tractive_effort = decode_uint16(p);
}
else
{
desc->tractive_effort = 0;
}
if(extended_version >= 4)
{
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
}
else
{
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
}
if(extended_version >= 5)
{
desc->livery_image_type = decode_uint8(p);
}
else
{
desc->livery_image_type = 0;
}
if(extended_version >= 6)
{
// With minimum and maximum loading times in seconds
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
}
else
{
desc->min_loading_time_seconds = desc->max_loading_time_seconds = 65535;
}
if(extended_version >= 7)
{
uint32 rolling_resistance_tenths_thousands = decode_uint16(p);
desc->rolling_resistance = rolling_resistance_tenths_thousands * float32e8_t::ten_thousandth;
desc->brake_force = decode_uint16(p);
desc->minimum_runway_length = decode_uint16(p);
}
else
{
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
}
desc->is_tall = false;
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else if (version == 10 || version == 11) {
// new: weight in kgs
desc->base_cost = decode_uint32(p);
if (extended && extended_version >= 4)
{
// Multiple classes, therefore multiple capacities.
desc->classes = decode_uint8(p);
}
else
{
desc->classes = 1;
}
// Initialise the arrays
desc->capacity = new uint16[desc->classes];
desc->comfort = new uint8[desc->classes];
for (uint32 i = 0; i < desc->classes; i++)
{
desc->capacity[i] = decode_uint16(p);
}
if (!extended)
{
// The new Standard datum for loading times is read here.
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
}
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint32(p);
desc->axle_load = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
if (!extended)
{
// Extended has this as a 32-bit integer, and reads it later.
desc->base_fixed_cost = decode_uint16(p);
}
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
if (extended_version >= 3)
{
desc->sound = decode_sint16(p);
}
else
{
desc->sound = decode_sint8(p);
}
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version < 7)
{
// NOTE: Extended version reset to 1 with incrementing of
// Standard version to 10.
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
if (extended && extended_version >= 5)
{
desc->basic_constraint_prev = decode_uint8(p);
}
else {
desc->can_lead_from_rear = decode_uint8(p);
desc->basic_constraint_prev = vehicle_desc_t::unknown_constraint;
}
for (uint32 i = 0; i < desc->classes; i++)
{
desc->comfort[i] = decode_uint8(p);
}
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
if (!extended && version == 10)
{
desc->base_fixed_cost = decode_uint16(p);
}
else
{
desc->base_fixed_cost = decode_uint32(p);
}
desc->tractive_effort = decode_uint16(p);
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
if (extended && extended_version >= 5)
{
desc->basic_constraint_next = decode_uint8(p);
}
else
{
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->basic_constraint_next = vehicle_desc_t::unknown_constraint;
}
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
desc->livery_image_type = decode_uint8(p);
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
uint32 rolling_resistance_tenths_thousands = decode_uint16(p);
desc->rolling_resistance = rolling_resistance_tenths_thousands * float32e8_t::ten_thousandth;
desc->brake_force = decode_uint16(p);
desc->minimum_runway_length = decode_uint16(p);
if(extended_version == 0)
{
desc->range = 0;
desc->way_wear_factor = UINT32_MAX_VALUE;
}
else
{
desc->range = decode_uint16(p);
desc->way_wear_factor = decode_uint32(p);
}
if (extended_version > 1)
{
desc->is_tall = decode_uint8(p);
}
else
{
desc->is_tall = false;
}
if (extended && extended_version >= 5)
{
desc->mixed_load_prohibition = decode_uint8(p);
}
else
{
desc->mixed_load_prohibition = false;
}
if (extended && extended_version >= 6)
{
desc->override_way_speed = decode_uint8(p);
}
else
{
desc->override_way_speed = false;
}
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else {
if( version!=0 ) {
dbg->fatal( "vehicle_reader_t::read_node()","Do not know how to handle version=%i", version );
}
// old node, version 0
desc->wtyp = (sint8)v;
desc->capacity[0] = decode_uint16(p);
desc->base_cost = decode_uint32(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->sound = decode_sint16(p);
desc->leader_count = (sint8)decode_uint16(p);
desc->trailer_count = (sint8)decode_uint16(p);
desc->intro_date = DEFAULT_INTRO_DATE*16;
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
desc->gear = 64;
}
// correct the engine type for old vehicles
if(version<2) {
// steam eangines usually have a sound of 3
// electric engines will be overridden further down ...
desc->engine_type = (desc->sound==3) ? vehicle_desc_t::steam : vehicle_desc_t::diesel;
}
//change the vehicle type
if(version<4) {
if(desc->wtyp==4) {
desc->engine_type = vehicle_desc_t::electric;
desc->wtyp = 1;
}
// convert to new standard
static const waytype_t convert_from_old[8]={road_wt, track_wt, water_wt, air_wt, invalid_wt, monorail_wt, invalid_wt, tram_wt };
desc->wtyp = convert_from_old[desc->wtyp];
}
// before version 5 dates were based on base 12 ...
if(version<5) {
uint16 date=desc->intro_date;
desc->intro_date = (date/16)*12 + (date%16);
date=desc->retire_date;
desc->retire_date = (date/16)*12 + (date%16);
}
// before the length was always 1/8 (=half a tile)
if(version<7) {
desc->len = CARUNITS_PER_TILE/2;
}
// adjust length for different offset step sizes (which may arise in future)
desc->len *= OBJECT_OFFSET_STEPS/CARUNITS_PER_TILE;
// before version 8 vehicles could only have one freight image in each direction
if(version<8) {
desc->freight_image_type=0;
}
if(!extended)
{
// Default values for items not in the standard vehicle format.
desc->classes = 1;
desc->is_tilting = false;
desc->catering_level = 0;
desc->bidirectional = false;
desc->can_lead_from_rear = false;
desc->comfort = new uint8[1];
desc->comfort[0] = 100;
desc->overcrowded_capacity = 0;
desc->tractive_effort = 0;
switch(desc->get_waytype())
{
default:
case tram_wt:
case road_wt:
desc->min_loading_time = desc->max_loading_time = 2000;
break;
case monorail_wt:
case maglev_wt:
case narrowgauge_wt:
case track_wt:
desc->min_loading_time = desc->max_loading_time = 4000;
break;
case water_wt:
desc->min_loading_time = desc->max_loading_time = 20000;
break;
case air_wt:
desc->min_loading_time = desc->max_loading_time = 30000;
break;
}
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
desc->upgrades = 0;
desc->base_upgrade_price = desc->base_cost;
desc->available_only_as_upgrade = false;
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
desc->livery_image_type = 0;
desc->min_loading_time_seconds = 20;
desc->max_loading_time_seconds = 60;
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
desc->range = 0;
desc->way_wear_factor = 1;
desc->is_tall = false;
desc->basic_constraint_prev = vehicle_desc_t::unknown_constraint;
desc->basic_constraint_next = vehicle_desc_t::unknown_constraint;
desc->mixed_load_prohibition = false;
desc->override_way_speed = false;
}
desc->set_way_constraints(way_constraints);
if(version<9) {
desc->base_fixed_cost = 0;
desc->axle_load = desc->weight;
}
// old weights were tons
if(version<10) {
desc->weight *= 1000;
desc->range = 0;
desc->way_wear_factor = UINT32_MAX_VALUE;
}
// Convert flag
if (version<11 || (version == 11 && extended && extended_version < 5)) {
if (desc->can_lead_from_rear == true && desc->bidirectional == false) {
desc->bidirectional = true;
}
}
if(desc->sound==LOAD_SOUND) {
uint8 len=decode_sint8(p);
char wavname[256];
wavname[len] = 0;
for(uint8 i=0; i<len; i++) {
wavname[i] = decode_sint8(p);
}
desc->sound = (sint16)sound_desc_t::get_sound_id(wavname);
DBG_MESSAGE("vehicle_reader_t::register_obj()","sound %s to %i",wavname,desc->sound);
}
else if(desc->sound>=0 && desc->sound<=MAX_OLD_SOUNDS) {
sint16 old_id = desc->sound;
desc->sound = (sint16)sound_desc_t::get_compatible_sound_id(old_id);
DBG_MESSAGE("vehicle_reader_t::register_obj()","old sound %i to %i",old_id,desc->sound);
}
desc->loaded();
DBG_DEBUG("vehicle_reader_t::read_node()",
"version=%d "
"way=%d classes=%d capacity=%d comfort=%d cost=%d topspeed=%d weight=%g axle_load=%d power=%d "
"betrieb=%d sound=%d vor=%d nach=%d "
"date=%d/%d gear=%d engine_type=%d len=%d is_tilting=%d mixed_load_prohibition=%d catering_level=%d "
"way_constraints_permissive=%d way_constraints_prohibitive%d bidirectional%d can_lead_from_rear%d coupling_constraint%d",
version,
desc->wtyp,
desc->classes,
desc->capacity[0],
desc->comfort[0],
desc->base_cost,
desc->topspeed,
desc->weight/1000.0,
desc->axle_load,
desc->power,
desc->running_cost,
desc->sound,
desc->leader_count,
desc->trailer_count,
(desc->intro_date%12)+1,
desc->intro_date/12,
desc->gear,
desc->engine_type,
desc->len,
desc->is_tilting,
desc->mixed_load_prohibition,
desc->override_way_speed,
desc->catering_level,
desc->get_way_constraints().get_permissive(),
desc->get_way_constraints().get_prohibitive(),
desc->bidirectional,
desc->basic_constraint_prev,
desc->basic_constraint_next);
return desc;
}
| 22,923
| 10,383
|
auto f = [](auto) {};
| 22
| 10
|
#include "precomp.h"
#undef TRACE
#define TRACE(object) clogf << "line " << __LINE__ << ", file "\
<< __FILE__ << ", " << #object " = " << object << endl;
/* John: I think we should remove boundary references. P. */
extern ofstream clogf;
void dfuvcomp(par_t& param, par_t_reg& dfparam, dmatrix& dfu, dmatrix& dfv,
int season)
{
//clogf << " dfuvcomp for season = " << season << endl;
gridpartype_vector& dfug = (gridpartype_vector&)dfparam.get_usergrid(season);
double rdx = 30.0/param.get_deltax_eq();
double rdy = 30.0/param.get_deltay();
int _m = param.get_m();
ivector& jlb = param.get_jlb();
ivector& jub = param.get_jub();
for (int i=_m; i>=1; i--)
{
int j1 = jlb(i);
int jn = jub(i);
for (int j=jn; j>=j1; j--)
{
int k = param.get_gridmap(i, j);
//v[i][j] = ug[k].v*rdy;
dfug[k].v += rdy*dfv[i][j];
dfv[i][j] = 0.0;
//u[i][j] = ug[k].u*rdx;
dfug[k].u += rdx*dfu[i][j];
dfu[i][j] = 0.0;
}
}
}
| 1,014
| 459
|
#include <string>
#include <FL/Fl.H>
#include "layer.hpp"
florb::layer::layer() :
m_name("N/A"),
m_enabled(true)
{
add_instance(this);
};
florb::layer::~layer()
{
del_instance(this);
};
const std::string& florb::layer::name() const
{
return m_name;
};
bool florb::layer::enabled() const
{
return m_enabled;
};
void florb::layer::name(const std::string &name)
{
m_name = name;
};
void florb::layer::enable(bool en)
{
m_enabled = en;
};
| 473
| 189
|
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "storage/persistent_index.h"
#include <gtest/gtest.h>
#include "env/env_memory.h"
#include "storage/fs/file_block_manager.h"
#include "storage/fs/fs_util.h"
#include "storage/storage_engine.h"
#include "testutil/parallel_test.h"
#include "util/coding.h"
#include "util/faststring.h"
#include "util/file_utils.h"
namespace starrocks {
PARALLEL_TEST(PersistentIndexTest, test_mutable_index) {
using Key = uint64_t;
vector<Key> keys;
vector<IndexValue> values;
int N = 1000;
for (int i = 0; i < N; i++) {
keys.emplace_back(i);
values.emplace_back(i * 2);
}
auto rs = MutableIndex::create(sizeof(Key));
ASSERT_TRUE(rs.ok());
std::unique_ptr<MutableIndex> idx = std::move(rs).value();
// test insert
ASSERT_TRUE(idx->insert(keys.size(), keys.data(), values.data()).ok());
// insert duplicate should return error
ASSERT_FALSE(idx->insert(keys.size(), keys.data(), values.data()).ok());
// test get
vector<IndexValue> get_values(keys.size());
KeysInfo get_not_found;
size_t get_num_found = 0;
ASSERT_TRUE(idx->get(keys.size(), keys.data(), get_values.data(), &get_not_found, &get_num_found).ok());
ASSERT_EQ(keys.size(), get_num_found);
ASSERT_EQ(get_not_found.key_idxes.size(), 0);
for (int i = 0; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
vector<Key> get2_keys;
for (int i = 0; i < N; i++) {
get2_keys.emplace_back(i * 2);
}
vector<IndexValue> get2_values(get2_keys.size());
KeysInfo get2_not_found;
size_t get2_num_found = 0;
// should only find 0,2,..N-2, not found: N,N+2, .. N*2-2
ASSERT_TRUE(
idx->get(get2_keys.size(), get2_keys.data(), get2_values.data(), &get2_not_found, &get2_num_found).ok());
ASSERT_EQ(N / 2, get2_num_found);
// test erase
vector<Key> erase_keys;
for (int i = 0; i < N + 3; i += 3) {
erase_keys.emplace_back(i);
}
vector<IndexValue> erase_old_values(erase_keys.size());
KeysInfo erase_not_found;
size_t erase_num_found = 0;
ASSERT_TRUE(idx->erase(erase_keys.size(), erase_keys.data(), erase_old_values.data(), &erase_not_found,
&erase_num_found)
.ok());
ASSERT_EQ(erase_num_found, (N + 2) / 3);
// N+2 not found
ASSERT_EQ(erase_not_found.key_idxes.size(), 1);
// test upsert
vector<Key> upsert_keys(N, 0);
vector<IndexValue> upsert_values(upsert_keys.size());
size_t expect_exists = 0;
size_t expect_not_found = 0;
for (int i = 0; i < N; i++) {
upsert_keys[i] = i * 2;
if (i % 3 != 0 && i * 2 < N) {
expect_exists++;
}
if (i * 2 >= N && i * 2 != N + 2) {
expect_not_found++;
}
upsert_values[i] = i * 3;
}
vector<IndexValue> upsert_old_values(upsert_keys.size());
KeysInfo upsert_not_found;
size_t upsert_num_found = 0;
ASSERT_TRUE(idx->upsert(upsert_keys.size(), upsert_keys.data(), upsert_values.data(), upsert_old_values.data(),
&upsert_not_found, &upsert_num_found)
.ok());
ASSERT_EQ(upsert_num_found, expect_exists);
ASSERT_EQ(upsert_not_found.key_idxes.size(), expect_not_found);
}
PARALLEL_TEST(PersistentIndexTest, test_mutable_index_wal) {
Env* env = Env::Default();
const std::string kPersistentIndexDir = "./ut_dir/persistent_index_test";
const std::string kIndexFile = "./ut_dir/persistent_index_test/index.l0.0.0";
ASSERT_TRUE(env->create_dir(kPersistentIndexDir).ok());
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions wblock_opts({kIndexFile});
ASSERT_TRUE((block_mgr->create_block(wblock_opts, &wblock)).ok());
wblock->close();
using Key = uint64_t;
EditVersion version(0, 0);
PersistentIndexMetaPB index_meta;
index_meta.set_key_size(sizeof(Key));
index_meta.set_size(0);
version.to_pb(index_meta.mutable_version());
MutableIndexMetaPB* l0_meta = index_meta.mutable_l0_meta();
IndexSnapshotMetaPB* snapshot_meta = l0_meta->mutable_snapshot();
version.to_pb(snapshot_meta->mutable_version());
PersistentIndex index(kPersistentIndexDir);
ASSERT_TRUE(index.create(sizeof(Key), version).ok());
ASSERT_TRUE(index.load(index_meta).ok());
// insert
vector<Key> keys;
vector<IndexValue> values;
int N = 1000000;
for (int i = 0; i < N; i++) {
keys.emplace_back(i);
values.emplace_back(i * 2);
}
ASSERT_TRUE(index.prepare(EditVersion(1, 0)).ok());
ASSERT_TRUE(index.insert(100, keys.data(), values.data(), false).ok());
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
{
std::vector<IndexValue> old_values(keys.size());
ASSERT_TRUE(index.prepare(EditVersion(2, 0)).ok());
ASSERT_TRUE(index.upsert(keys.size(), keys.data(), values.data(), old_values.data()).ok());
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
}
// erase
vector<Key> erase_keys;
for (int i = 0; i < N / 2; i++) {
erase_keys.emplace_back(i);
}
vector<IndexValue> erase_old_values(erase_keys.size());
ASSERT_TRUE(index.prepare(EditVersion(3, 0)).ok());
ASSERT_TRUE(index.erase(erase_keys.size(), erase_keys.data(), erase_old_values.data()).ok());
// update PersistentMetaPB in memory
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
// append invalid wal
std::vector<Key> invalid_keys;
std::vector<IndexValue> invalid_values;
faststring fixed_buf;
for (int i = 0; i < N / 2; i++) {
invalid_keys.emplace_back(i);
invalid_values.emplace_back(i * 2);
}
{
const uint8_t* fkeys = reinterpret_cast<const uint8_t*>(invalid_keys.data());
for (int i = 0; i < N / 2; i++) {
fixed_buf.append(fkeys + i * sizeof(Key), sizeof(Key));
put_fixed64_le(&fixed_buf, invalid_values[i]);
}
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions wblock_opts({"./ut_dir/persistent_index_test/index.l0.1.0"});
wblock_opts.mode = Env::MUST_EXIST;
ASSERT_TRUE((block_mgr->create_block(wblock_opts, &wblock)).ok());
ASSERT_TRUE(wblock->append(fixed_buf).ok());
wblock->close();
}
// rebuild mutableindex according PersistentIndexMetaPB
PersistentIndex new_index(kPersistentIndexDir);
ASSERT_TRUE(new_index.create(sizeof(Key), EditVersion(3, 0)).ok());
//ASSERT_TRUE(new_index.load(index_meta).ok());
Status st = new_index.load(index_meta);
if (!st.ok()) {
LOG(WARNING) << "load failed, status is " << st.to_string();
ASSERT_TRUE(false);
}
std::vector<IndexValue> get_values(keys.size());
ASSERT_TRUE(new_index.get(keys.size(), keys.data(), get_values.data()).ok());
ASSERT_EQ(keys.size(), get_values.size());
for (int i = 0; i < N / 2; i++) {
ASSERT_EQ(NullIndexValue, get_values[i]);
}
for (int i = N / 2; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
// upsert key/value to new_index
{
vector<IndexValue> old_values(invalid_keys.size());
ASSERT_TRUE(new_index.prepare(EditVersion(4, 0)).ok());
ASSERT_TRUE(new_index.upsert(invalid_keys.size(), invalid_keys.data(), invalid_values.data(), old_values.data())
.ok());
ASSERT_TRUE(new_index.commit(&index_meta).ok());
ASSERT_TRUE(new_index.on_commited().ok());
}
// rebuild mutableindex according to PersistentIndexMetaPB
{
PersistentIndex index(kPersistentIndexDir);
ASSERT_TRUE(index.create(sizeof(Key), EditVersion(4, 0)).ok());
ASSERT_TRUE(index.load(index_meta).ok());
std::vector<IndexValue> get_values(keys.size());
ASSERT_TRUE(index.get(keys.size(), keys.data(), get_values.data()).ok());
ASSERT_EQ(keys.size(), get_values.size());
for (int i = 0; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
}
ASSERT_TRUE(FileUtils::remove_all(kPersistentIndexDir).ok());
}
PARALLEL_TEST(PersistentIndexTest, test_mutable_flush_to_immutable) {
using Key = uint64_t;
int N = 200000;
vector<Key> keys(N);
vector<IndexValue> values(N);
for (int i = 0; i < N; i++) {
keys[i] = i;
values[i] = i * 2;
}
auto rs = MutableIndex::create(sizeof(Key));
ASSERT_TRUE(rs.ok());
std::unique_ptr<MutableIndex> idx = std::move(rs).value();
// test insert
ASSERT_TRUE(idx->insert(keys.size(), keys.data(), values.data()).ok());
ASSERT_TRUE(idx->flush_to_immutable_index(".", EditVersion(1, 1)).ok());
std::unique_ptr<fs::ReadableBlock> rb;
auto block_mgr = fs::fs_util::block_manager();
ASSERT_TRUE(block_mgr->open_block("./index.l1.1.1", &rb).ok());
auto st_load = ImmutableIndex::load(std::move(rb));
if (!st_load.ok()) {
LOG(WARNING) << st_load.status();
}
ASSERT_TRUE(st_load.ok());
auto& idx_loaded = st_load.value();
KeysInfo keys_info;
for (size_t i = 0; i < N; i++) {
keys_info.key_idxes.emplace_back(i);
uint64_t h = key_index_hash(&keys[i], sizeof(Key));
keys_info.hashes.emplace_back(h);
}
vector<IndexValue> get_values(N);
size_t num_found = 0;
auto st_get = idx_loaded->get(N, keys.data(), keys_info, get_values.data(), &num_found);
if (!st_get.ok()) {
LOG(WARNING) << st_get;
}
ASSERT_TRUE(st_get.ok());
ASSERT_EQ(N, num_found);
for (size_t i = 0; i < N; i++) {
ASSERT_EQ(values[i], get_values[i]);
}
ASSERT_TRUE(idx_loaded->check_not_exist(N, keys.data()).is_already_exist());
vector<Key> check_not_exist_keys(10);
for (int i = 0; i < 10; i++) {
check_not_exist_keys[i] = N + i;
}
ASSERT_TRUE(idx_loaded->check_not_exist(10, check_not_exist_keys.data()).ok());
}
} // namespace starrocks
| 10,361
| 3,903
|
#include <iostream>
#include <fstream>
#include <string>
typedef unsigned int uint;
void write_file(std::string path, uint number)
{
std::ofstream file;
file.open(path, std::ios::app);
if (file.is_open()){
file << number << ' ';
file.close();
}else{
std::cerr << "File isn't opened!";
}
}
int main()
{
std::string path = "file.txt";
for (uint number = 1; number < 31; number ++){
write_file(path, number);
}
std::cout << "File is created";
return 0;
}
| 528
| 189
|
/*
* MIT License
*
* Copyright (c) 2021 Jimmie Bergmann
*
* 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 "Molten/Renderer/OpenGL/OpenGLWin32Renderer.hpp"
#if defined(MOLTEN_ENABLE_OPENGL)
#if MOLTEN_PLATFORM == MOLTEN_PLATFORM_WINDOWS
#include "Molten/Renderer/OpenGL/OpengGLFunctions.hpp"
#include "Molten/Renderer/PushConstant.hpp"
#include "Molten/Window/Window.hpp"
#include "Molten/System/Exception.hpp"
#include <array>
namespace Molten
{
OpenGLWin32Renderer::OpenGLWin32Renderer() :
m_deviceContext(NULL),
m_context(NULL)
{}
OpenGLWin32Renderer::OpenGLWin32Renderer(RenderTarget& renderTarget, const Version& version, Logger* logger) :
OpenGLWin32Renderer()
{
Open(renderTarget, version, logger);
}
OpenGLWin32Renderer::~OpenGLWin32Renderer()
{
Close();
}
bool OpenGLWin32Renderer::Open(RenderTarget& renderTarget, const Version& version, Logger* /*logger*/)
{
HGLRC temporaryContext = NULL;
auto deviceContext = renderTarget.GetWin32DeviceContext();
if (deviceContext == NULL)
{
throw Exception("OpenGLWin32Renderer: Device context of parameter \"window\" is null.");
}
try
{
static PIXELFORMATDESCRIPTOR pixelFormatDescriptor =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
16, //DepthBits,
8, //StencilBits,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
// Choose and set the pixel format
GLuint pixelFormat;
if ((pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDescriptor)) == 0)
{
throw Exception("OpenGLWin32Renderer: Failed to choose pixel format for Win32 device context.");
}
if ((SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDescriptor)) == false)
{
throw Exception("OpenGLWin32Renderer: Failed to set pixel format for Win32 device context.");
}
temporaryContext = ::wglCreateContext(deviceContext);
if (temporaryContext == NULL)
{
throw Exception("OpenGLWin32Renderer: Failed to create primitive Win32 OpenGL context.");
}
::wglMakeCurrent(NULL, NULL);
::wglMakeCurrent(deviceContext, temporaryContext);
if (version == Version::None)
{
Version openedVersion;
OpenBestVersion(deviceContext, openedVersion);
m_version = openedVersion;
}
else
{
OpenVersion(deviceContext, version);
m_version = version;
}
}
catch (Exception &)
{
if (temporaryContext)
{
::wglDeleteContext(temporaryContext);
}
::wglMakeCurrent(NULL, NULL);
throw;
}
catch (...)
{
throw;
}
OpenGL::BindOpenGLExtensions();
return false;
}
void OpenGLWin32Renderer::Close()
{
if (m_context)
{
// Release the context from the current thread
if (!wglMakeCurrent(NULL, NULL))
{
throw Exception("OpenGLWin32Renderer: Failed to set current context to null.");
}
// Delete the context
if (!wglDeleteContext(m_context))
{
throw Exception("OpenGLWin32Renderer: Failed to delete context.");
}
m_context = NULL;
}
}
bool OpenGLWin32Renderer::IsOpen() const
{
return false;
}
void OpenGLWin32Renderer::Resize(const Vector2ui32& /*size*/)
{
}
Renderer::BackendApi OpenGLWin32Renderer::GetBackendApi() const
{
return Renderer::BackendApi::OpenGL;
}
Version OpenGLWin32Renderer::GetVersion() const
{
return m_version;
}
const RendererCapabilities& OpenGLWin32Renderer::GetCapabilities() const
{
static RendererCapabilities tmpCapabilities = {};
return tmpCapabilities;
}
uint32_t OpenGLWin32Renderer::GetPushConstantLocation(Pipeline& /*pipeline*/, const uint32_t /*id*/)
{
return PushConstantLocation::UnknownLocation;
}
RenderResource<DescriptorSet> OpenGLWin32Renderer::CreateDescriptorSet(const DescriptorSetDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<FramedDescriptorSet> OpenGLWin32Renderer::CreateFramedDescriptorSet(const FramedDescriptorSetDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<IndexBuffer> OpenGLWin32Renderer::CreateIndexBuffer(const IndexBufferDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<Pipeline> OpenGLWin32Renderer::CreatePipeline(const PipelineDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<RenderPass> OpenGLWin32Renderer::CreateRenderPass(const RenderPassDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler1D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler2D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler3D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor3D& /*descriptor*/)
{
return { };
}
SharedRenderResource<ShaderProgram> OpenGLWin32Renderer::CreateShaderProgram(const VisualShaderProgramDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture1D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture2D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture3D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor3D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture1D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture2D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture3D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor3D& /*descriptor*/)
{
return { };
}
RenderResource<UniformBuffer> OpenGLWin32Renderer::CreateUniformBuffer(const UniformBufferDescriptor&)
{
return { };
}
RenderResource<FramedUniformBuffer> OpenGLWin32Renderer::CreateFramedUniformBuffer(const FramedUniformBufferDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<VertexBuffer> OpenGLWin32Renderer::CreateVertexBuffer(const VertexBufferDescriptor&)
{
return { };
}
bool OpenGLWin32Renderer::UpdateRenderPass(RenderPass& /*renderPass*/, const RenderPassUpdateDescriptor& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture1D& /*texture1D*/, const TextureUpdateDescriptor1D& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture2D& /*texture2D*/, const TextureUpdateDescriptor2D& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture3D& /*texture3D*/, const TextureUpdateDescriptor3D& /*descriptor*/)
{
return false;
}
void OpenGLWin32Renderer::UpdateUniformBuffer(RenderResource<UniformBuffer>& /*uniformBuffer*/, const void* /*data*/, const size_t /*size*/, const size_t /*offset*/)
{
}
void OpenGLWin32Renderer::UpdateFramedUniformBuffer(RenderResource<FramedUniformBuffer>& /*framedUniformBuffer*/, const void* /*data*/, const size_t /*size*/, const size_t /*offset*/)
{
}
bool OpenGLWin32Renderer::DrawFrame(const RenderPasses& /*renderPasses*/)
{
return false;
}
void OpenGLWin32Renderer::Destroy(DescriptorSet& /*descriptorSet*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedDescriptorSet& /*framedDescriptorSet*/)
{
}
void OpenGLWin32Renderer::Destroy(IndexBuffer& /*indexBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(Pipeline& /*pipeline*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler1D& /*sampler1D*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler2D& /*sampler2D*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler3D& /*sampler3D*/)
{
}
void OpenGLWin32Renderer::Destroy(ShaderProgram& /*shaderProgram*/ )
{
}
void OpenGLWin32Renderer::Destroy(Texture1D& /*texture1D*/)
{
}
void OpenGLWin32Renderer::Destroy(Texture2D& /*texture2D*/)
{
}
void OpenGLWin32Renderer::Destroy(Texture3D& /*texture3D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture1D& /*framedTexture1D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture2D& /*framedTexture2D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture3D& /*framedTexture3D*/)
{
}
void OpenGLWin32Renderer::Destroy(UniformBuffer& /*uniformBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedUniformBuffer& /*framedUniformBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(VertexBuffer& /*vertexBuffer*/)
{
}
void OpenGLWin32Renderer::WaitForDevice()
{
}
bool OpenGLWin32Renderer::OpenVersion(HDC deviceContext, const Version& version)
{
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
if ((wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB")) == NULL)
{
throw Exception("Cannot get address of wglCreateContextAttribsARB.");
}
const int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(version.Major),
WGL_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(version.Minor),
0
};
if ((m_context = wglCreateContextAttribsARB(deviceContext, 0, attributes)) == NULL)
{
throw Exception("Failed to create OpenGL context version " + version.AsString());
}
return true;
}
void OpenGLWin32Renderer::OpenBestVersion(HDC deviceContext, Version& version)
{
static const std::array versions =
{
Version(4, 6),
Version(4, 5),
Version(4, 4),
Version(4, 3),
Version(4, 2),
Version(4, 1),
Version(4, 0),
Version(3, 3),
Version(3, 2),
Version(3, 1),
Version(3, 0),
Version(2, 1),
Version(2, 0)
};
version = Version::None;
for(auto it = versions.begin(); it != versions.end(); it++)
{
try
{
const Version& ver = *it;
if (OpenVersion(deviceContext, ver))
{
version = ver;
return;
}
}
catch (Exception & e)
{
if(std::next(it) != versions.end())
{
continue;
}
throw Exception("OpenGLWin32Renderer: Failed to create best OpenGL context, last error: " + e.GetMessage());
}
}
}
}
#endif
#endif
| 13,156
| 3,933
|
/*******************************************************************************
The content of this file includes portions of the AUDIOKINETIC Wwise Technology
released in source code form as part of the SDK installer package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use this file in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Version: v2017.2.9 Build: 6726
Copyright (c) 2006-2019 Audiokinetic Inc.
*******************************************************************************/
//////////////////////////////////////////////////////////////////////
//
// AkDelayFX.cpp
//
// Sample delay FX implementation.
//
//////////////////////////////////////////////////////////////////////
#include "AkDelayFX.h"
#include <AK/Tools/Common/AkAssert.h>
#include <AK/AkWwiseSDKVersion.h>
/// Plugin mechanism. Instantiation method that must be registered to the plug-in manager.
AK::IAkPlugin* CreateAkDelayFX( AK::IAkPluginMemAlloc * in_pAllocator )
{
return AK_PLUGIN_NEW( in_pAllocator, CAkDelayFX( ) );
}
/// Plugin mechanism. Instantiation method that must be registered to the plug-in manager.
AK::IAkPluginParam * CreateAkDelayFXParams(AK::IAkPluginMemAlloc * in_pAllocator)
{
return AK_PLUGIN_NEW(in_pAllocator, CAkDelayFXParams());
}
AK_IMPLEMENT_PLUGIN_FACTORY(AkDelayFX, AkPluginTypeEffect, 0, 106)
/// Constructor.
CAkDelayFX::CAkDelayFX()
: m_pParams( NULL )
, m_pAllocator( NULL )
{
}
/// Destructor.
CAkDelayFX::~CAkDelayFX()
{
}
/// Initializes and allocate memory for the effect.
AKRESULT CAkDelayFX::Init( AK::IAkPluginMemAlloc * in_pAllocator, /// Memory allocator interface.
AK::IAkEffectPluginContext * in_pFXCtx, /// Sound engine plug-in execution context.
AK::IAkPluginParam * in_pParams, /// Associated effect parameters node.
AkAudioFormat & in_rFormat /// Input/output audio format.
)
{
m_pParams = (CAkDelayFXParams*)in_pParams;
m_pAllocator = in_pAllocator;
m_FXState.Setup( m_pParams, in_rFormat.uSampleRate );
AKRESULT eResult = m_FXState.InitDelay( in_pAllocator, m_pParams, in_rFormat.channelConfig );
m_FXState.ComputeTailLength( m_pParams->RTPC.bFeedbackEnabled, m_pParams->RTPC.fFeedback );
m_pParams->NonRTPC.bHasChanged = false;
m_pParams->RTPC.bHasChanged = false;
AK_PERF_RECORDING_RESET();
return eResult;
}
/// Effect termination.
AKRESULT CAkDelayFX::Term( AK::IAkPluginMemAlloc * in_pAllocator )
{
m_FXState.TermDelay( in_pAllocator );
AK_PLUGIN_DELETE( in_pAllocator, this ); /// Effect must delete itself
return AK_Success;
}
/// Actions to perform on FX reset (example on bypass)
AKRESULT CAkDelayFX::Reset( )
{
m_FXState.ResetDelay();
return AK_Success;
}
/// Effect info query.
AKRESULT CAkDelayFX::GetPluginInfo( AkPluginInfo & out_rPluginInfo )
{
out_rPluginInfo.eType = AkPluginTypeEffect;
out_rPluginInfo.bIsInPlace = true;
out_rPluginInfo.uBuildVersion = AK_WWISESDK_VERSION_COMBINED;
return AK_Success;
}
/// Effect plug-in DSP processing
void CAkDelayFX::Execute( AkAudioBuffer * io_pBuffer )
{
if ( AK_EXPECT_FALSE( m_pParams->NonRTPC.bHasChanged ) )
{
AKRESULT eResult = m_FXState.InitDelay( m_pAllocator, m_pParams, io_pBuffer->GetChannelConfig() );
if ( eResult != AK_Success )
return; // passthrough
m_FXState.ResetDelay();
m_pParams->NonRTPC.bHasChanged = false;
}
if ( AK_EXPECT_FALSE( m_pParams->RTPC.bHasChanged ) )
{
m_FXState.ComputeTailLength( m_pParams->RTPC.bFeedbackEnabled, m_pParams->RTPC.fFeedback );
m_pParams->RTPC.bHasChanged = false;
}
AK_PERF_RECORDING_START( "Delay", 25, 30 );
// Execute DSP processing synchronously here
m_FXState.Process( io_pBuffer, m_pParams );
AK_PERF_RECORDING_STOP( "Delay", 25, 30 );
}
| 3,919
| 1,459
|
#include <cligen/cligen.h>
#include <clixon/clixon.h>
#include "plugin_lifecycle.h"
int LifecycleManager::plugin_start(clicon_handle h) {
return 0;
}
int LifecycleManager::plugin_exit(clicon_handle h) {
return 0;
}
int LifecycleManager::plugin_daemon(clicon_handle h) {
return 0;
}
| 298
| 118
|
#include <iostream>
struct [[nodiscard]] error_info { /*...*/ };
error_info enable_missile_safety_mode() { /*...*/ return {}; }
void launch_missiles() { /*...*/ }
void test_missiles()
{
enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value
launch_missiles();
}
// nodiscard( string-literal ) (since C++20):
struct [[nodiscard("OneFLOW CFD")]] cfd_info { /*...*/ };
void test_cfd()
{
cfd_info();
}
int main ( int argc, char **argv )
{
{
}
return 0;
}
| 504
| 192
|
#include "NotificationFdbEvent.h"
#include "Meta.h"
#include "MetaTestSaiInterface.h"
#include "sairediscommon.h"
#include "sai_serialize.h"
#include <gtest/gtest.h>
#include <memory>
using namespace sairedis;
using namespace saimeta;
static std::string s =
"[{\"fdb_entry\":\"{\\\"bvid\\\":\\\"oid:0x260000000005be\\\",\\\"mac\\\":\\\"52:54:00:86:DD:7A\\\",\\\"switch_id\\\":\\\"oid:0x21000000000000\\\"}\","
"\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\","
"\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_TYPE\",\"value\":\"SAI_FDB_ENTRY_TYPE_DYNAMIC\"},{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\"oid:0x3a000000000660\"}]}]";
static std::string null =
"[{\"fdb_entry\":\"{\\\"bvid\\\":\\\"oid:0x260000000005be\\\",\\\"mac\\\":\\\"52:54:00:86:DD:7A\\\",\\\"switch_id\\\":\\\"oid:0x0\\\"}\","
"\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\","
"\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_TYPE\",\"value\":\"SAI_FDB_ENTRY_TYPE_DYNAMIC\"},{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\"oid:0x3a000000000660\"}]}]";
static std::string fullnull = "[]";
TEST(NotificationFdbEvent, ctr)
{
NotificationFdbEvent n(s);
}
TEST(NotificationFdbEvent, getSwitchId)
{
NotificationFdbEvent n(s);
EXPECT_EQ(n.getSwitchId(), 0x21000000000000);
NotificationFdbEvent n2(null);
EXPECT_EQ(n2.getSwitchId(), 0);
}
TEST(NotificationFdbEvent, getAnyObjectId)
{
NotificationFdbEvent n(s);
EXPECT_EQ(n.getAnyObjectId(), 0x21000000000000);
NotificationFdbEvent n2(null);
EXPECT_EQ(n2.getAnyObjectId(), 0x260000000005be);
NotificationFdbEvent n3(fullnull);
EXPECT_EQ(n3.getSwitchId(), 0x0);
EXPECT_EQ(n3.getAnyObjectId(), 0x0);
}
TEST(NotificationFdbEvent, processMetadata)
{
NotificationFdbEvent n(s);
auto sai = std::make_shared<MetaTestSaiInterface>();
auto meta = std::make_shared<Meta>(sai);
n.processMetadata(meta);
}
| 1,882
| 890
|
// Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <algorithm>
#include <cmath>
#include <functional>
#include <random>
#include <vector>
#include <xnnpack.h>
#include <benchmark/benchmark.h>
#include "bench/end2end.h"
#include "bench/utils.h"
#include "models/models.h"
#include <xnnpack/gemm.h>
#include <xnnpack/igemm.h>
#include <xnnpack/params.h>
static void GEMMEnd2EndBenchmark(
benchmark::State& state,
models::ExecutionPlanFactory model_factory,
xnn_f32_gemm_ukernel_function gemm,
xnn_f32_igemm_ukernel_function igemm,
xnn_f32_gemm_ukernel_function gemm1,
xnn_f32_igemm_ukernel_function igemm1,
uint8_t mr, uint8_t nr, uint8_t log2_kr = 0, uint8_t log2_sr = 0,
benchmark::utils::IsaCheckFunction isa_check = nullptr)
{
if (isa_check && !isa_check(state)) {
return;
}
if (xnn_initialize(nullptr /* allocator */) != xnn_status_success) {
state.SkipWithError("failed to initialize XNNPACK");
return;
}
// Override microkernels chosen in xnn_initialize
xnn_params.f32.gemm = (struct gemm_parameters) {
.gemm = xnn_gemm_ukernel_function(gemm),
.igemm = xnn_igemm_ukernel_function(igemm),
.gemm1 = xnn_gemm_ukernel_function(gemm1),
.igemm1 = xnn_igemm_ukernel_function(igemm1),
.mr = mr,
.nr = nr,
.log2_kr = log2_kr,
.log2_sr = log2_sr,
};
auto execution_plan = model_factory(nullptr);
if (execution_plan.empty()) {
state.SkipWithError("failed to create a model");
return;
}
for (auto _ : state) {
for (const std::unique_ptr<xnn_operator, decltype(&xnn_delete_operator)>& op : execution_plan) {
xnn_status status = xnn_run_operator(op.get(), nullptr);
if (status != xnn_status_success) {
state.SkipWithError("failed to run a model");
return;
}
}
}
state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency();
}
#if XNN_ARCH_ARM64 && XNN_ENABLE_ASSEMBLY
static void f32_gemm_4x12__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x12__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_4x12__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x12__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x12__aarch64_neonfma_cortex_a53,
4 /* mr */, 12 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_5x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_5x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
5 /* mr */, 8 /* nr */);
}
static void f32_gemm_5x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_5x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
5 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a73(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a73,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a73,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__neonfma_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__neonfma_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__neonfma_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__neonfma_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_lane_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_ld64)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_ld128);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_ld64);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_ld128);
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a53)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a57)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a75)
BENCHMARK_END2END(f32_gemm_5x8__aarch64_neonfma_cortex_a57);
BENCHMARK_END2END(f32_gemm_5x8__aarch64_neonfma_cortex_a75);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a53);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a73);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a57);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a75);
BENCHMARK_END2END(f32_gemm_4x12__aarch64_neonfma_cortex_a53)
BENCHMARK_END2END(f32_gemm_4x8__neonfma_lane_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_lane_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_lane_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_lane_ld128);
#endif // XNN_ARCH_ARM64 && XNN_ENABLE_ASSEMBLY
#if XNN_ARCH_ARM && XNN_ENABLE_ASSEMBLY
static void f32_gemm_4x8__aarch32_neon_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_ld64,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_cortex_a53,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_cortex_a75,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_pld_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_pld_cortex_a75,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_ld64);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_cortex_a53);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_cortex_a75);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_pld_cortex_a75);
#endif // XNN_ARCH_ARM && XNN_ENABLE_ASSEMBLY
#if XNN_ARCH_ARM || XNN_ARCH_ARM64
static void f32_gemm_4x8__neon_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_lane_ld128,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_6x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_lane_ld128,
xnn_f32_igemm_ukernel_6x8__neon_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_4x8__neon_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_dup_ld128,
xnn_f32_igemm_ukernel_4x8__neon_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_6x8__neon_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_dup_ld128,
xnn_f32_igemm_ukernel_6x8__neon_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neonfma_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_4x8__neonfma_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_dup_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8__neonfma_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8__neonfma_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_dup_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_4x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__neon,
xnn_f32_igemm_ukernel_4x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__neonfma,
xnn_f32_igemm_ukernel_4x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__neon,
xnn_f32_igemm_ukernel_6x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__neonfma,
xnn_f32_igemm_ukernel_6x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_8x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8s4__neon,
xnn_f32_igemm_ukernel_8x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
8 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_8x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8s4__neonfma,
xnn_f32_igemm_ukernel_8x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
8 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
BENCHMARK_END2END(f32_gemm_4x8__neon_lane_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neon_lane_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neon_lane_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neon_lane_ld128);
BENCHMARK_END2END(f32_gemm_4x8__neon_dup_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neon_dup_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neon_dup_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neon_dup_ld128);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_dup_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_dup_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_dup_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_dup_ld128);
BENCHMARK_END2END(f32_gemm_4x8s4__neon);
BENCHMARK_END2END(f32_gemm_6x8s4__neon);
BENCHMARK_END2END(f32_gemm_8x8s4__neon);
BENCHMARK_END2END(f32_gemm_4x8s4__neonfma);
BENCHMARK_END2END(f32_gemm_6x8s4__neonfma);
BENCHMARK_END2END(f32_gemm_8x8s4__neonfma);
#endif // XNN_ARCH_ARM || XNN_ARCH_ARM64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
static void f32_gemm_4x8__sse_load1(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__sse_load1,
xnn_f32_igemm_ukernel_4x8__sse_load1,
xnn_f32_gemm_ukernel_1x8__sse_load1,
xnn_f32_igemm_ukernel_1x8__sse_load1,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__sse_dup(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__sse_dup,
xnn_f32_igemm_ukernel_4x8__sse_dup,
xnn_f32_gemm_ukernel_1x8__sse_dup,
xnn_f32_igemm_ukernel_1x8__sse_dup,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8s4__sse(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__sse,
xnn_f32_igemm_ukernel_4x8s4__sse,
xnn_f32_gemm_ukernel_1x8s4__sse,
xnn_f32_igemm_ukernel_1x8s4__sse,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
static void f32_gemm_4x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__avx_broadcast,
xnn_f32_igemm_ukernel_4x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_5x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__avx_broadcast,
xnn_f32_igemm_ukernel_5x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
5 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_6x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__avx_broadcast,
xnn_f32_igemm_ukernel_6x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_7x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x8__avx_broadcast,
xnn_f32_igemm_ukernel_7x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
7 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_3x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16__avx_broadcast,
xnn_f32_igemm_ukernel_3x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_4x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__avx_broadcast,
xnn_f32_igemm_ukernel_4x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_5x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__avx_broadcast,
xnn_f32_igemm_ukernel_5x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_4x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__fma3_broadcast,
xnn_f32_igemm_ukernel_4x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__fma3_broadcast,
xnn_f32_igemm_ukernel_5x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
5 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_6x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__fma3_broadcast,
xnn_f32_igemm_ukernel_6x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_7x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x8__fma3_broadcast,
xnn_f32_igemm_ukernel_7x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
7 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_8x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8__fma3_broadcast,
xnn_f32_igemm_ukernel_8x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
8 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_3x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16__fma3_broadcast,
xnn_f32_igemm_ukernel_3x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__fma3_broadcast,
xnn_f32_igemm_ukernel_4x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__fma3_broadcast,
xnn_f32_igemm_ukernel_5x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_3x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_3x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_4x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_5x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_4x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_5x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_5x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_6x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_6x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
6 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_7x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_7x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
7 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_8x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_8x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
8 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
BENCHMARK_END2END(f32_gemm_4x8__sse_load1);
BENCHMARK_END2END(f32_gemm_4x8__sse_dup);
BENCHMARK_END2END(f32_gemm_4x8s4__sse);
BENCHMARK_END2END(f32_gemm_4x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_5x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_6x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_7x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_3x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_4x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_6x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_7x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_8x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_3x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_3x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_6x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_7x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_8x16__avx512f_broadcast);
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if !XNN_ARCH_WASM && !XNN_ARCH_ASMJS
static void f32_gemm_4x8__psimd_loadsplat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_4x8__psimd_loadsplat,
xnn_f32_gemm_ukernel_1x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_1x8__psimd_loadsplat,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__psimd_loadsplat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_6x8__psimd_loadsplat,
xnn_f32_gemm_ukernel_1x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_1x8__psimd_loadsplat,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__psimd_splat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__psimd_splat,
xnn_f32_igemm_ukernel_4x8__psimd_splat,
xnn_f32_gemm_ukernel_1x8__psimd_splat,
xnn_f32_igemm_ukernel_1x8__psimd_splat,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__psimd_splat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__psimd_splat,
xnn_f32_igemm_ukernel_6x8__psimd_splat,
xnn_f32_gemm_ukernel_1x8__psimd_splat,
xnn_f32_igemm_ukernel_1x8__psimd_splat,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8s4__psimd(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__psimd,
xnn_f32_igemm_ukernel_4x8s4__psimd,
xnn_f32_gemm_ukernel_1x8s4__psimd,
xnn_f32_igemm_ukernel_1x8s4__psimd,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
static void f32_gemm_6x8s4__psimd(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__psimd,
xnn_f32_igemm_ukernel_6x8s4__psimd,
xnn_f32_gemm_ukernel_1x8s4__psimd,
xnn_f32_igemm_ukernel_1x8s4__psimd,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
BENCHMARK_END2END(f32_gemm_4x8__psimd_loadsplat);
BENCHMARK_END2END(f32_gemm_6x8__psimd_loadsplat);
BENCHMARK_END2END(f32_gemm_4x8__psimd_splat);
BENCHMARK_END2END(f32_gemm_6x8__psimd_splat);
BENCHMARK_END2END(f32_gemm_4x8s4__psimd);
BENCHMARK_END2END(f32_gemm_6x8s4__psimd);
#endif // !XNN_ARCH_WASM && !XNN_ARCH_ASMJS
#if XNN_ARCH_WASM
static void f32_gemm_2x4__wasm(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_2x4__wasm,
xnn_f32_igemm_ukernel_2x4__wasm,
xnn_f32_gemm_ukernel_1x4__wasm,
xnn_f32_igemm_ukernel_1x4__wasm,
2 /* mr */, 4 /* nr */);
}
static void f32_gemm_4x4__wasm(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x4__wasm,
xnn_f32_igemm_ukernel_4x4__wasm,
xnn_f32_gemm_ukernel_1x4__wasm,
xnn_f32_igemm_ukernel_1x4__wasm,
4 /* mr */, 4 /* nr */);
}
BENCHMARK_END2END(f32_gemm_2x4__wasm);
BENCHMARK_END2END(f32_gemm_4x4__wasm);
#endif // XNN_ARCH_WASM
static void f32_gemm_2x4__scalar(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_2x4__scalar,
xnn_f32_igemm_ukernel_2x4__scalar,
xnn_f32_gemm_ukernel_1x4__scalar,
xnn_f32_igemm_ukernel_1x4__scalar,
2 /* mr */, 4 /* nr */);
}
static void f32_gemm_4x4__scalar(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x4__scalar,
xnn_f32_igemm_ukernel_4x4__scalar,
xnn_f32_gemm_ukernel_1x4__scalar,
xnn_f32_igemm_ukernel_1x4__scalar,
4 /* mr */, 4 /* nr */);
}
BENCHMARK_END2END(f32_gemm_2x4__scalar);
BENCHMARK_END2END(f32_gemm_4x4__scalar);
#ifndef XNNPACK_BENCHMARK_NO_MAIN
BENCHMARK_MAIN();
#endif
| 38,689
| 19,550
|
/*****************************************************************************
*
* ftp.cpp - FTP folder bookkeeping
*
*****************************************************************************/
#include "priv.h"
//#include "ftpinet.h"
//#include "ftpsite.h"
//#include "ftplist.h"
//#include "msieftp.h"
//#include "cookie.h"
extern struct GLOBALTIMEOUTINFO g_gti;
extern DWORD g_dwOpenConnections;
/*****************************************************************************
*
* Dynamic Globals. There should be as few of these as possible.
*
* All access to dynamic globals must be thread-safe.
*
*****************************************************************************/
ULONG g_cRef = 0; /* Global reference count */
CRITICAL_SECTION g_csDll; /* The shared critical section */
#ifdef DEBUG
DWORD g_TlsMem = 0xffffffff;
#endif // DEBUG
ULONG g_cRef_CFtpView = 0; // Needed to determine when to purge cache.
/*****************************************************************************
*
* DllAddRef / DllRelease
*
* Maintain the DLL reference count.
*
*****************************************************************************/
void DllAddRef(void)
{
InterlockedIncrement((LPLONG)&g_cRef);
}
void DllRelease(void)
{
InterlockedDecrement((LPLONG)&g_cRef);
}
/*****************************************************************************
*
* DllGetClassObject
*
* OLE entry point. Produces an IClassFactory for the indicated GUID.
*
* The artificial refcount inside DllGetClassObject helps to
* avoid the race condition described in DllCanUnloadNow. It's
* not perfect, but it makes the race window much smaller.
*
*****************************************************************************/
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID * ppvObj)
{
HRESULT hres;
DllAddRef();
// if (IsEqualIID(rclsid, CLSID_FtpFolder) ||
// IsEqualIID(rclsid, CLSID_FtpWebView))
{
hres = CFtpFactory_Create(rclsid, riid, ppvObj);
}
// else
// {
// *ppvObj = NULL;
// hres = CLASS_E_CLASSNOTAVAILABLE;
// }
DllRelease();
return hres;
}
/*****************************************************************************
*
* DllCanUnloadNow
*
* OLE entry point. Fail iff there are outstanding refs.
*
* There is an unavoidable race condition between DllCanUnloadNow
* and the creation of a new IClassFactory: Between the time we
* return from DllCanUnloadNow() and the caller inspects the value,
* another thread in the same process may decide to call
* DllGetClassObject, thus suddenly creating an object in this DLL
* when there previously was none.
*
* It is the caller's responsibility to prepare for this possibility;
* there is nothing we can do about it.
*
*****************************************************************************/
STDMETHODIMP DllCanUnloadNow(void)
{
HRESULT hres;
ENTERCRITICAL;
hres = g_cRef ? S_FALSE : S_OK;
TraceMsg(TF_FTP_DLLLOADING, "DllCanUnloadNow() returning hres=%#08lx. (S_OK means yes)", hres);
LEAVECRITICAL;
return hres;
}
/*****************************************************************************
*
* Entry32
*
* DLL entry point.
*
* BUGBUG -- On a thread detach, must check if the thread owns any
* global timeouts. If so, we must transfer the timeout to another
* thread or something.
*
*****************************************************************************/
STDAPI_(BOOL) DllEntry(HINSTANCE hinst, DWORD dwReason, LPVOID lpReserved)
{
static s_hresOle = E_FAIL;
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
InitializeCriticalSection(&g_csDll);
g_hinst = hinst;
DisableThreadLibraryCalls(hinst);
break;
case DLL_PROCESS_DETACH:
DeleteCriticalSection(&g_csDll);
break;
}
return 1;
}
const CLSID CLSID_FtpFolder = {0x63da6ec0, 0x2e98, 0x11cf, 0x8d,0x82,0x44,0x45,0x53,0x54,0,0};
| 4,139
| 1,381
|
// Copyright 2020 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dawn_native/CopyTextureForBrowserHelper.h"
#include "dawn_native/BindGroup.h"
#include "dawn_native/BindGroupLayout.h"
#include "dawn_native/Buffer.h"
#include "dawn_native/CommandBuffer.h"
#include "dawn_native/CommandEncoder.h"
#include "dawn_native/CommandValidation.h"
#include "dawn_native/Device.h"
#include "dawn_native/InternalPipelineStore.h"
#include "dawn_native/Queue.h"
#include "dawn_native/RenderPassEncoder.h"
#include "dawn_native/RenderPipeline.h"
#include "dawn_native/Sampler.h"
#include "dawn_native/Texture.h"
#include "dawn_native/ValidationUtils_autogen.h"
#include "dawn_native/utils/WGPUHelpers.h"
#include <unordered_set>
namespace dawn_native {
namespace {
static const char sCopyTextureForBrowserShader[] = R"(
[[block]] struct Uniforms {
u_scale: vec2<f32>;
u_offset: vec2<f32>;
u_alphaOp: u32;
};
[[binding(0), group(0)]] var<uniform> uniforms : Uniforms;
struct VertexOutputs {
[[location(0)]] texcoords : vec2<f32>;
[[builtin(position)]] position : vec4<f32>;
};
[[stage(vertex)]] fn vs_main(
[[builtin(vertex_index)]] VertexIndex : u32
) -> VertexOutputs {
var texcoord = array<vec2<f32>, 3>(
vec2<f32>(-0.5, 0.0),
vec2<f32>( 1.5, 0.0),
vec2<f32>( 0.5, 2.0));
var output : VertexOutputs;
output.position = vec4<f32>((texcoord[VertexIndex] * 2.0 - vec2<f32>(1.0, 1.0)), 0.0, 1.0);
// Y component of scale is calculated by the copySizeHeight / textureHeight. Only
// flipY case can get negative number.
var flipY = uniforms.u_scale.y < 0.0;
// Texture coordinate takes top-left as origin point. We need to map the
// texture to triangle carefully.
if (flipY) {
// We need to get the mirror positions(mirrored based on y = 0.5) on flip cases.
// Adopt transform to src texture and then mapping it to triangle coord which
// do a +1 shift on Y dimension will help us got that mirror position perfectly.
output.texcoords = (texcoord[VertexIndex] * uniforms.u_scale + uniforms.u_offset) *
vec2<f32>(1.0, -1.0) + vec2<f32>(0.0, 1.0);
} else {
// For the normal case, we need to get the exact position.
// So mapping texture to triangle firstly then adopt the transform.
output.texcoords = (texcoord[VertexIndex] *
vec2<f32>(1.0, -1.0) + vec2<f32>(0.0, 1.0)) *
uniforms.u_scale + uniforms.u_offset;
}
return output;
}
[[binding(1), group(0)]] var mySampler: sampler;
[[binding(2), group(0)]] var myTexture: texture_2d<f32>;
[[stage(fragment)]] fn fs_main(
[[location(0)]] texcoord : vec2<f32>
) -> [[location(0)]] vec4<f32> {
// Clamp the texcoord and discard the out-of-bound pixels.
var clampedTexcoord =
clamp(texcoord, vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 1.0));
if (!all(clampedTexcoord == texcoord)) {
discard;
}
// Swizzling of texture formats when sampling / rendering is handled by the
// hardware so we don't need special logic in this shader. This is covered by tests.
var srcColor = textureSample(myTexture, mySampler, texcoord);
// Handle alpha. Alpha here helps on the source content and dst content have
// different alpha config. There are three possible ops: DontChange, Premultiply
// and Unpremultiply.
// TODO(crbug.com/1217153): if wgsl support `constexpr` and allow it
// to be case selector, Replace 0u/1u/2u with a constexpr variable with
// meaningful name.
switch(uniforms.u_alphaOp) {
case 0u: { // AlphaOp: DontChange
break;
}
case 1u: { // AlphaOp: Premultiply
srcColor = vec4<f32>(srcColor.rgb * srcColor.a, srcColor.a);
break;
}
case 2u: { // AlphaOp: Unpremultiply
if (srcColor.a != 0.0) {
srcColor = vec4<f32>(srcColor.rgb / srcColor.a, srcColor.a);
}
break;
}
default: {
break;
}
}
return srcColor;
}
)";
struct Uniform {
float scaleX;
float scaleY;
float offsetX;
float offsetY;
wgpu::AlphaOp alphaOp;
};
static_assert(sizeof(Uniform) == 20, "");
// TODO(crbug.com/dawn/856): Expand copyTextureForBrowser to support any
// non-depth, non-stencil, non-compressed texture format pair copy. Now this API
// supports CopyImageBitmapToTexture normal format pairs.
MaybeError ValidateCopyTextureFormatConversion(const wgpu::TextureFormat srcFormat,
const wgpu::TextureFormat dstFormat) {
switch (srcFormat) {
case wgpu::TextureFormat::BGRA8Unorm:
case wgpu::TextureFormat::RGBA8Unorm:
break;
default:
return DAWN_FORMAT_VALIDATION_ERROR(
"Source texture format (%s) is not supported.", srcFormat);
}
switch (dstFormat) {
case wgpu::TextureFormat::R8Unorm:
case wgpu::TextureFormat::R16Float:
case wgpu::TextureFormat::R32Float:
case wgpu::TextureFormat::RG8Unorm:
case wgpu::TextureFormat::RG16Float:
case wgpu::TextureFormat::RG32Float:
case wgpu::TextureFormat::RGBA8Unorm:
case wgpu::TextureFormat::RGBA8UnormSrgb:
case wgpu::TextureFormat::BGRA8Unorm:
case wgpu::TextureFormat::BGRA8UnormSrgb:
case wgpu::TextureFormat::RGB10A2Unorm:
case wgpu::TextureFormat::RGBA16Float:
case wgpu::TextureFormat::RGBA32Float:
break;
default:
return DAWN_FORMAT_VALIDATION_ERROR(
"Destination texture format (%s) is not supported.", dstFormat);
}
return {};
}
RenderPipelineBase* GetCachedPipeline(InternalPipelineStore* store,
wgpu::TextureFormat dstFormat) {
auto pipeline = store->copyTextureForBrowserPipelines.find(dstFormat);
if (pipeline != store->copyTextureForBrowserPipelines.end()) {
return pipeline->second.Get();
}
return nullptr;
}
ResultOrError<RenderPipelineBase*> GetOrCreateCopyTextureForBrowserPipeline(
DeviceBase* device,
wgpu::TextureFormat dstFormat) {
InternalPipelineStore* store = device->GetInternalPipelineStore();
if (GetCachedPipeline(store, dstFormat) == nullptr) {
// Create vertex shader module if not cached before.
if (store->copyTextureForBrowser == nullptr) {
DAWN_TRY_ASSIGN(
store->copyTextureForBrowser,
utils::CreateShaderModule(device, sCopyTextureForBrowserShader));
}
ShaderModuleBase* shaderModule = store->copyTextureForBrowser.Get();
// Prepare vertex stage.
VertexState vertex = {};
vertex.module = shaderModule;
vertex.entryPoint = "vs_main";
// Prepare frgament stage.
FragmentState fragment = {};
fragment.module = shaderModule;
fragment.entryPoint = "fs_main";
// Prepare color state.
ColorTargetState target = {};
target.format = dstFormat;
// Create RenderPipeline.
RenderPipelineDescriptor renderPipelineDesc = {};
// Generate the layout based on shader modules.
renderPipelineDesc.layout = nullptr;
renderPipelineDesc.vertex = vertex;
renderPipelineDesc.fragment = &fragment;
renderPipelineDesc.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
fragment.targetCount = 1;
fragment.targets = ⌖
Ref<RenderPipelineBase> pipeline;
DAWN_TRY_ASSIGN(pipeline, device->CreateRenderPipeline(&renderPipelineDesc));
store->copyTextureForBrowserPipelines.insert({dstFormat, std::move(pipeline)});
}
return GetCachedPipeline(store, dstFormat);
}
} // anonymous namespace
MaybeError ValidateCopyTextureForBrowser(DeviceBase* device,
const ImageCopyTexture* source,
const ImageCopyTexture* destination,
const Extent3D* copySize,
const CopyTextureForBrowserOptions* options) {
DAWN_TRY(device->ValidateObject(source->texture));
DAWN_TRY(device->ValidateObject(destination->texture));
DAWN_TRY_CONTEXT(ValidateImageCopyTexture(device, *source, *copySize),
"validating the ImageCopyTexture for the source");
DAWN_TRY_CONTEXT(ValidateImageCopyTexture(device, *destination, *copySize),
"validating the ImageCopyTexture for the destination");
DAWN_TRY_CONTEXT(ValidateTextureCopyRange(device, *source, *copySize),
"validating that the copy fits in the source");
DAWN_TRY_CONTEXT(ValidateTextureCopyRange(device, *destination, *copySize),
"validating that the copy fits in the destination");
DAWN_TRY(ValidateTextureToTextureCopyCommonRestrictions(*source, *destination, *copySize));
DAWN_INVALID_IF(source->origin.z > 0, "Source has a non-zero z origin (%u).",
source->origin.z);
DAWN_INVALID_IF(copySize->depthOrArrayLayers > 1,
"Copy is for more than one array layer (%u)", copySize->depthOrArrayLayers);
DAWN_INVALID_IF(
source->texture->GetSampleCount() > 1 || destination->texture->GetSampleCount() > 1,
"The source texture sample count (%u) or the destination texture sample count (%u) is "
"not 1.",
source->texture->GetSampleCount(), destination->texture->GetSampleCount());
DAWN_TRY(ValidateCanUseAs(source->texture, wgpu::TextureUsage::CopySrc));
DAWN_TRY(ValidateCanUseAs(source->texture, wgpu::TextureUsage::TextureBinding));
DAWN_TRY(ValidateCanUseAs(destination->texture, wgpu::TextureUsage::CopyDst));
DAWN_TRY(ValidateCanUseAs(destination->texture, wgpu::TextureUsage::RenderAttachment));
DAWN_TRY(ValidateCopyTextureFormatConversion(source->texture->GetFormat().format,
destination->texture->GetFormat().format));
DAWN_INVALID_IF(options->nextInChain != nullptr, "nextInChain must be nullptr");
DAWN_TRY(ValidateAlphaOp(options->alphaOp));
return {};
}
MaybeError DoCopyTextureForBrowser(DeviceBase* device,
const ImageCopyTexture* source,
const ImageCopyTexture* destination,
const Extent3D* copySize,
const CopyTextureForBrowserOptions* options) {
// TODO(crbug.com/dawn/856): In D3D12 and Vulkan, compatible texture format can directly
// copy to each other. This can be a potential fast path.
// Noop copy
if (copySize->width == 0 || copySize->height == 0 || copySize->depthOrArrayLayers == 0) {
return {};
}
RenderPipelineBase* pipeline;
DAWN_TRY_ASSIGN(pipeline, GetOrCreateCopyTextureForBrowserPipeline(
device, destination->texture->GetFormat().format));
// Prepare bind group layout.
Ref<BindGroupLayoutBase> layout;
DAWN_TRY_ASSIGN(layout, pipeline->GetBindGroupLayout(0));
Extent3D srcTextureSize = source->texture->GetSize();
// Prepare binding 0 resource: uniform buffer.
Uniform uniformData = {
copySize->width / static_cast<float>(srcTextureSize.width),
copySize->height / static_cast<float>(srcTextureSize.height), // scale
source->origin.x / static_cast<float>(srcTextureSize.width),
source->origin.y / static_cast<float>(srcTextureSize.height), // offset
wgpu::AlphaOp::DontChange // alphaOp default value: DontChange
};
// Handle flipY. FlipY here means we flip the source texture firstly and then
// do copy. This helps on the case which source texture is flipped and the copy
// need to unpack the flip.
if (options->flipY) {
uniformData.scaleY *= -1.0;
uniformData.offsetY += copySize->height / static_cast<float>(srcTextureSize.height);
}
// Set alpha op.
uniformData.alphaOp = options->alphaOp;
Ref<BufferBase> uniformBuffer;
DAWN_TRY_ASSIGN(
uniformBuffer,
utils::CreateBufferFromData(
device, wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform, {uniformData}));
// Prepare binding 1 resource: sampler
// Use default configuration, filterMode set to Nearest for min and mag.
SamplerDescriptor samplerDesc = {};
Ref<SamplerBase> sampler;
DAWN_TRY_ASSIGN(sampler, device->CreateSampler(&samplerDesc));
// Prepare binding 2 resource: sampled texture
TextureViewDescriptor srcTextureViewDesc = {};
srcTextureViewDesc.baseMipLevel = source->mipLevel;
srcTextureViewDesc.mipLevelCount = 1;
srcTextureViewDesc.arrayLayerCount = 1;
Ref<TextureViewBase> srcTextureView;
DAWN_TRY_ASSIGN(srcTextureView,
device->CreateTextureView(source->texture, &srcTextureViewDesc));
// Create bind group after all binding entries are set.
Ref<BindGroupBase> bindGroup;
DAWN_TRY_ASSIGN(bindGroup, utils::MakeBindGroup(
device, layout,
{{0, uniformBuffer}, {1, sampler}, {2, srcTextureView}}));
// Create command encoder.
CommandEncoderDescriptor encoderDesc = {};
// TODO(dawn:723): change to not use AcquireRef for reentrant object creation.
Ref<CommandEncoder> encoder = AcquireRef(device->APICreateCommandEncoder(&encoderDesc));
// Prepare dst texture view as color Attachment.
TextureViewDescriptor dstTextureViewDesc;
dstTextureViewDesc.baseMipLevel = destination->mipLevel;
dstTextureViewDesc.mipLevelCount = 1;
dstTextureViewDesc.baseArrayLayer = destination->origin.z;
dstTextureViewDesc.arrayLayerCount = 1;
Ref<TextureViewBase> dstView;
DAWN_TRY_ASSIGN(dstView,
device->CreateTextureView(destination->texture, &dstTextureViewDesc));
// Prepare render pass color attachment descriptor.
RenderPassColorAttachment colorAttachmentDesc;
colorAttachmentDesc.view = dstView.Get();
colorAttachmentDesc.loadOp = wgpu::LoadOp::Load;
colorAttachmentDesc.storeOp = wgpu::StoreOp::Store;
colorAttachmentDesc.clearColor = {0.0, 0.0, 0.0, 1.0};
// Create render pass.
RenderPassDescriptor renderPassDesc;
renderPassDesc.colorAttachmentCount = 1;
renderPassDesc.colorAttachments = &colorAttachmentDesc;
// TODO(dawn:723): change to not use AcquireRef for reentrant object creation.
Ref<RenderPassEncoder> passEncoder =
AcquireRef(encoder->APIBeginRenderPass(&renderPassDesc));
// Start pipeline and encode commands to complete
// the copy from src texture to dst texture with transformation.
passEncoder->APISetPipeline(pipeline);
passEncoder->APISetBindGroup(0, bindGroup.Get());
passEncoder->APISetViewport(destination->origin.x, destination->origin.y, copySize->width,
copySize->height, 0.0, 1.0);
passEncoder->APIDraw(3);
passEncoder->APIEndPass();
// Finsh encoding.
// TODO(dawn:723): change to not use AcquireRef for reentrant object creation.
Ref<CommandBufferBase> commandBuffer = AcquireRef(encoder->APIFinish());
CommandBufferBase* submitCommandBuffer = commandBuffer.Get();
// Submit command buffer.
device->GetQueue()->APISubmit(1, &submitCommandBuffer);
return {};
}
} // namespace dawn_native
| 18,358
| 5,021
|
/*#include <omp.h>
#include <stdio.h>
#include <cmath>
void byRows(double** A, double* V, int n, int m, double* result) {
#pragma omp parallel for schedule(static) shared(result)
for (int i = 0; i < n; ++i) {
double sum = 0.0;
for (int j = 0; j < m; ++j) {
sum += A[i][j] * V[j];
}
result[i] = sum;
}
}
void byCols(double** A, double* V, int n, int m, double* result) {
for (int i = 0; i < n; ++i)
result[i] = 0.0;
#pragma omp parallel for schedule(static) shared(result)
for (int j = 0; j < m; ++j) {
double Vj = V[j];
for (int i = 0; i < n; ++i) {
#pragma omp atomic
result[i] += A[i][j] * Vj;
}
}
}
void byBlocks(double** A, double* V, int n, int m, double* result) {
for (int i = 0; i < n; ++i) {
result[i] = 0.0;
}
int s, q = 1, tn, k, l;
#pragma omp parallel shared(s, q, tn, k, l)
{
#pragma omp single
tn = omp_get_num_threads();
#pragma omp barrier
#pragma omp for //reduction(max: q) //It doesn't work on my version of OpenMP:( You need OpenMP 3.0 or higher to use it.
for (int i = 2; i <= (int)sqrt(tn); ++i) {
if (tn % i == 0)
//q = i //You should use this if reduction works. Otherwise use next two rows.
#pragma omp critical
q = q < i ? i : q;
}
#pragma omp single
{
if (m < n)
s = tn / q;
else {
s = q;
q = tn / s;
}
k = (n + n % s) / s;
l = (m + m % q) / q;
}
#pragma omp barrier
int num = omp_get_thread_num();
int bi = num / q;
int bj = num % q;
int bh = k;
if (bi == s - 1)
bh = n - bi * k;
int bw = l;
if (bj == q - 1)
bw = m - bj * l;
for (int i = bi * k; i < bi * k + bh; ++i) {
double sum = 0.0;
for (int j = bj * l; j < bj * l + bw; ++j) {
sum += A[i][j] * V[j];
}
#pragma omp atomic
result[i] += sum;
}
}
}
int main()
{
int n = 10000, m = 20000;
double** matrix, * vector, * vectorprod;
double time;
for (int k = 1; k < 10; ++k) {
matrix = new double* [n];
vector = new double[m];
vectorprod = new double[n];
for (int i = 0; i < n; ++i) {
matrix[i] = new double[m];
for (int j = 0; j < m; ++j) {
matrix[i][j] = 1;
}
}
for (int i = 0; i < m; ++i) {
vector[i] = 1;
}
switch (k % 3) {
case 0:
{
time = omp_get_wtime();
byRows(matrix, vector, n, m, vectorprod);
time = omp_get_wtime() - time;
}
case 1:
{
time = omp_get_wtime();
byCols(matrix, vector, n, m, vectorprod);
time = omp_get_wtime() - time;
}
case 2:
{
time = omp_get_wtime();
byBlocks(matrix, vector, n, m, vectorprod);
time = omp_get_wtime() - time;
}
}
for (int i = 0; i < n; ++i) {
delete matrix[i];
}
delete[] matrix, vector, vectorprod;
if (k % 3 == 0) printf("by rows; ");
if (k % 3 == 1) printf("by collumns; ");
if (k % 3 == 2) printf("by block; ");
printf("time is %f seconds;\n", time);
}
}
*/
| 2,824
| 1,437
|
// 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/ui/webui/options/search_engine_manager_handler.h"
#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
#include "chrome/browser/ui/search_engines/keyword_editor_controller.h"
#include "chrome/browser/ui/search_engines/template_url_table_model.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/locale_settings.h"
#include "components/search_engines/template_url.h"
#include "components/search_engines/template_url_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_ui.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
enum EngineInfoIndexes {
ENGINE_NAME,
ENGINE_KEYWORD,
ENGINE_URL,
};
}; // namespace
namespace options {
SearchEngineManagerHandler::SearchEngineManagerHandler() {
}
SearchEngineManagerHandler::~SearchEngineManagerHandler() {
if (list_controller_.get() && list_controller_->table_model())
list_controller_->table_model()->SetObserver(NULL);
}
void SearchEngineManagerHandler::InitializeHandler() {
list_controller_.reset(
new KeywordEditorController(Profile::FromWebUI(web_ui())));
DCHECK(list_controller_.get());
list_controller_->table_model()->SetObserver(this);
}
void SearchEngineManagerHandler::InitializePage() {
OnModelChanged();
}
void SearchEngineManagerHandler::GetLocalizedValues(
base::DictionaryValue* localized_strings) {
DCHECK(localized_strings);
RegisterTitle(localized_strings, "searchEngineManagerPage",
IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE);
localized_strings->SetString("defaultSearchEngineListTitle",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAIN_SEPARATOR));
localized_strings->SetString("otherSearchEngineListTitle",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_OTHER_SEPARATOR));
localized_strings->SetString("extensionKeywordsListTitle",
l10n_util::GetStringUTF16(
IDS_SEARCH_ENGINES_EDITOR_EXTENSIONS_SEPARATOR));
localized_strings->SetString("makeDefaultSearchEngineButton",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));
localized_strings->SetString("searchEngineTableNamePlaceholder",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_NAME_PLACEHOLDER));
localized_strings->SetString("searchEngineTableKeywordPlaceholder",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_KEYWORD_PLACEHOLDER));
localized_strings->SetString("searchEngineTableURLPlaceholder",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_URL_PLACEHOLDER));
localized_strings->SetString("editSearchEngineInvalidTitleToolTip",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_TITLE_TT));
localized_strings->SetString("editSearchEngineInvalidKeywordToolTip",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT));
localized_strings->SetString("editSearchEngineInvalidURLToolTip",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_URL_TT));
}
void SearchEngineManagerHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"managerSetDefaultSearchEngine",
base::Bind(&SearchEngineManagerHandler::SetDefaultSearchEngine,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"removeSearchEngine",
base::Bind(&SearchEngineManagerHandler::RemoveSearchEngine,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"editSearchEngine",
base::Bind(&SearchEngineManagerHandler::EditSearchEngine,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"checkSearchEngineInfoValidity",
base::Bind(&SearchEngineManagerHandler::CheckSearchEngineInfoValidity,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"searchEngineEditCancelled",
base::Bind(&SearchEngineManagerHandler::EditCancelled,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"searchEngineEditCompleted",
base::Bind(&SearchEngineManagerHandler::EditCompleted,
base::Unretained(this)));
}
void SearchEngineManagerHandler::OnModelChanged() {
DCHECK(list_controller_.get());
if (!list_controller_->loaded())
return;
// Find the default engine.
const TemplateURL* default_engine =
list_controller_->GetDefaultSearchProvider();
int default_index = list_controller_->table_model()->IndexOfTemplateURL(
default_engine);
// Build the first list (default search engine options).
base::ListValue defaults_list;
int last_default_engine_index =
list_controller_->table_model()->last_search_engine_index();
for (int i = 0; i < last_default_engine_index; ++i) {
// Third argument is false, as the engine is not from an extension.
defaults_list.Append(CreateDictionaryForEngine(
i, i == default_index));
}
// Build the second list (other search templates).
base::ListValue others_list;
int last_other_engine_index =
list_controller_->table_model()->last_other_engine_index();
if (last_default_engine_index < 0)
last_default_engine_index = 0;
for (int i = last_default_engine_index; i < last_other_engine_index; ++i) {
others_list.Append(CreateDictionaryForEngine(i, i == default_index));
}
// Build the extension keywords list.
base::ListValue keyword_list;
if (last_other_engine_index < 0)
last_other_engine_index = 0;
int engine_count = list_controller_->table_model()->RowCount();
for (int i = last_other_engine_index; i < engine_count; ++i) {
keyword_list.Append(CreateDictionaryForEngine(i, i == default_index));
}
web_ui()->CallJavascriptFunctionUnsafe(
"SearchEngineManager.updateSearchEngineList", defaults_list, others_list,
keyword_list);
}
void SearchEngineManagerHandler::OnItemsChanged(int start, int length) {
OnModelChanged();
}
void SearchEngineManagerHandler::OnItemsAdded(int start, int length) {
OnModelChanged();
}
void SearchEngineManagerHandler::OnItemsRemoved(int start, int length) {
OnModelChanged();
}
std::unique_ptr<base::DictionaryValue>
SearchEngineManagerHandler::CreateDictionaryForEngine(int index,
bool is_default) {
TemplateURLTableModel* table_model = list_controller_->table_model();
const TemplateURL* template_url = list_controller_->GetTemplateURL(index);
// The items which are to be written into |dict| are also described in
// chrome/browser/resources/options/search_engine_manager_engine_list.js
// in @typedef for SearchEngine. Please update it whenever you add or remove
// any keys here.
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetString("name", template_url->short_name());
dict->SetString("displayName", table_model->GetText(
index, IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN));
dict->SetString("keyword", table_model->GetText(
index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN));
dict->SetString("url", template_url->url_ref().DisplayURL(
UIThreadSearchTermsData(Profile::FromWebUI(web_ui()))));
dict->SetBoolean("urlLocked", template_url->prepopulate_id() > 0);
GURL icon_url = template_url->favicon_url();
if (icon_url.is_valid())
dict->SetString("iconURL", icon_url.spec());
dict->SetString("modelIndex", base::IntToString(index));
dict->SetBoolean("canBeRemoved",
list_controller_->CanRemove(template_url));
dict->SetBoolean("canBeDefault",
list_controller_->CanMakeDefault(template_url));
dict->SetBoolean("default", is_default);
dict->SetBoolean("canBeEdited", list_controller_->CanEdit(template_url));
TemplateURL::Type type = template_url->GetType();
dict->SetBoolean("isOmniboxExtension",
type == TemplateURL::OMNIBOX_API_EXTENSION);
if (type == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION ||
type == TemplateURL::OMNIBOX_API_EXTENSION) {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
->GetExtensionById(template_url->GetExtensionId(),
extensions::ExtensionRegistry::EVERYTHING);
if (extension) {
dict->Set("extension",
extensions::util::GetExtensionInfo(extension).release());
}
}
return dict;
}
void SearchEngineManagerHandler::SetDefaultSearchEngine(
const base::ListValue* args) {
int index;
if (!ExtractIntegerValue(args, &index)) {
NOTREACHED();
return;
}
if (index < 0 || index >= list_controller_->table_model()->RowCount())
return;
list_controller_->MakeDefaultTemplateURL(index);
content::RecordAction(
base::UserMetricsAction("Options_SearchEngineSetDefault"));
}
void SearchEngineManagerHandler::RemoveSearchEngine(
const base::ListValue* args) {
int index;
if (!ExtractIntegerValue(args, &index)) {
NOTREACHED();
return;
}
if (index < 0 || index >= list_controller_->table_model()->RowCount())
return;
if (list_controller_->CanRemove(list_controller_->GetTemplateURL(index))) {
list_controller_->RemoveTemplateURL(index);
content::RecordAction(
base::UserMetricsAction("Options_SearchEngineRemoved"));
}
}
void SearchEngineManagerHandler::EditSearchEngine(const base::ListValue* args) {
int index;
if (!ExtractIntegerValue(args, &index)) {
NOTREACHED();
return;
}
// Allow -1, which means we are adding a new engine.
if (index < -1 || index >= list_controller_->table_model()->RowCount())
return;
edit_controller_.reset(new EditSearchEngineController(
(index == -1) ? NULL : list_controller_->GetTemplateURL(index), this,
Profile::FromWebUI(web_ui())));
}
void SearchEngineManagerHandler::OnEditedKeyword(
TemplateURL* template_url,
const base::string16& title,
const base::string16& keyword,
const std::string& url) {
DCHECK(!url.empty());
if (template_url)
list_controller_->ModifyTemplateURL(template_url, title, keyword, url);
else
list_controller_->AddTemplateURL(title, keyword, url);
edit_controller_.reset();
}
void SearchEngineManagerHandler::CheckSearchEngineInfoValidity(
const base::ListValue* args) {
if (!edit_controller_.get())
return;
base::string16 name;
base::string16 keyword;
std::string url;
std::string modelIndex;
if (!args->GetString(ENGINE_NAME, &name) ||
!args->GetString(ENGINE_KEYWORD, &keyword) ||
!args->GetString(ENGINE_URL, &url) ||
!args->GetString(3, &modelIndex)) {
NOTREACHED();
return;
}
base::DictionaryValue validity;
validity.SetBoolean("name", edit_controller_->IsTitleValid(name));
validity.SetBoolean("keyword", edit_controller_->IsKeywordValid(keyword));
validity.SetBoolean("url", edit_controller_->IsURLValid(url));
base::StringValue indexValue(modelIndex);
web_ui()->CallJavascriptFunctionUnsafe(
"SearchEngineManager.validityCheckCallback", validity, indexValue);
}
void SearchEngineManagerHandler::EditCancelled(const base::ListValue* args) {
if (!edit_controller_.get())
return;
edit_controller_->CleanUpCancelledAdd();
edit_controller_.reset();
}
void SearchEngineManagerHandler::EditCompleted(const base::ListValue* args) {
if (!edit_controller_.get())
return;
base::string16 name;
base::string16 keyword;
std::string url;
if (!args->GetString(ENGINE_NAME, &name) ||
!args->GetString(ENGINE_KEYWORD, &keyword) ||
!args->GetString(ENGINE_URL, &url)) {
NOTREACHED();
return;
}
// Recheck validity. It's possible to get here with invalid input if e.g. the
// user calls the right JS functions directly from the web inspector.
if (edit_controller_->IsTitleValid(name) &&
edit_controller_->IsKeywordValid(keyword) &&
edit_controller_->IsURLValid(url))
edit_controller_->AcceptAddOrEdit(name, keyword, url);
}
} // namespace options
| 12,533
| 3,936
|