text
stringlengths 54
60.6k
|
---|
<commit_before>//===- FxpMathConfig.cpp - Reference fixed point config -------------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
//
// This file defines a TargetConfiguration for reference fixed-point math
// quantization scheme based on the FxpMathOps (plus a small category of
// extension ops that can be added from other dialects).
//
//===----------------------------------------------------------------------===//
#include "mlir/Quantizer/Configurations/FxpMathConfig.h"
#include "mlir/Dialect/FxpMathOps/FxpMathOps.h"
#include "mlir/Dialect/QuantOps/QuantOps.h"
#include "mlir/Dialect/QuantOps/QuantTypes.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Quantizer/Support/ConstraintAnalysisGraph.h"
#include "mlir/Quantizer/Support/Metadata.h"
#include "mlir/Quantizer/Support/Statistics.h"
#include "mlir/Quantizer/Support/UniformConstraints.h"
#include "mlir/StandardOps/Ops.h"
using namespace mlir;
using namespace mlir::quantizer;
using namespace mlir::fxpmath;
using namespace mlir::quant;
using namespace std::placeholders;
namespace {
struct FxpMathTargetConfigImpl : public FxpMathTargetConfig {
FxpMathTargetConfigImpl(SolverContext &context)
: FxpMathTargetConfig(context) {
Builder b(&context.getMlirContext());
IntegerType i8Type = b.getIntegerType(8);
IntegerType i16Type = b.getIntegerType(16);
IntegerType i32Type = b.getIntegerType(32);
q8 = addCandidateType(
AnyQuantizedType::get(QuantizationFlags::Signed, i8Type, nullptr,
std::numeric_limits<int8_t>::min(),
std::numeric_limits<int8_t>::max()),
CandidateQuantizedType::Scheme::UniformPerLayer);
q16 = addCandidateType(
AnyQuantizedType::get(QuantizationFlags::Signed, i16Type, nullptr,
std::numeric_limits<int16_t>::min(),
std::numeric_limits<int16_t>::max()),
CandidateQuantizedType::Scheme::UniformPerLayer);
q32ExplicitFixedPoint = addCandidateType(
AnyQuantizedType::get(QuantizationFlags::Signed, i32Type, nullptr,
std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::max()),
CandidateQuantizedType::Scheme::UniformExplicitFixedPointScale);
// Op handlers.
addOpHandler<ConstantOp>(
std::bind(&FxpMathTargetConfigImpl::handleConstant, this, _1, _2));
addOpHandler<ReturnOp>(
std::bind(&FxpMathTargetConfigImpl::handleTerminal, this, _1, _2));
addOpHandler<quant::StatisticsOp>(
std::bind(&FxpMathTargetConfigImpl::handleStats, this, _1, _2));
// FxpMathOps.
addOpHandler<RealAddEwOp>(
std::bind(&FxpMathTargetConfigImpl::handleAdd, this, _1, _2));
addOpHandler<RealMulEwOp>(
std::bind(&FxpMathTargetConfigImpl::handleMul, this, _1, _2));
addOpHandler<RealMatMulOp>(
std::bind(&FxpMathTargetConfigImpl::handleMatMul, this, _1, _2));
addOpHandler<RealMatMulBiasOp>(
std::bind(&FxpMathTargetConfigImpl::handleMatMulBias, this, _1, _2));
// Require stats ops.
addRequireStatsOp<RealAddEwOp>();
addRequireStatsOp<RealSubEwOp>();
addRequireStatsOp<RealDivEwOp>();
addRequireStatsOp<RealMulEwOp>();
addRequireStatsOp<RealMatMulOp>();
addRequireStatsOp<RealMatMulBiasOp>();
}
bool isHandledType(Type t) const final {
if (t.isa<FloatType>())
return true;
auto shapedType = t.dyn_cast<ShapedType>();
return (shapedType && shapedType.getElementType().isa<FloatType>() &&
(t.isa<VectorType>() || t.isa<TensorType>()));
}
void finalizeAnchors(CAGSlice &cag) const override {
cag.enumerateImpliedConnections(
[&](CAGAnchorNode *from, CAGAnchorNode *to) {
UniformConstraintsBuilder(cag).coupleAnchors(from, to);
});
}
void addValueIdentityOpByName(StringRef opName) override {
addOpHandlerByName(
opName,
std::bind(&FxpMathTargetConfigImpl::handleValueIdentity, this, _1, _2));
}
void handleValueIdentity(Operation *op, CAGSlice &cag) const {
assert(op->getNumResults() == 1);
if (!isHandledType(op->getResult(0)->getType()))
return;
auto resultNode = cag.getResultAnchor(op, 0);
resultNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::DirectStorage);
for (unsigned opIdx = 0, e = op->getNumOperands(); opIdx < e; ++opIdx) {
if (!isHandledType(op->getOperand(opIdx)->getType()))
continue;
auto operandNode = cag.getOperandAnchor(op, opIdx);
operandNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::DirectStorage);
UniformConstraintsBuilder(cag).coupleAnchors(operandNode, resultNode);
}
}
void handleConstant(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto resultNode = cag.getResultAnchor(op, 0);
resultNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::ExpressedOnly);
Attribute valueAttr;
if (!matchPattern(op, m_Constant(&valueAttr))) {
return;
}
AttributeTensorStatistics stats(valueAttr);
TensorAxisStatistics layerStats;
if (!stats.get(layerStats)) {
op->emitOpError("could not compute statistics");
return;
}
UniformConstraintsBuilder(cag).applyStats(resultNode, layerStats);
}
void handleTerminal(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getOperand(0)->getType()))
return;
auto operandNode = cag.getOperandAnchor(op, 0);
operandNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::ExpressedOnly);
}
void handleStats(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto argNode = cag.getOperandAnchor(op, 0);
auto resultNode = cag.getResultAnchor(op, 0);
UniformConstraintsBuilder(cag).coupleAnchors(argNode, resultNode);
TensorAxisStatistics layerStats;
auto statsOp = cast<quant::StatisticsOp>(op);
auto layerStatsAttr = statsOp.layerStats();
layerStats.minValue =
layerStatsAttr.getValue({0}).cast<FloatAttr>().getValueAsDouble();
layerStats.maxValue =
layerStatsAttr.getValue({1}).cast<FloatAttr>().getValueAsDouble();
UniformConstraintsBuilder(cag).applyStats(resultNode,
std::move(layerStats));
}
void handleAdd(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto resultNode = cag.getResultAnchor(op, 0);
// Add supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
// NOTE: We couple the add such that the scale/zeroPoint match between
// both args and the result. This is overly constrained in that it is
// possible to write efficient add kernels with a bit more freedom (i.e.
// zeroPoints can vary, scales can differ by a power of two, etc).
// However, fully coupled yields the simples solutions on the fast path.
// Further efficiency can be had by constraining the zeroPoint to 0, but
// there isn't a constraint for this yet (and there are tradeoffs).
UniformConstraintsBuilder(cag).coupleAnchors(lhs, resultNode);
UniformConstraintsBuilder(cag).coupleAnchors(rhs, resultNode);
addRealMathOptionalConstraints(op, resultNode, cag);
}
void handleMul(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto resultNode = cag.getResultAnchor(op, 0);
// Mul supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
addRealMathOptionalConstraints(op, resultNode, cag);
}
void handleMatMul(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto resultNode = cag.getResultAnchor(op, 0);
// Mul supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
addRealMathOptionalConstraints(op, resultNode, cag);
}
void handleMatMulBias(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto bias = cag.getOperandAnchor(op, 2);
bias->getUniformMetadata().disabledCandidateTypes =
getCandidateTypeDisabledExceptMask({q32ExplicitFixedPoint});
auto resultNode = cag.getResultAnchor(op, 0);
UniformConstraintsBuilder(cag).propagateExplicitScale(resultNode, bias);
// Mul supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
addRealMathOptionalConstraints(op, resultNode, cag);
}
void addRealMathOptionalConstraints(Operation *op, CAGAnchorNode *anchor,
CAGSlice &cag) const {
// TODO: It would be nice if these all extended some base trait instead
// of requiring name lookup.
auto clampMinAttr = op->getAttrOfType<FloatAttr>("clamp_min");
auto clampMaxAttr = op->getAttrOfType<FloatAttr>("clamp_max");
if (clampMinAttr || clampMaxAttr) {
auto nan = APFloat::getQNaN(APFloat::IEEEdouble());
auto clampMin = clampMinAttr ? clampMinAttr.getValue() : nan;
auto clampMax = clampMaxAttr ? clampMaxAttr.getValue() : nan;
UniformConstraintsBuilder(cag).clamp(anchor, clampMin, clampMax);
}
}
unsigned q8;
unsigned q16;
unsigned q32ExplicitFixedPoint;
};
} // anonymous namespace
std::unique_ptr<FxpMathTargetConfig>
FxpMathTargetConfig::create(SolverContext &context) {
return llvm::make_unique<FxpMathTargetConfigImpl>(context);
}
<commit_msg> Avoid dyn_cast to ShapedType<commit_after>//===- FxpMathConfig.cpp - Reference fixed point config -------------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
//
// This file defines a TargetConfiguration for reference fixed-point math
// quantization scheme based on the FxpMathOps (plus a small category of
// extension ops that can be added from other dialects).
//
//===----------------------------------------------------------------------===//
#include "mlir/Quantizer/Configurations/FxpMathConfig.h"
#include "mlir/Dialect/FxpMathOps/FxpMathOps.h"
#include "mlir/Dialect/QuantOps/QuantOps.h"
#include "mlir/Dialect/QuantOps/QuantTypes.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Quantizer/Support/ConstraintAnalysisGraph.h"
#include "mlir/Quantizer/Support/Metadata.h"
#include "mlir/Quantizer/Support/Statistics.h"
#include "mlir/Quantizer/Support/UniformConstraints.h"
#include "mlir/StandardOps/Ops.h"
using namespace mlir;
using namespace mlir::quantizer;
using namespace mlir::fxpmath;
using namespace mlir::quant;
using namespace std::placeholders;
namespace {
struct FxpMathTargetConfigImpl : public FxpMathTargetConfig {
FxpMathTargetConfigImpl(SolverContext &context)
: FxpMathTargetConfig(context) {
Builder b(&context.getMlirContext());
IntegerType i8Type = b.getIntegerType(8);
IntegerType i16Type = b.getIntegerType(16);
IntegerType i32Type = b.getIntegerType(32);
q8 = addCandidateType(
AnyQuantizedType::get(QuantizationFlags::Signed, i8Type, nullptr,
std::numeric_limits<int8_t>::min(),
std::numeric_limits<int8_t>::max()),
CandidateQuantizedType::Scheme::UniformPerLayer);
q16 = addCandidateType(
AnyQuantizedType::get(QuantizationFlags::Signed, i16Type, nullptr,
std::numeric_limits<int16_t>::min(),
std::numeric_limits<int16_t>::max()),
CandidateQuantizedType::Scheme::UniformPerLayer);
q32ExplicitFixedPoint = addCandidateType(
AnyQuantizedType::get(QuantizationFlags::Signed, i32Type, nullptr,
std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::max()),
CandidateQuantizedType::Scheme::UniformExplicitFixedPointScale);
// Op handlers.
addOpHandler<ConstantOp>(
std::bind(&FxpMathTargetConfigImpl::handleConstant, this, _1, _2));
addOpHandler<ReturnOp>(
std::bind(&FxpMathTargetConfigImpl::handleTerminal, this, _1, _2));
addOpHandler<quant::StatisticsOp>(
std::bind(&FxpMathTargetConfigImpl::handleStats, this, _1, _2));
// FxpMathOps.
addOpHandler<RealAddEwOp>(
std::bind(&FxpMathTargetConfigImpl::handleAdd, this, _1, _2));
addOpHandler<RealMulEwOp>(
std::bind(&FxpMathTargetConfigImpl::handleMul, this, _1, _2));
addOpHandler<RealMatMulOp>(
std::bind(&FxpMathTargetConfigImpl::handleMatMul, this, _1, _2));
addOpHandler<RealMatMulBiasOp>(
std::bind(&FxpMathTargetConfigImpl::handleMatMulBias, this, _1, _2));
// Require stats ops.
addRequireStatsOp<RealAddEwOp>();
addRequireStatsOp<RealSubEwOp>();
addRequireStatsOp<RealDivEwOp>();
addRequireStatsOp<RealMulEwOp>();
addRequireStatsOp<RealMatMulOp>();
addRequireStatsOp<RealMatMulBiasOp>();
}
bool isHandledType(Type t) const final {
if (t.isa<FloatType>())
return true;
return (t.isa<VectorType>() || t.isa<TensorType>()) &&
t.cast<ShapedType>().getElementType().isa<FloatType>();
}
void finalizeAnchors(CAGSlice &cag) const override {
cag.enumerateImpliedConnections(
[&](CAGAnchorNode *from, CAGAnchorNode *to) {
UniformConstraintsBuilder(cag).coupleAnchors(from, to);
});
}
void addValueIdentityOpByName(StringRef opName) override {
addOpHandlerByName(
opName,
std::bind(&FxpMathTargetConfigImpl::handleValueIdentity, this, _1, _2));
}
void handleValueIdentity(Operation *op, CAGSlice &cag) const {
assert(op->getNumResults() == 1);
if (!isHandledType(op->getResult(0)->getType()))
return;
auto resultNode = cag.getResultAnchor(op, 0);
resultNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::DirectStorage);
for (unsigned opIdx = 0, e = op->getNumOperands(); opIdx < e; ++opIdx) {
if (!isHandledType(op->getOperand(opIdx)->getType()))
continue;
auto operandNode = cag.getOperandAnchor(op, opIdx);
operandNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::DirectStorage);
UniformConstraintsBuilder(cag).coupleAnchors(operandNode, resultNode);
}
}
void handleConstant(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto resultNode = cag.getResultAnchor(op, 0);
resultNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::ExpressedOnly);
Attribute valueAttr;
if (!matchPattern(op, m_Constant(&valueAttr))) {
return;
}
AttributeTensorStatistics stats(valueAttr);
TensorAxisStatistics layerStats;
if (!stats.get(layerStats)) {
op->emitOpError("could not compute statistics");
return;
}
UniformConstraintsBuilder(cag).applyStats(resultNode, layerStats);
}
void handleTerminal(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getOperand(0)->getType()))
return;
auto operandNode = cag.getOperandAnchor(op, 0);
operandNode->setTypeTransformRule(
CAGAnchorNode::TypeTransformRule::ExpressedOnly);
}
void handleStats(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto argNode = cag.getOperandAnchor(op, 0);
auto resultNode = cag.getResultAnchor(op, 0);
UniformConstraintsBuilder(cag).coupleAnchors(argNode, resultNode);
TensorAxisStatistics layerStats;
auto statsOp = cast<quant::StatisticsOp>(op);
auto layerStatsAttr = statsOp.layerStats();
layerStats.minValue =
layerStatsAttr.getValue({0}).cast<FloatAttr>().getValueAsDouble();
layerStats.maxValue =
layerStatsAttr.getValue({1}).cast<FloatAttr>().getValueAsDouble();
UniformConstraintsBuilder(cag).applyStats(resultNode,
std::move(layerStats));
}
void handleAdd(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto resultNode = cag.getResultAnchor(op, 0);
// Add supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
// NOTE: We couple the add such that the scale/zeroPoint match between
// both args and the result. This is overly constrained in that it is
// possible to write efficient add kernels with a bit more freedom (i.e.
// zeroPoints can vary, scales can differ by a power of two, etc).
// However, fully coupled yields the simples solutions on the fast path.
// Further efficiency can be had by constraining the zeroPoint to 0, but
// there isn't a constraint for this yet (and there are tradeoffs).
UniformConstraintsBuilder(cag).coupleAnchors(lhs, resultNode);
UniformConstraintsBuilder(cag).coupleAnchors(rhs, resultNode);
addRealMathOptionalConstraints(op, resultNode, cag);
}
void handleMul(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto resultNode = cag.getResultAnchor(op, 0);
// Mul supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
addRealMathOptionalConstraints(op, resultNode, cag);
}
void handleMatMul(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto resultNode = cag.getResultAnchor(op, 0);
// Mul supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
addRealMathOptionalConstraints(op, resultNode, cag);
}
void handleMatMulBias(Operation *op, CAGSlice &cag) const {
if (!isHandledType(op->getResult(0)->getType()))
return;
auto lhs = cag.getOperandAnchor(op, 0);
auto rhs = cag.getOperandAnchor(op, 1);
auto bias = cag.getOperandAnchor(op, 2);
bias->getUniformMetadata().disabledCandidateTypes =
getCandidateTypeDisabledExceptMask({q32ExplicitFixedPoint});
auto resultNode = cag.getResultAnchor(op, 0);
UniformConstraintsBuilder(cag).propagateExplicitScale(resultNode, bias);
// Mul supports 8/16 bit math.
llvm::SmallBitVector disableMask =
getCandidateTypeDisabledExceptMask({q8, q16});
lhs->getUniformMetadata().disabledCandidateTypes = disableMask;
rhs->getUniformMetadata().disabledCandidateTypes = disableMask;
resultNode->getUniformMetadata().disabledCandidateTypes = disableMask;
addRealMathOptionalConstraints(op, resultNode, cag);
}
void addRealMathOptionalConstraints(Operation *op, CAGAnchorNode *anchor,
CAGSlice &cag) const {
// TODO: It would be nice if these all extended some base trait instead
// of requiring name lookup.
auto clampMinAttr = op->getAttrOfType<FloatAttr>("clamp_min");
auto clampMaxAttr = op->getAttrOfType<FloatAttr>("clamp_max");
if (clampMinAttr || clampMaxAttr) {
auto nan = APFloat::getQNaN(APFloat::IEEEdouble());
auto clampMin = clampMinAttr ? clampMinAttr.getValue() : nan;
auto clampMax = clampMaxAttr ? clampMaxAttr.getValue() : nan;
UniformConstraintsBuilder(cag).clamp(anchor, clampMin, clampMax);
}
}
unsigned q8;
unsigned q16;
unsigned q32ExplicitFixedPoint;
};
} // anonymous namespace
std::unique_ptr<FxpMathTargetConfig>
FxpMathTargetConfig::create(SolverContext &context) {
return llvm::make_unique<FxpMathTargetConfigImpl>(context);
}
<|endoftext|> |
<commit_before><commit_msg>vcl: Use glScissor for rectangular clip regions<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: soicon.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ssa $ $Date: 2001-04-27 15:29:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_SOICON_HXX
#define _SV_SOICON_HXX
// base name of a custom icon function (must be declared extern "C")
// the iconid must be directly appended, eg: vcl_customIcon100
#define VCL_CUSTOM_ICON_BASE "vcl_customIcon"
// type of the custom icon function
typedef void VCL_CUSTOM_ICON_FN( char **&, char **&, char **&, char **&);
class SalDisplay;
class SalBitmap;
class Bitmap;
BOOL SelectAppIconPixmap( SalDisplay *pDisplay, USHORT nIcon, USHORT iconSize,
Pixmap& icon_pixmap, Pixmap& icon_mask );
BOOL ReadXPMFile( Display*, const String&, SalBitmap*&, SalBitmap*& );
BOOL ReadXBMFile( Display*, const String&, SalBitmap*& );
#endif
<commit_msg>INTEGRATION: CWS wmicons (1.2.772); FILE MERGED 2005/02/24 14:14:01 obr 1.2.772.1: #i37167# window manager icons now loaded from resource<commit_after>/*************************************************************************
*
* $RCSfile: soicon.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-03-03 19:57:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_SOICON_HXX
#define _SV_SOICON_HXX
class SalDisplay;
class SalBitmap;
class Bitmap;
BOOL SelectAppIconPixmap( SalDisplay *pDisplay, USHORT nIcon, USHORT iconSize,
Pixmap& icon_pixmap, Pixmap& icon_mask );
#endif
<|endoftext|> |
<commit_before>#ifndef __BH_VE_CPU_SPECIALIZER
#define __BH_VE_CPU_SPECIALIZER
#include <ctemplate/template.h>
static ctemplate::Strip strip_mode = ctemplate::STRIP_BLANK_LINES;
void specializer_init()
{
ctemplate::mutable_default_template_cache()->SetTemplateRootDirectory(template_path);
ctemplate::LoadTemplate("ewise.cont.nd.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.1d.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.2d.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.3d.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.nd.tpl", strip_mode);
ctemplate::LoadTemplate("kernel.tpl", strip_mode);
ctemplate::LoadTemplate("license.tpl", strip_mode);
ctemplate::LoadTemplate("random.cont.1d.tpl", strip_mode);
ctemplate::LoadTemplate("range.cont.1d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.1d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.2d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.3d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.nd.tpl", strip_mode);
ctemplate::LoadTemplate("scan.strided.1d.tpl", strip_mode);
ctemplate::LoadTemplate("scan.strided.nd.tpl", strip_mode);
ctemplate::mutable_default_template_cache()->Freeze();
}
/**
* Choose the template.
*
* Contract: Do not call this for system or extension operations.
*/
string template_filename(block_t& block, int pc, bh_intp optimized)
{
string tpl_ndim = "nd.",
tpl_opcode,
tpl_layout = "strided.";
tac_t* tac = &block.program[pc];
int ndim = (tac->op == REDUCE) ? \
block.scope[tac->in1].ndim : \
block.scope[tac->out].ndim;
int lmask = block.lmask[pc];
switch (tac->op) { // OPCODE_SWITCH
case MAP:
tpl_opcode = "ewise.";
if ((optimized) && ((lmask == LMASK_CC) || \
(lmask == LMASK_CK))) {
tpl_layout = "cont.";
} else if ((optimized) && (ndim == 1)) {
tpl_ndim = "1d.";
} else if ((optimized) && (ndim == 2)) {
tpl_ndim = "2d.";
} else if ((optimized) && (ndim == 3)) {
tpl_ndim = "3d.";
}
break;
case ZIP:
tpl_opcode = "ewise.";
if ((optimized) && (
(lmask == LMASK_CCC) || (lmask == LMASK_CKC) || (lmask == LMASK_CCK)
)) {
tpl_layout = "cont.";
} else if ((optimized) && (ndim == 1)) {
tpl_ndim = "1d.";
} else if ((optimized) && (ndim == 2)) {
tpl_ndim = "2d.";
} else if ((optimized) && (ndim == 3)) {
tpl_ndim = "3d.";
}
break;
case SCAN:
tpl_opcode = "scan.";
if (optimized && (ndim == 1)) {
tpl_ndim = "1d.";
}
break;
case REDUCE:
tpl_opcode = "reduce.";
if (optimized && (ndim == 1)) {
tpl_ndim = "1d.";
} else if (optimized && (ndim == 2)) {
tpl_ndim = "2d.";
} else if (optimized && (ndim == 3)) {
tpl_ndim = "3d.";
}
break;
case GENERATE:
switch(tac->oper) {
case RANDOM:
tpl_opcode = "random.";
break;
case RANGE:
tpl_opcode = "range.";
default:
printf("Operator x is not supported with operation y\n");
}
tpl_layout = "cont.";
break;
default:
printf("template_filename: Err=[Unsupported operation %d.]\n", tac->oper);
throw runtime_error("template_filename: No template for opcode.");
}
return tpl_opcode + tpl_layout + tpl_ndim + "tpl";
}
/**
* Construct the c-sourcecode for the given block.
*
* NOTE: System opcodes are ignored.
*
* @param optimized The level of optimizations to apply to the generated code.
* @param block The block to generate sourcecode for.
* @return The generated sourcecode.
*
*/
string specialize(block_t& block, bh_intp const optimized) {
string sourcecode = "";
ctemplate::TemplateDictionary kernel_d("KERNEL"); // Kernel - function wrapping code
kernel_d.SetValue("SYMBOL", block.symbol);
for(int j=0; j<block.ninstr; ++j) {
//
// Grab the tacuction for which to generate sourcecode
tac_t *tac = &block.program[j];
//
// Skip code generation for system and extensions
if ((tac->op == SYSTEM) || (tac->op == EXTENSION)) {
continue;
}
//
// The operation (ewise, reduction, scan, random, range).
ctemplate::TemplateDictionary* operation_d = kernel_d.AddIncludeDictionary("OPERATIONS");
string tf = template_filename(
block,
j,
optimized
);
operation_d->SetFilename(tf);
//
// The operator +, -, /, min, max, sin, sqrt, etc...
//
ctemplate::TemplateDictionary* operator_d = operation_d->AddSectionDictionary("OPERATORS");
operator_d->SetValue("OPERATOR", operator_cexpr(tac->op, tac->oper, block.scope[tac->out].type));
//
// Reduction and scan specific expansions
// TODO: fix for multiple tacuctions
if ((tac->op == REDUCE) || (tac->op == SCAN)) {
operation_d->SetValue("TYPE_OUTPUT", enum_to_ctypestr(block.scope[tac->out].type));
operation_d->SetValue("TYPE_INPUT", enum_to_ctypestr(block.scope[tac->in1].type));
operation_d->SetValue("TYPE_AXIS", "int64_t");
if (tac->oper == ADD) {
operation_d->SetValue("NEUTRAL_ELEMENT", std::to_string(0));
} else if (tac->oper == MULTIPLY) {
operation_d->SetValue("NEUTRAL_ELEMENT", std::to_string(1));
}
}
operation_d->SetValue("NR_OUTPUT", std::to_string(tac->out));
operation_d->SetValue("NR_FINPUT", std::to_string(tac->in1)); // Not all have
operation_d->SetValue("NR_SINPUT", std::to_string(tac->in2)); // Not all have
//
// Fill out the tacuction operands globally such that they
// are available to both for the kernel argument unpacking, the operations and the operators.
//
// TODO: this should actually distinguish between the total set of operands
// and those used for a single tacuction depending on the amount of loops that can be
// fused
//
int nops_tac = noperands(tac);
for(int i=0; i<nops_tac; ++i) { // Operand dict
ctemplate::TemplateDictionary* argument_d = kernel_d.AddSectionDictionary("ARGUMENT");
ctemplate::TemplateDictionary* operand_d = operation_d->AddSectionDictionary("OPERAND");
argument_d->SetValue("TYPE", enum_to_ctypestr(block.scope[tac->out].type));
argument_d->SetIntValue("NR", tac->out);
operand_d->SetValue("TYPE", enum_to_ctypestr(block.scope[tac->out].type));
operand_d->SetIntValue("NR", tac->out);
if (block.scope[tac->out].layout != CONSTANT) {
argument_d->ShowSection("ARRAY");
operand_d->ShowSection("ARRAY");
}
}
}
//
// Fill out the template and return the generated sourcecode
//
ctemplate::ExpandTemplate(
"kernel.tpl",
strip_mode,
&kernel_d,
&sourcecode
);
return sourcecode;
}
/**
* Create a symbol for the kernel.
*
* NOTE: System and extension opcodes are ignored.
* If a kernel consists of nothing but system and/or extension
* opcodes then the symbol will be the empty string "".
*/
bool symbolize(bh_kernel_t &kernel, bh_intp const optimized) {
std::string symbol_opcode,
symbol_lmask,
symbol_tsig,
symbol_ndim;
kernel.symbol = "";
for (int i=0; i<kernel.ninstr; ++i) {
tac_t* tac = &kernel.program[i];
// Do not include system opcodes in the kernel symbol.
if ((tac->op == SYSTEM) || (tac->op == EXTENSION)) {
continue;
}
symbol_opcode += std::string(bh_opcode_to_cstr_short(tac->op));
symbol_tsig += std::string(bh_typesig_to_shorthand(kernel.tsig[i]));
symbol_lmask += std::string(bh_layoutmask_to_shorthand(kernel.lmask[i]));
int ndim = kernel.scope[tac->out].ndim;
if (tac->op == REDUCE) {
ndim = kernel.scope[tac->in1].ndim;
}
if (optimized && (ndim <= 3)) { // Optimized
symbol_ndim += std::to_string(ndim);
} else {
symbol_ndim += std::string("N");
}
symbol_ndim += "D";
kernel.tsig[i] = tsig;
kernel.lmask[i] = lmask;
}
if (kernel.omask == (HAS_ARRAY_OP)) {
kernel.symbol = "BH_" + \
symbol_opcode + "_" +\
symbol_tsig + "_" +\
symbol_lmask + "_" +\
symbol_ndim;
}
return true;
}
#endif
<commit_msg>cpu: Kernels are now "blocks" until they are codegenerated...<commit_after>#ifndef __BH_VE_CPU_SPECIALIZER
#define __BH_VE_CPU_SPECIALIZER
#include <ctemplate/template.h>
static ctemplate::Strip strip_mode = ctemplate::STRIP_BLANK_LINES;
void specializer_init()
{
ctemplate::mutable_default_template_cache()->SetTemplateRootDirectory(template_path);
ctemplate::LoadTemplate("ewise.cont.nd.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.1d.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.2d.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.3d.tpl", strip_mode);
ctemplate::LoadTemplate("ewise.strided.nd.tpl", strip_mode);
ctemplate::LoadTemplate("kernel.tpl", strip_mode);
ctemplate::LoadTemplate("license.tpl", strip_mode);
ctemplate::LoadTemplate("random.cont.1d.tpl", strip_mode);
ctemplate::LoadTemplate("range.cont.1d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.1d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.2d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.3d.tpl", strip_mode);
ctemplate::LoadTemplate("reduce.strided.nd.tpl", strip_mode);
ctemplate::LoadTemplate("scan.strided.1d.tpl", strip_mode);
ctemplate::LoadTemplate("scan.strided.nd.tpl", strip_mode);
ctemplate::mutable_default_template_cache()->Freeze();
}
/**
* Choose the template.
*
* Contract: Do not call this for system or extension operations.
*/
string template_filename(block_t& block, int pc, bh_intp optimized)
{
string tpl_ndim = "nd.",
tpl_opcode,
tpl_layout = "strided.";
tac_t* tac = &block.program[pc];
int ndim = (tac->op == REDUCE) ? \
block.scope[tac->in1].ndim : \
block.scope[tac->out].ndim;
int lmask = block.lmask[pc];
switch (tac->op) { // OPCODE_SWITCH
case MAP:
tpl_opcode = "ewise.";
if ((optimized) && ((lmask == LMASK_CC) || \
(lmask == LMASK_CK))) {
tpl_layout = "cont.";
} else if ((optimized) && (ndim == 1)) {
tpl_ndim = "1d.";
} else if ((optimized) && (ndim == 2)) {
tpl_ndim = "2d.";
} else if ((optimized) && (ndim == 3)) {
tpl_ndim = "3d.";
}
break;
case ZIP:
tpl_opcode = "ewise.";
if ((optimized) && (
(lmask == LMASK_CCC) || (lmask == LMASK_CKC) || (lmask == LMASK_CCK)
)) {
tpl_layout = "cont.";
} else if ((optimized) && (ndim == 1)) {
tpl_ndim = "1d.";
} else if ((optimized) && (ndim == 2)) {
tpl_ndim = "2d.";
} else if ((optimized) && (ndim == 3)) {
tpl_ndim = "3d.";
}
break;
case SCAN:
tpl_opcode = "scan.";
if (optimized && (ndim == 1)) {
tpl_ndim = "1d.";
}
break;
case REDUCE:
tpl_opcode = "reduce.";
if (optimized && (ndim == 1)) {
tpl_ndim = "1d.";
} else if (optimized && (ndim == 2)) {
tpl_ndim = "2d.";
} else if (optimized && (ndim == 3)) {
tpl_ndim = "3d.";
}
break;
case GENERATE:
switch(tac->oper) {
case RANDOM:
tpl_opcode = "random.";
break;
case RANGE:
tpl_opcode = "range.";
default:
printf("Operator x is not supported with operation y\n");
}
tpl_layout = "cont.";
break;
default:
printf("template_filename: Err=[Unsupported operation %d.]\n", tac->oper);
throw runtime_error("template_filename: No template for opcode.");
}
return tpl_opcode + tpl_layout + tpl_ndim + "tpl";
}
/**
* Construct the c-sourcecode for the given block.
*
* NOTE: System opcodes are ignored.
*
* @param optimized The level of optimizations to apply to the generated code.
* @param block The block to generate sourcecode for.
* @return The generated sourcecode.
*
*/
string specialize(block_t& block, bh_intp const optimized) {
string sourcecode = "";
ctemplate::TemplateDictionary kernel_d("KERNEL"); // Kernel - function wrapping code
kernel_d.SetValue("SYMBOL", block.symbol);
for(int j=0; j<block.ninstr; ++j) {
//
// Grab the tacuction for which to generate sourcecode
tac_t *tac = &block.program[j];
//
// Skip code generation for system and extensions
if ((tac->op == SYSTEM) || (tac->op == EXTENSION)) {
continue;
}
//
// The operation (ewise, reduction, scan, random, range).
ctemplate::TemplateDictionary* operation_d = kernel_d.AddIncludeDictionary("OPERATIONS");
string tf = template_filename(
block,
j,
optimized
);
operation_d->SetFilename(tf);
//
// The operator +, -, /, min, max, sin, sqrt, etc...
//
ctemplate::TemplateDictionary* operator_d = operation_d->AddSectionDictionary("OPERATORS");
operator_d->SetValue("OPERATOR", operator_cexpr(tac->op, tac->oper, block.scope[tac->out].type));
//
// Reduction and scan specific expansions
// TODO: fix for multiple tacuctions
if ((tac->op == REDUCE) || (tac->op == SCAN)) {
operation_d->SetValue("TYPE_OUTPUT", enum_to_ctypestr(block.scope[tac->out].type));
operation_d->SetValue("TYPE_INPUT", enum_to_ctypestr(block.scope[tac->in1].type));
operation_d->SetValue("TYPE_AXIS", "int64_t");
if (tac->oper == ADD) {
operation_d->SetValue("NEUTRAL_ELEMENT", std::to_string(0));
} else if (tac->oper == MULTIPLY) {
operation_d->SetValue("NEUTRAL_ELEMENT", std::to_string(1));
}
}
operation_d->SetValue("NR_OUTPUT", std::to_string(tac->out));
operation_d->SetValue("NR_FINPUT", std::to_string(tac->in1)); // Not all have
operation_d->SetValue("NR_SINPUT", std::to_string(tac->in2)); // Not all have
//
// Fill out the tacuction operands globally such that they
// are available to both for the kernel argument unpacking, the operations and the operators.
//
// TODO: this should actually distinguish between the total set of operands
// and those used for a single tacuction depending on the amount of loops that can be
// fused
//
int nops_tac = noperands(tac);
for(int i=0; i<nops_tac; ++i) { // Operand dict
ctemplate::TemplateDictionary* argument_d = kernel_d.AddSectionDictionary("ARGUMENT");
ctemplate::TemplateDictionary* operand_d = operation_d->AddSectionDictionary("OPERAND");
argument_d->SetValue("TYPE", enum_to_ctypestr(block.scope[tac->out].type));
argument_d->SetIntValue("NR", tac->out);
operand_d->SetValue("TYPE", enum_to_ctypestr(block.scope[tac->out].type));
operand_d->SetIntValue("NR", tac->out);
if (block.scope[tac->out].layout != CONSTANT) {
argument_d->ShowSection("ARRAY");
operand_d->ShowSection("ARRAY");
}
}
}
//
// Fill out the template and return the generated sourcecode
//
ctemplate::ExpandTemplate(
"kernel.tpl",
strip_mode,
&kernel_d,
&sourcecode
);
return sourcecode;
}
/**
* Create a symbol for the kernel.
*
* NOTE: System and extension opcodes are ignored.
* If a block consists of nothing but system and/or extension
* opcodes then the symbol will be the empty string "".
*/
bool symbolize(block_t &block, bh_intp const optimized) {
std::string symbol_opcode,
symbol_lmask,
symbol_tsig,
symbol_ndim;
block.symbol = "";
for (int i=0; i<block.ninstr; ++i) {
tac_t* tac = &block.program[i];
// Do not include system opcodes in the kernel symbol.
if ((tac->op == SYSTEM) || (tac->op == EXTENSION)) {
continue;
}
symbol_opcode += std::string(bh_opcode_to_cstr_short(tac->op));
symbol_tsig += std::string(bh_typesig_to_shorthand(block.tsig[i]));
symbol_lmask += std::string(bh_layoutmask_to_shorthand(block.lmask[i]));
int ndim = block.scope[tac->out].ndim;
if (tac->op == REDUCE) {
ndim = block.scope[tac->in1].ndim;
}
if (optimized && (ndim <= 3)) { // Optimized
symbol_ndim += std::to_string(ndim);
} else {
symbol_ndim += std::string("N");
}
symbol_ndim += "D";
block.tsig[i] = tsig;
block.lmask[i] = lmask;
}
if (block.omask == (HAS_ARRAY_OP)) {
block.symbol = "BH_" + \
symbol_opcode + "_" +\
symbol_tsig + "_" +\
symbol_lmask + "_" +\
symbol_ndim;
}
return true;
}
#endif
<|endoftext|> |
<commit_before>#line 2 "togo/game/world/world_manager.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/game/config.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/collection/array.hpp>
#include <togo/core/collection/queue.hpp>
#include <togo/core/collection/hash_map.hpp>
#include <togo/game/world/types.hpp>
#include <togo/game/world/world_manager.hpp>
namespace togo {
namespace game {
namespace {
enum : unsigned {
MIN_FREE_INDICES = 64,
};
} // anonymous namespace
WorldInstance::WorldInstance(
Allocator& allocator
)
: generation(0)
, component_managers(allocator)
, entities(allocator)
{}
WorldManager::WorldManager(
Allocator& allocator
)
: _component_manager_defs(allocator)
, _instances(allocator)
, _free_indices(allocator)
{
hash_map::reserve(_component_manager_defs, 32);
array::reserve(_instances, 32);
queue::reserve(_free_indices, MIN_FREE_INDICES);
}
WorldManager::~WorldManager() {
world_manager::shutdown(*this);
}
/// Whether a world is alive.
bool world_manager::alive(
WorldManager const& wm,
WorldID const& id
) {
auto const index = id.index();
return
index < array::size(wm._instances) &&
wm._instances[index].generation == id.generation()
;
}
/// Register a component manager.
///
/// An assertion will fail if the component name has already been
/// registered.
/// Component managers must be registered before any worlds are created.
void world_manager::register_component_manager(
WorldManager& wm,
ComponentManagerDef const& def
) {
TOGO_DEBUG_ASSERTE(
def.name_hash != hash::IDENTITY32 &&
def.func_create &&
def.func_destroy &&
def.func_clear
);
TOGO_ASSERT(
!hash_map::has(wm._component_manager_defs, def.name_hash),
"a component manager has already been registered with this name"
);
TOGO_ASSERT(
array::empty(wm._instances),
"component managers must be registered before any worlds are created"
);
hash_map::push(wm._component_manager_defs, def.name_hash, def);
}
/// Create world.
WorldID world_manager::create(WorldManager& wm) {
WorldID::value_type index;
if (queue::size(wm._free_indices) > MIN_FREE_INDICES) {
index = queue::front(wm._free_indices);
queue::pop_front(wm._free_indices);
} else {
index = array::size(wm._instances);
array::increase_size(wm._instances, 1);
auto& instance = array::back(wm._instances);
new(&instance) WorldInstance(*wm._instances._allocator);
hash_map::reserve(
instance.component_managers,
hash_map::size(wm._component_manager_defs)
);
for (auto const& entry : wm._component_manager_defs) {
hash_map::push(instance.component_managers, entry.key, entry.value.func_create(wm));
}
TOGO_ASSERTE(index < (1 << WorldID::INDEX_BITS));
}
return WorldID{index | (wm._instances[index].generation << WorldID::INDEX_BITS)};
}
/// Destroy world.
void world_manager::destroy(
WorldManager& wm,
WorldID const& id
) {
TOGO_ASSERTE(world_manager::alive(wm, id));
auto const index = id.index();
auto& instance = wm._instances[index];
array::clear(instance.entities);
for (auto& entry : instance.component_managers) {
void* data = entry.value;
auto* def = hash_map::find(wm._component_manager_defs, entry.key);
TOGO_DEBUG_ASSERTE(def);
def->func_clear(wm, data);
}
++instance.generation;
queue::push_back(wm._free_indices, index);
}
/// Shutdown.
///
/// Removes all worlds and component manager definitions.
/// This should only be used as part of system deinitialization.
/// Using it during runtime can lead to zombie IDs pointing to valid
/// worlds (i.e., not the world originally created with the ID).
void world_manager::shutdown(WorldManager& wm) {
for (auto& instance : wm._instances) {
for (auto const& entry : instance.component_managers) {
void* data = entry.value;
auto* def = hash_map::find(wm._component_manager_defs, entry.key);
TOGO_DEBUG_ASSERTE(def);
def->func_destroy(wm, data);
}
instance.~WorldInstance();
}
queue::clear(wm._free_indices);
array::clear(wm._instances);
hash_map::clear(wm._component_manager_defs);
}
} // namespace game
} // namespace togo
<commit_msg>lib/game/world/world_manager: use push_back_inplace() instead of placement-new.<commit_after>#line 2 "togo/game/world/world_manager.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/game/config.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/collection/array.hpp>
#include <togo/core/collection/queue.hpp>
#include <togo/core/collection/hash_map.hpp>
#include <togo/game/world/types.hpp>
#include <togo/game/world/world_manager.hpp>
namespace togo {
namespace game {
namespace {
enum : unsigned {
MIN_FREE_INDICES = 64,
};
} // anonymous namespace
WorldInstance::WorldInstance(
Allocator& allocator
)
: generation(0)
, component_managers(allocator)
, entities(allocator)
{}
WorldManager::WorldManager(
Allocator& allocator
)
: _component_manager_defs(allocator)
, _instances(allocator)
, _free_indices(allocator)
{
hash_map::reserve(_component_manager_defs, 32);
array::reserve(_instances, 32);
queue::reserve(_free_indices, MIN_FREE_INDICES);
}
WorldManager::~WorldManager() {
world_manager::shutdown(*this);
}
/// Whether a world is alive.
bool world_manager::alive(
WorldManager const& wm,
WorldID const& id
) {
auto const index = id.index();
return
index < array::size(wm._instances) &&
wm._instances[index].generation == id.generation()
;
}
/// Register a component manager.
///
/// An assertion will fail if the component name has already been
/// registered.
/// Component managers must be registered before any worlds are created.
void world_manager::register_component_manager(
WorldManager& wm,
ComponentManagerDef const& def
) {
TOGO_DEBUG_ASSERTE(
def.name_hash != hash::IDENTITY32 &&
def.func_create &&
def.func_destroy &&
def.func_clear
);
TOGO_ASSERT(
!hash_map::has(wm._component_manager_defs, def.name_hash),
"a component manager has already been registered with this name"
);
TOGO_ASSERT(
array::empty(wm._instances),
"component managers must be registered before any worlds are created"
);
hash_map::push(wm._component_manager_defs, def.name_hash, def);
}
/// Create world.
WorldID world_manager::create(WorldManager& wm) {
WorldID::value_type index;
if (queue::size(wm._free_indices) > MIN_FREE_INDICES) {
index = queue::front(wm._free_indices);
queue::pop_front(wm._free_indices);
} else {
index = array::size(wm._instances);
auto& instance = array::push_back_inplace(wm._instances, *wm._instances._allocator);
hash_map::reserve(
instance.component_managers,
hash_map::size(wm._component_manager_defs)
);
for (auto const& entry : wm._component_manager_defs) {
hash_map::push(instance.component_managers, entry.key, entry.value.func_create(wm));
}
TOGO_ASSERTE(index < (1 << WorldID::INDEX_BITS));
}
return WorldID{index | (wm._instances[index].generation << WorldID::INDEX_BITS)};
}
/// Destroy world.
void world_manager::destroy(
WorldManager& wm,
WorldID const& id
) {
TOGO_ASSERTE(world_manager::alive(wm, id));
auto const index = id.index();
auto& instance = wm._instances[index];
array::clear(instance.entities);
for (auto& entry : instance.component_managers) {
void* data = entry.value;
auto* def = hash_map::find(wm._component_manager_defs, entry.key);
TOGO_DEBUG_ASSERTE(def);
def->func_clear(wm, data);
}
++instance.generation;
queue::push_back(wm._free_indices, index);
}
/// Shutdown.
///
/// Removes all worlds and component manager definitions.
/// This should only be used as part of system deinitialization.
/// Using it during runtime can lead to zombie IDs pointing to valid
/// worlds (i.e., not the world originally created with the ID).
void world_manager::shutdown(WorldManager& wm) {
for (auto& instance : wm._instances) {
for (auto const& entry : instance.component_managers) {
void* data = entry.value;
auto* def = hash_map::find(wm._component_manager_defs, entry.key);
TOGO_DEBUG_ASSERTE(def);
def->func_destroy(wm, data);
}
instance.~WorldInstance();
}
queue::clear(wm._free_indices);
array::clear(wm._instances);
hash_map::clear(wm._component_manager_defs);
}
} // namespace game
} // namespace togo
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include <autowiring/autowiring.h>
#include <autowiring/AutoSelfUpdate.h>
class AutoFilterSequencing:
public testing::Test
{
public:
AutoFilterSequencing(void) {
AutoCurrentContext()->Initiate();
}
};
class FilterFirst {
public:
FilterFirst(void) :
m_magic(0xDEADBEEF),
m_called(0)
{}
const int m_magic;
int m_called;
void AutoFilter(AutoPacket& pkt) {
ASSERT_EQ(0xDEADBEEF, m_magic) << "Magic value was corrupted, pointer was not adjusted to the correct offset";
++m_called;
pkt.Decorate(Decoration<0>());
}
};
class FilterFirstValidateInheritance:
public FilterFirst
{};
static_assert(
std::is_same<
FilterFirst,
Decompose<decltype(&FilterFirstValidateInheritance::AutoFilter)>::type
>::value,
"Decomposed type did not correctly name the implementing type of an inherited method"
);
TEST_F(AutoFilterSequencing, VerifyFirstLastCalls) {
AutoRequired<AutoPacketFactory> factory;
AutoRequired<FilterFirst> first;
{
auto pkt = factory->NewPacket();
ASSERT_EQ(1, first->m_called) << "First-call filter was not applied";
}
ASSERT_EQ(1, first->m_called) << "First-call filter was applied as final call";
}
class FilterOutDeferred:
public CoreThread
{
public:
Deferred AutoFilter(auto_out<Decoration<0>> out) {
//Default constructor sets i == 0
return Deferred(this);
}
};
TEST_F(AutoFilterSequencing, SuccessorAliasRules) {
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
auto packet2 = packet1->Successor();
ASSERT_TRUE(!!packet2) << "Returned successor packet was null";
auto expected = factory->NewPacket();
ASSERT_EQ(expected, packet2) << "Expected that the successor packet would match the next packet returned by the factory";
}
TEST_F(AutoFilterSequencing, SuccessorHoldViolationCheck) {
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
auto packet2 = packet1->Successor();
ASSERT_TRUE(packet1.unique()) << "Expected that the first issued packet shared pointer not to be aliased anywhere";
packet1.reset();
ASSERT_TRUE(packet2.unique()) << "Expected that a successor packet would be unique when the principal was destroyed";
}
TEST_F(AutoFilterSequencing, PacketReverseSuccessor) {
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
auto packet2 = factory->NewPacket();
ASSERT_EQ(packet2, packet1->Successor()) << "Successor packet obtained after generation from the factory did not match as expected";
}
TEST_F(AutoFilterSequencing, ManySuccessors) {
AutoRequired<AutoPacketFactory> factory;
auto packetA = factory->NewPacket();
auto packet5 = packetA->Successor()->Successor()->Successor()->Successor();
auto packetB = factory->NewPacket();
auto packetC = factory->NewPacket();
auto packetD = factory->NewPacket();
auto packetE = factory->NewPacket();
ASSERT_EQ(packet5, packetE) << "Successor packet obtained after generation from the factory did not match as expected";
}
<commit_msg>Add AutoPacket successor satisfaction test<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include <autowiring/autowiring.h>
#include <autowiring/AutoSelfUpdate.h>
class AutoFilterSequencing:
public testing::Test
{
public:
AutoFilterSequencing(void) {
AutoCurrentContext()->Initiate();
}
};
class FilterFirst {
public:
FilterFirst(void) :
m_magic(0xDEADBEEF),
m_called(0)
{}
const int m_magic;
int m_called;
void AutoFilter(AutoPacket& pkt) {
ASSERT_EQ(0xDEADBEEF, m_magic) << "Magic value was corrupted, pointer was not adjusted to the correct offset";
++m_called;
pkt.Decorate(Decoration<0>());
}
};
class FilterFirstValidateInheritance:
public FilterFirst
{};
static_assert(
std::is_same<
FilterFirst,
Decompose<decltype(&FilterFirstValidateInheritance::AutoFilter)>::type
>::value,
"Decomposed type did not correctly name the implementing type of an inherited method"
);
TEST_F(AutoFilterSequencing, VerifyFirstLastCalls) {
AutoRequired<AutoPacketFactory> factory;
AutoRequired<FilterFirst> first;
{
auto pkt = factory->NewPacket();
ASSERT_EQ(1, first->m_called) << "First-call filter was not applied";
}
ASSERT_EQ(1, first->m_called) << "First-call filter was applied as final call";
}
class FilterOutDeferred:
public CoreThread
{
public:
Deferred AutoFilter(auto_out<Decoration<0>> out) {
//Default constructor sets i == 0
return Deferred(this);
}
};
TEST_F(AutoFilterSequencing, SuccessorAliasRules) {
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
auto packet2 = packet1->Successor();
ASSERT_TRUE(!!packet2) << "Returned successor packet was null";
auto expected = factory->NewPacket();
ASSERT_EQ(expected, packet2) << "Expected that the successor packet would match the next packet returned by the factory";
}
TEST_F(AutoFilterSequencing, SuccessorHoldViolationCheck) {
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
auto packet2 = packet1->Successor();
ASSERT_TRUE(packet1.unique()) << "Expected that the first issued packet shared pointer not to be aliased anywhere";
packet1.reset();
ASSERT_TRUE(packet2.unique()) << "Expected that a successor packet would be unique when the principal was destroyed";
}
TEST_F(AutoFilterSequencing, PacketReverseSuccessor) {
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
auto packet2 = factory->NewPacket();
ASSERT_EQ(packet2, packet1->Successor()) << "Successor packet obtained after generation from the factory did not match as expected";
}
TEST_F(AutoFilterSequencing, ManySuccessors) {
AutoRequired<AutoPacketFactory> factory;
{
auto packetA = factory->NewPacket();
auto packet5 = packetA->Successor()->Successor()->Successor()->Successor();
factory->NewPacket();
factory->NewPacket();
factory->NewPacket();
auto packetE = factory->NewPacket();
ASSERT_EQ(packet5, packetE) << "Successor packet obtained after generation from the factory did not match as expected";
}
AutoRequired<FilterFirst> first;
{
auto packetA = factory->NewPacket();
packetA->Successor()->Successor()->Successor()->Successor();
ASSERT_EQ(1, first->m_called) << "AutoFilter triggered from successor";
factory->NewPacket();
ASSERT_EQ(2, first->m_called) << "AutoFilter not triggered from new packet";
factory->NewPacket();
ASSERT_EQ(3, first->m_called) << "AutoFilter not triggered from new packet";
factory->NewPacket();
ASSERT_EQ(4, first->m_called) << "AutoFilter not triggered from new packet";
factory->NewPacket();
ASSERT_EQ(5, first->m_called) << "AutoFilter not triggered from new packet";
factory->NewPacket();
ASSERT_EQ(6, first->m_called) << "AutoFilter not triggered from new packet";
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// index_scan_executor.cpp
//
// Identification: src/backend/executor/index_scan_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/executor/index_scan_executor.h"
#include <memory>
#include <utility>
#include <vector>
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/common/logger.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for indexscan executor.
* @param node Indexscan node corresponding to this executor.
*/
IndexScanExecutor::IndexScanExecutor(planner::AbstractPlanNode *node,
ExecutorContext *executor_context)
: AbstractScanExecutor(node, executor_context) {}
/**
* @brief Let base class Dinit() first, then do my job.
* @return true on success, false otherwise.
*/
bool IndexScanExecutor::DInit() {
auto status = AbstractScanExecutor::DInit();
if (!status) return false;
assert(children_.size() == 0);
LOG_TRACE("Index Scan executor :: 0 child");
// Grab info from plan node and check it
const planner::IndexScanNode &node = GetPlanNode<planner::IndexScanNode>();
index_ = node.GetIndex();
assert(index_ != nullptr);
result_itr = START_OID;
done_ = false;
column_ids_ = node.GetColumnIds();
key_column_ids_ = node.GetKeyColumnIds();
expr_types_ = node.GetExprTypes();
values_ = node.GetValues();
auto table = node.GetTable();
if (table != nullptr) {
if (column_ids_.empty()) {
column_ids_.resize(table->GetSchema()->GetColumnCount());
std::iota(column_ids_.begin(), column_ids_.end(), 0);
}
}
return true;
}
/**
* @brief Creates logical tile(s) after scanning index.
* @return true on success, false otherwise.
*/
bool IndexScanExecutor::DExecute() {
if (!done_) {
auto status = ExecIndexLookup();
if (status == false) return false;
}
// Already performed the index lookup
assert(done_);
while (result_itr < result.size()) { // Avoid returning empty tiles
// In order to be as lazy as possible,
// the generic predicate is checked here (instead of upfront)
if (nullptr != predicate_) {
for (oid_t tuple_id : *result[result_itr]) {
expression::ContainerTuple<LogicalTile> tuple(result[result_itr],
tuple_id);
if (predicate_->Evaluate(&tuple, nullptr, executor_context_)
.IsFalse()) {
result[result_itr]->RemoveVisibility(tuple_id);
}
}
}
if (result[result_itr]->GetTupleCount() == 0) {
result_itr++;
continue;
} else {
SetOutput(result[result_itr]);
result_itr++;
return true;
}
} // end while
return false;
}
bool IndexScanExecutor::ExecIndexLookup() {
assert(!done_);
std::vector<ItemPointer> tuple_locations;
tuple_locations = index_->Scan(values_, key_column_ids_, expr_types_);
LOG_INFO("Tuple locations : %lu", tuple_locations.size());
if (tuple_locations.size() == 0) return false;
auto transaction_ = executor_context_->GetTransaction();
txn_id_t txn_id = transaction_->GetTransactionId();
cid_t commit_id = transaction_->GetLastCommitId();
// Get the logical tiles corresponding to the given tuple locations
result = LogicalTileFactory::WrapTileGroups(tuple_locations, column_ids_,
txn_id, commit_id);
done_ = true;
LOG_TRACE("Result tiles : %lu", result.size());
return true;
}
} // namespace executor
} // namespace peloton
<commit_msg>index scan handles empty scan keys<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// index_scan_executor.cpp
//
// Identification: src/backend/executor/index_scan_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/executor/index_scan_executor.h"
#include <memory>
#include <utility>
#include <vector>
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/common/logger.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for indexscan executor.
* @param node Indexscan node corresponding to this executor.
*/
IndexScanExecutor::IndexScanExecutor(planner::AbstractPlanNode *node,
ExecutorContext *executor_context)
: AbstractScanExecutor(node, executor_context) {}
/**
* @brief Let base class Dinit() first, then do my job.
* @return true on success, false otherwise.
*/
bool IndexScanExecutor::DInit() {
auto status = AbstractScanExecutor::DInit();
if (!status) return false;
assert(children_.size() == 0);
LOG_TRACE("Index Scan executor :: 0 child");
// Grab info from plan node and check it
const planner::IndexScanNode &node = GetPlanNode<planner::IndexScanNode>();
index_ = node.GetIndex();
assert(index_ != nullptr);
result_itr = START_OID;
done_ = false;
column_ids_ = node.GetColumnIds();
key_column_ids_ = node.GetKeyColumnIds();
expr_types_ = node.GetExprTypes();
values_ = node.GetValues();
auto table = node.GetTable();
if (table != nullptr) {
if (column_ids_.empty()) {
column_ids_.resize(table->GetSchema()->GetColumnCount());
std::iota(column_ids_.begin(), column_ids_.end(), 0);
}
}
return true;
}
/**
* @brief Creates logical tile(s) after scanning index.
* @return true on success, false otherwise.
*/
bool IndexScanExecutor::DExecute() {
if (!done_) {
auto status = ExecIndexLookup();
if (status == false) return false;
}
// Already performed the index lookup
assert(done_);
while (result_itr < result.size()) { // Avoid returning empty tiles
// In order to be as lazy as possible,
// the generic predicate is checked here (instead of upfront)
if (nullptr != predicate_) {
for (oid_t tuple_id : *result[result_itr]) {
expression::ContainerTuple<LogicalTile> tuple(result[result_itr],
tuple_id);
if (predicate_->Evaluate(&tuple, nullptr, executor_context_)
.IsFalse()) {
result[result_itr]->RemoveVisibility(tuple_id);
}
}
}
if (result[result_itr]->GetTupleCount() == 0) {
result_itr++;
continue;
} else {
SetOutput(result[result_itr]);
result_itr++;
return true;
}
} // end while
return false;
}
bool IndexScanExecutor::ExecIndexLookup() {
assert(!done_);
std::vector<ItemPointer> tuple_locations;
if (0 == key_column_ids_.size()) {
tuple_locations = index_->Scan();
} else {
tuple_locations = index_->Scan(values_, key_column_ids_, expr_types_);
}
LOG_INFO("Tuple locations : %lu", tuple_locations.size());
if (tuple_locations.size() == 0) return false;
auto transaction_ = executor_context_->GetTransaction();
txn_id_t txn_id = transaction_->GetTransactionId();
cid_t commit_id = transaction_->GetLastCommitId();
// Get the logical tiles corresponding to the given tuple locations
result = LogicalTileFactory::WrapTileGroups(tuple_locations, column_ids_,
txn_id, commit_id);
done_ = true;
LOG_TRACE("Result tiles : %lu", result.size());
return true;
}
} // namespace executor
} // namespace peloton
<|endoftext|> |
<commit_before>/*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) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Peng Xiao, [email protected]
//
// 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 "opencl_kernels.hpp"
using namespace cv;
using namespace cv::ocl;
// currently sort procedure on the host is more efficient
static bool use_cpu_sorter = true;
// compact structure for corners
struct DefCorner
{
float eig; //eigenvalue of corner
short x; //x coordinate of corner point
short y; //y coordinate of corner point
} ;
// compare procedure for corner
//it is used for sort on the host side
struct DefCornerCompare
{
bool operator()(const DefCorner a, const DefCorner b) const
{
return a.eig > b.eig;
}
};
// sort corner point using opencl bitonicosrt implementation
static void sortCorners_caller(oclMat& corners, const int count)
{
Context * cxt = Context::getContext();
int GS = count/2;
int LS = min(255,GS);
size_t globalThreads[3] = {GS, 1, 1};
size_t localThreads[3] = {LS, 1, 1};
// 2^numStages should be equal to count or the output is invalid
int numStages = 0;
for(int i = count; i > 1; i >>= 1)
{
++numStages;
}
const int argc = 4;
std::vector< std::pair<size_t, const void *> > args(argc);
std::string kernelname = "sortCorners_bitonicSort";
args[0] = std::make_pair(sizeof(cl_mem), (void *)&corners.data);
args[1] = std::make_pair(sizeof(cl_int), (void *)&count);
for(int stage = 0; stage < numStages; ++stage)
{
args[2] = std::make_pair(sizeof(cl_int), (void *)&stage);
for(int passOfStage = 0; passOfStage < stage + 1; ++passOfStage)
{
args[3] = std::make_pair(sizeof(cl_int), (void *)&passOfStage);
openCLExecuteKernel(cxt, &imgproc_gftt, kernelname, globalThreads, localThreads, args, -1, -1);
}
}
}
// find corners on matrix and put it into array
static void findCorners_caller(
const oclMat& eig_mat, //input matrix worth eigenvalues
oclMat& eigMinMax, //input with min and max values of eigenvalues
const float qualityLevel,
const oclMat& mask,
oclMat& corners, //output array with detected corners
oclMat& counter) //output value with number of detected corners, have to be 0 before call
{
string opt;
std::vector<int> k;
Context * cxt = Context::getContext();
std::vector< std::pair<size_t, const void*> > args;
const int mask_strip = mask.step / mask.elemSize1();
args.push_back(make_pair( sizeof(cl_mem), (void*)&(eig_mat.data)));
int src_pitch = (int)eig_mat.step;
args.push_back(make_pair( sizeof(cl_int), (void*)&src_pitch ));
args.push_back(make_pair( sizeof(cl_mem), (void*)&mask.data ));
args.push_back(make_pair( sizeof(cl_mem), (void*)&corners.data ));
args.push_back(make_pair( sizeof(cl_int), (void*)&mask_strip));
args.push_back(make_pair( sizeof(cl_mem), (void*)&eigMinMax.data ));
args.push_back(make_pair( sizeof(cl_float), (void*)&qualityLevel ));
args.push_back(make_pair( sizeof(cl_int), (void*)&eig_mat.rows ));
args.push_back(make_pair( sizeof(cl_int), (void*)&eig_mat.cols ));
args.push_back(make_pair( sizeof(cl_int), (void*)&corners.cols ));
args.push_back(make_pair( sizeof(cl_mem), (void*)&counter.data ));
size_t globalThreads[3] = {eig_mat.cols, eig_mat.rows, 1};
size_t localThreads[3] = {16, 16, 1};
if(!mask.empty())
opt += " -D WITH_MASK=1";
openCLExecuteKernel(cxt, &imgproc_gftt, "findCorners", globalThreads, localThreads, args, -1, -1, opt.c_str());
}
static void minMaxEig_caller(const oclMat &src, oclMat &dst, oclMat & tozero)
{
size_t groupnum = src.clCxt->getDeviceInfo().maxComputeUnits;
CV_Assert(groupnum != 0);
int dbsize = groupnum * 2 * src.elemSize();
ensureSizeIsEnough(1, dbsize, CV_8UC1, dst);
cl_mem dst_data = reinterpret_cast<cl_mem>(dst.data);
int vElemSize = src.elemSize1();
int src_step = src.step / vElemSize, src_offset = src.offset / vElemSize;
int total = src.size().area();
{
// first parallel pass
vector<pair<size_t , const void *> > args;
args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src_step));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src_offset));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
args.push_back( make_pair( sizeof(cl_int) , (void *)&total));
args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum));
args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_data ));
size_t globalThreads[3] = {groupnum * 256, 1, 1};
size_t localThreads[3] = {256, 1, 1};
openCLExecuteKernel(src.clCxt, &arithm_minMax, "arithm_op_minMax", globalThreads, localThreads,
args, -1, -1, "-D T=float -D DEPTH_5 -D vlen=1");
}
{
// run final "serial" kernel to find accumulate results from threads and reset corner counter
vector<pair<size_t , const void *> > args;
args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_data ));
args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum ));
args.push_back( make_pair( sizeof(cl_mem) , (void *)&tozero.data ));
size_t globalThreads[3] = {1, 1, 1};
size_t localThreads[3] = {1, 1, 1};
openCLExecuteKernel(src.clCxt, &imgproc_gftt, "arithm_op_minMax_final", globalThreads, localThreads,
args, -1, -1);
}
}
void cv::ocl::GoodFeaturesToTrackDetector_OCL::operator ()(const oclMat& image, oclMat& corners, const oclMat& mask)
{
CV_Assert(qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0);
CV_Assert(mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()));
ensureSizeIsEnough(image.size(), CV_32F, eig_);
if (useHarrisDetector)
cornerHarris_dxdy(image, eig_, Dx_, Dy_, blockSize, 3, harrisK);
else
cornerMinEigenVal_dxdy(image, eig_, Dx_, Dy_, blockSize, 3);
ensureSizeIsEnough(1,1, CV_32SC1, counter_);
// find max eigenvalue and reset detected counters
minMaxEig_caller(eig_,eig_minmax_,counter_);
// allocate buffer for kernels
int corner_array_size = std::max(1024, static_cast<int>(image.size().area() * 0.05));
if(!use_cpu_sorter)
{ // round to 2^n
unsigned int n=1;
for(n=1;n<(unsigned int)corner_array_size;n<<=1) ;
corner_array_size = (int)n;
ensureSizeIsEnough(1, corner_array_size , CV_32FC2, tmpCorners_);
// set to 0 to be able use bitonic sort on whole 2^n array
tmpCorners_.setTo(0);
}
else
{
ensureSizeIsEnough(1, corner_array_size , CV_32FC2, tmpCorners_);
}
int total = tmpCorners_.cols; // by default the number of corner is full array
vector<DefCorner> tmp(tmpCorners_.cols); // input buffer with corner for HOST part of algorithm
//find points with high eigenvalue and put it into the output array
findCorners_caller(
eig_,
eig_minmax_,
static_cast<float>(qualityLevel),
mask,
tmpCorners_,
counter_);
if(!use_cpu_sorter)
{// sort detected corners on deivce side
sortCorners_caller(tmpCorners_, corner_array_size);
}
else
{// send non-blocking request to read real non-zero number of corners to sort it on the HOST side
openCLVerifyCall(clEnqueueReadBuffer(getClCommandQueue(counter_.clCxt), (cl_mem)counter_.data, CL_FALSE, 0,sizeof(int), &total, 0, NULL, NULL));
}
//blocking read whole corners array (sorted or not sorted)
openCLReadBuffer(tmpCorners_.clCxt,(cl_mem)tmpCorners_.data,&tmp[0],tmpCorners_.cols*sizeof(DefCorner));
if (total == 0)
{// check for trivial case
corners.release();
return;
}
if(use_cpu_sorter)
{// sort detected corners on cpu side.
tmp.resize(total);
cv::sort(tmp,DefCornerCompare());
}
//estimate maximal size of final output array
int total_max = maxCorners > 0 ? std::min(maxCorners, total) : total;
int D2 = (int)ceil(minDistance * minDistance);
// allocate output buffer
vector<Point2f> tmp2;
tmp2.reserve(total_max);
if (minDistance < 1)
{// we have not distance restriction. then just copy with conversion maximal allowed points into output array
for(int i=0;i<total_max && tmp[i].eig>0.0f;++i)
{
tmp2.push_back(Point2f(tmp[i].x,tmp[i].y));
}
}
else
{// we have distance restriction. then start coping to output array from the first element and check distance for each next one
const int cell_size = cvRound(minDistance);
const int grid_width = (image.cols + cell_size - 1) / cell_size;
const int grid_height = (image.rows + cell_size - 1) / cell_size;
std::vector< std::vector<Point2i> > grid(grid_width * grid_height);
for (int i = 0; i < total ; ++i)
{
DefCorner p = tmp[i];
if(p.eig<=0.0f)
break; // condition to stop that is needed for GPU bitonic sort usage.
bool good = true;
int x_cell = static_cast<int>(p.x / cell_size);
int y_cell = static_cast<int>(p.y / cell_size);
int x1 = x_cell - 1;
int y1 = y_cell - 1;
int x2 = x_cell + 1;
int y2 = y_cell + 1;
// boundary check
x1 = std::max(0, x1);
y1 = std::max(0, y1);
x2 = std::min(grid_width - 1, x2);
y2 = std::min(grid_height - 1, y2);
for (int yy = y1; yy <= y2; yy++)
{
for (int xx = x1; xx <= x2; xx++)
{
vector<Point2i>& m = grid[yy * grid_width + xx];
if (m.empty())
continue;
for(size_t j = 0; j < m.size(); j++)
{
int dx = p.x - m[j].x;
int dy = p.y - m[j].y;
if (dx * dx + dy * dy < D2)
{
good = false;
goto break_out_;
}
}
}
}
break_out_:
if(good)
{
grid[y_cell * grid_width + x_cell].push_back(Point2i(p.x,p.y));
tmp2.push_back(Point2f(p.x,p.y));
if (maxCorners > 0 && tmp2.size() == static_cast<size_t>(maxCorners))
break;
}
}
}
int final_size = static_cast<int>(tmp2.size());
if(final_size>0)
corners.upload(Mat(1, final_size, CV_32FC2, &tmp2[0]));
else
corners.release();
}
void cv::ocl::GoodFeaturesToTrackDetector_OCL::downloadPoints(const oclMat &points, vector<Point2f> &points_v)
{
CV_DbgAssert(points.type() == CV_32FC2);
points_v.resize(points.cols);
openCLSafeCall(clEnqueueReadBuffer(
*(cl_command_queue*)getClCommandQueuePtr(),
reinterpret_cast<cl_mem>(points.data),
CL_TRUE,
0,
points.cols * sizeof(Point2f),
&points_v[0],
0,
NULL,
NULL));
}
<commit_msg>remove unused variable in findCorners_caller()<commit_after>/*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) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Peng Xiao, [email protected]
//
// 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 "opencl_kernels.hpp"
using namespace cv;
using namespace cv::ocl;
// currently sort procedure on the host is more efficient
static bool use_cpu_sorter = true;
// compact structure for corners
struct DefCorner
{
float eig; //eigenvalue of corner
short x; //x coordinate of corner point
short y; //y coordinate of corner point
} ;
// compare procedure for corner
//it is used for sort on the host side
struct DefCornerCompare
{
bool operator()(const DefCorner a, const DefCorner b) const
{
return a.eig > b.eig;
}
};
// sort corner point using opencl bitonicosrt implementation
static void sortCorners_caller(oclMat& corners, const int count)
{
Context * cxt = Context::getContext();
int GS = count/2;
int LS = min(255,GS);
size_t globalThreads[3] = {GS, 1, 1};
size_t localThreads[3] = {LS, 1, 1};
// 2^numStages should be equal to count or the output is invalid
int numStages = 0;
for(int i = count; i > 1; i >>= 1)
{
++numStages;
}
const int argc = 4;
std::vector< std::pair<size_t, const void *> > args(argc);
std::string kernelname = "sortCorners_bitonicSort";
args[0] = std::make_pair(sizeof(cl_mem), (void *)&corners.data);
args[1] = std::make_pair(sizeof(cl_int), (void *)&count);
for(int stage = 0; stage < numStages; ++stage)
{
args[2] = std::make_pair(sizeof(cl_int), (void *)&stage);
for(int passOfStage = 0; passOfStage < stage + 1; ++passOfStage)
{
args[3] = std::make_pair(sizeof(cl_int), (void *)&passOfStage);
openCLExecuteKernel(cxt, &imgproc_gftt, kernelname, globalThreads, localThreads, args, -1, -1);
}
}
}
// find corners on matrix and put it into array
static void findCorners_caller(
const oclMat& eig_mat, //input matrix worth eigenvalues
oclMat& eigMinMax, //input with min and max values of eigenvalues
const float qualityLevel,
const oclMat& mask,
oclMat& corners, //output array with detected corners
oclMat& counter) //output value with number of detected corners, have to be 0 before call
{
string opt;
Context * cxt = Context::getContext();
std::vector< std::pair<size_t, const void*> > args;
const int mask_strip = mask.step / mask.elemSize1();
args.push_back(make_pair( sizeof(cl_mem), (void*)&(eig_mat.data)));
int src_pitch = (int)eig_mat.step;
args.push_back(make_pair( sizeof(cl_int), (void*)&src_pitch ));
args.push_back(make_pair( sizeof(cl_mem), (void*)&mask.data ));
args.push_back(make_pair( sizeof(cl_mem), (void*)&corners.data ));
args.push_back(make_pair( sizeof(cl_int), (void*)&mask_strip));
args.push_back(make_pair( sizeof(cl_mem), (void*)&eigMinMax.data ));
args.push_back(make_pair( sizeof(cl_float), (void*)&qualityLevel ));
args.push_back(make_pair( sizeof(cl_int), (void*)&eig_mat.rows ));
args.push_back(make_pair( sizeof(cl_int), (void*)&eig_mat.cols ));
args.push_back(make_pair( sizeof(cl_int), (void*)&corners.cols ));
args.push_back(make_pair( sizeof(cl_mem), (void*)&counter.data ));
size_t globalThreads[3] = {eig_mat.cols, eig_mat.rows, 1};
size_t localThreads[3] = {16, 16, 1};
if(!mask.empty())
opt += " -D WITH_MASK=1";
openCLExecuteKernel(cxt, &imgproc_gftt, "findCorners", globalThreads, localThreads, args, -1, -1, opt.c_str());
}
static void minMaxEig_caller(const oclMat &src, oclMat &dst, oclMat & tozero)
{
size_t groupnum = src.clCxt->getDeviceInfo().maxComputeUnits;
CV_Assert(groupnum != 0);
int dbsize = groupnum * 2 * src.elemSize();
ensureSizeIsEnough(1, dbsize, CV_8UC1, dst);
cl_mem dst_data = reinterpret_cast<cl_mem>(dst.data);
int vElemSize = src.elemSize1();
int src_step = src.step / vElemSize, src_offset = src.offset / vElemSize;
int total = src.size().area();
{
// first parallel pass
vector<pair<size_t , const void *> > args;
args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src_step));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src_offset));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
args.push_back( make_pair( sizeof(cl_int) , (void *)&total));
args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum));
args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_data ));
size_t globalThreads[3] = {groupnum * 256, 1, 1};
size_t localThreads[3] = {256, 1, 1};
openCLExecuteKernel(src.clCxt, &arithm_minMax, "arithm_op_minMax", globalThreads, localThreads,
args, -1, -1, "-D T=float -D DEPTH_5 -D vlen=1");
}
{
// run final "serial" kernel to find accumulate results from threads and reset corner counter
vector<pair<size_t , const void *> > args;
args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_data ));
args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum ));
args.push_back( make_pair( sizeof(cl_mem) , (void *)&tozero.data ));
size_t globalThreads[3] = {1, 1, 1};
size_t localThreads[3] = {1, 1, 1};
openCLExecuteKernel(src.clCxt, &imgproc_gftt, "arithm_op_minMax_final", globalThreads, localThreads,
args, -1, -1);
}
}
void cv::ocl::GoodFeaturesToTrackDetector_OCL::operator ()(const oclMat& image, oclMat& corners, const oclMat& mask)
{
CV_Assert(qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0);
CV_Assert(mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()));
ensureSizeIsEnough(image.size(), CV_32F, eig_);
if (useHarrisDetector)
cornerHarris_dxdy(image, eig_, Dx_, Dy_, blockSize, 3, harrisK);
else
cornerMinEigenVal_dxdy(image, eig_, Dx_, Dy_, blockSize, 3);
ensureSizeIsEnough(1,1, CV_32SC1, counter_);
// find max eigenvalue and reset detected counters
minMaxEig_caller(eig_,eig_minmax_,counter_);
// allocate buffer for kernels
int corner_array_size = std::max(1024, static_cast<int>(image.size().area() * 0.05));
if(!use_cpu_sorter)
{ // round to 2^n
unsigned int n=1;
for(n=1;n<(unsigned int)corner_array_size;n<<=1) ;
corner_array_size = (int)n;
ensureSizeIsEnough(1, corner_array_size , CV_32FC2, tmpCorners_);
// set to 0 to be able use bitonic sort on whole 2^n array
tmpCorners_.setTo(0);
}
else
{
ensureSizeIsEnough(1, corner_array_size , CV_32FC2, tmpCorners_);
}
int total = tmpCorners_.cols; // by default the number of corner is full array
vector<DefCorner> tmp(tmpCorners_.cols); // input buffer with corner for HOST part of algorithm
//find points with high eigenvalue and put it into the output array
findCorners_caller(
eig_,
eig_minmax_,
static_cast<float>(qualityLevel),
mask,
tmpCorners_,
counter_);
if(!use_cpu_sorter)
{// sort detected corners on deivce side
sortCorners_caller(tmpCorners_, corner_array_size);
}
else
{// send non-blocking request to read real non-zero number of corners to sort it on the HOST side
openCLVerifyCall(clEnqueueReadBuffer(getClCommandQueue(counter_.clCxt), (cl_mem)counter_.data, CL_FALSE, 0,sizeof(int), &total, 0, NULL, NULL));
}
//blocking read whole corners array (sorted or not sorted)
openCLReadBuffer(tmpCorners_.clCxt,(cl_mem)tmpCorners_.data,&tmp[0],tmpCorners_.cols*sizeof(DefCorner));
if (total == 0)
{// check for trivial case
corners.release();
return;
}
if(use_cpu_sorter)
{// sort detected corners on cpu side.
tmp.resize(total);
cv::sort(tmp,DefCornerCompare());
}
//estimate maximal size of final output array
int total_max = maxCorners > 0 ? std::min(maxCorners, total) : total;
int D2 = (int)ceil(minDistance * minDistance);
// allocate output buffer
vector<Point2f> tmp2;
tmp2.reserve(total_max);
if (minDistance < 1)
{// we have not distance restriction. then just copy with conversion maximal allowed points into output array
for(int i=0;i<total_max && tmp[i].eig>0.0f;++i)
{
tmp2.push_back(Point2f(tmp[i].x,tmp[i].y));
}
}
else
{// we have distance restriction. then start coping to output array from the first element and check distance for each next one
const int cell_size = cvRound(minDistance);
const int grid_width = (image.cols + cell_size - 1) / cell_size;
const int grid_height = (image.rows + cell_size - 1) / cell_size;
std::vector< std::vector<Point2i> > grid(grid_width * grid_height);
for (int i = 0; i < total ; ++i)
{
DefCorner p = tmp[i];
if(p.eig<=0.0f)
break; // condition to stop that is needed for GPU bitonic sort usage.
bool good = true;
int x_cell = static_cast<int>(p.x / cell_size);
int y_cell = static_cast<int>(p.y / cell_size);
int x1 = x_cell - 1;
int y1 = y_cell - 1;
int x2 = x_cell + 1;
int y2 = y_cell + 1;
// boundary check
x1 = std::max(0, x1);
y1 = std::max(0, y1);
x2 = std::min(grid_width - 1, x2);
y2 = std::min(grid_height - 1, y2);
for (int yy = y1; yy <= y2; yy++)
{
for (int xx = x1; xx <= x2; xx++)
{
vector<Point2i>& m = grid[yy * grid_width + xx];
if (m.empty())
continue;
for(size_t j = 0; j < m.size(); j++)
{
int dx = p.x - m[j].x;
int dy = p.y - m[j].y;
if (dx * dx + dy * dy < D2)
{
good = false;
goto break_out_;
}
}
}
}
break_out_:
if(good)
{
grid[y_cell * grid_width + x_cell].push_back(Point2i(p.x,p.y));
tmp2.push_back(Point2f(p.x,p.y));
if (maxCorners > 0 && tmp2.size() == static_cast<size_t>(maxCorners))
break;
}
}
}
int final_size = static_cast<int>(tmp2.size());
if(final_size>0)
corners.upload(Mat(1, final_size, CV_32FC2, &tmp2[0]));
else
corners.release();
}
void cv::ocl::GoodFeaturesToTrackDetector_OCL::downloadPoints(const oclMat &points, vector<Point2f> &points_v)
{
CV_DbgAssert(points.type() == CV_32FC2);
points_v.resize(points.cols);
openCLSafeCall(clEnqueueReadBuffer(
*(cl_command_queue*)getClCommandQueuePtr(),
reinterpret_cast<cl_mem>(points.data),
CL_TRUE,
0,
points.cols * sizeof(Point2f),
&points_v[0],
0,
NULL,
NULL));
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestHyperOctreeDual.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/
// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT
#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeDualGridContourFilter.h"
#include "vtkContourFilter.h"
#include "vtkProperty.h"
#include "vtkDataSetMapper.h"
#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeFractalSource.h"
#include "vtkSphere.h"
#include "vtkCamera.h"
int TestHyperOctreeDual(int argc, char* argv[])
{
// Standard rendering classes
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
vtkTimerLog *timer=vtkTimerLog::New();
// 3D
vtkHyperOctreeFractalSource* source3d = vtkHyperOctreeFractalSource::New();
source3d->SetMaximumNumberOfIterations(17);
source3d->SetMaximumLevel(7);
source3d->SetMinimumLevel(3);
cout<<"update source3d..."<<endl;
timer->StartTimer();
source3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated3d"<<endl;
cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeDualGridContourFilter *contour3d;
contour3d = vtkHyperOctreeDualGridContourFilter::New();
contour3d->SetNumberOfContours(2);
contour3d->SetValue(0,4.5);
contour3d->SetValue(1,10.5);
contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
cout<<"update contour3d..."<<endl;
timer->StartTimer();
contour3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour3d updated"<<endl;
cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut3d = vtkLookupTable::New();
lut3d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
mapper3d->SetScalarRange(0, 17);
vtkActor *actor3d = vtkActor::New();
actor3d->SetMapper(mapper3d);
renderer->AddActor(actor3d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
writer3d->SetFileName("contour3d.vtp");
writer3d->SetDataModeToAscii();
writer3d->Write();
writer3d->Delete();
#endif // #ifdef WRITE_RESULT
// 2D
vtkHyperOctreeFractalSource* source2d = vtkHyperOctreeFractalSource::New();
source2d->SetDimension(2);
source2d->SetMaximumNumberOfIterations(17);
source2d->SetMaximumLevel(7);
source2d->SetMinimumLevel(4);
cout<<"update source2d..."<<endl;
timer->StartTimer();
source2d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated2d"<<endl;
cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut2d = vtkLookupTable::New();
lut2d->SetHueRange (0.667, 0.0);
vtkDataSetMapper *mapper2d = vtkDataSetMapper::New();
mapper2d->SetInputConnection(0,source2d->GetOutputPort(0));
mapper2d->SetLookupTable(lut2d);
mapper2d->SetScalarRange(0, 17);
vtkActor *actor2d = vtkActor::New();
actor2d->SetPosition(2.5,0,0);
actor2d->SetOrientation(180,0,0);
actor2d->SetMapper(mapper2d);
actor2d->GetProperty()->SetRepresentationToWireframe();
actor2d->GetProperty()->SetAmbient(1.0);
actor2d->GetProperty()->SetDiffuse(0.0);
renderer->AddActor(actor2d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
writer2d->SetInputConnection(0,source2d->GetOutputPort(0));
writer2d->SetFileName("dual2d.vtp");
writer2d->SetDataModeToAscii();
writer2d->Write();
writer2d->Delete();
#endif // #ifdef WRITE_RESULT
// Contour using data set API.
vtkHyperOctreeFractalSource* source3dHack = vtkHyperOctreeFractalSource::New();
source3dHack->SetMaximumNumberOfIterations(17);
source3dHack->SetMaximumLevel(7);
source3dHack->SetMinimumLevel(3);
vtkContourFilter *contourDS=vtkContourFilter::New();
contourDS->SetNumberOfContours(2);
contourDS->SetValue(0,4.5);
contourDS->SetValue(1,10.5);
contourDS->SetInputConnection(0,source3dHack->GetOutputPort(0));
cout<<"update contour data set..."<<endl;
timer->StartTimer();
contourDS->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour data set updated"<<endl;
cout<<"contour data set time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lutDS = vtkLookupTable::New();
lutDS->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapperDS = vtkPolyDataMapper::New();
mapperDS->SetInputConnection(0,contourDS->GetOutputPort(0));
mapperDS->SetLookupTable(lutDS);
mapperDS->SetScalarRange(0, 17);
vtkActor *actorDS = vtkActor::New();
actorDS->SetPosition(2.5,2.5,0);
actorDS->SetMapper(mapperDS);
renderer->AddActor(actorDS);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writerDS=vtkXMLPolyDataWriter::New();
writerDS->SetInputConnection(0,contourDS->GetOutputPort(0));
writerDS->SetFileName("contourDS.vtp");
writerDS->SetDataModeToAscii();
writerDS->Write();
writerDS->Delete();
#endif // #ifdef WRITE_RESULT
// Standard testing code.
renderer->SetBackground(0.5,0.5,0.5);
renWin->SetSize(300,300);
vtkCamera *cam=renderer->GetActiveCamera();
renderer->ResetCamera();
cam->Azimuth(180);
cam->Zoom(1.35);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
renderer->Delete();
renWin->Delete();
iren->Delete();
contourDS->Delete();
lutDS->Delete();
mapperDS->Delete();
actorDS->Delete();
source3d->Delete();
source3dHack->Delete();
contour3d->Delete();
mapper3d->Delete();
actor3d->Delete();
lut3d->Delete();
source2d->Delete();
mapper2d->Delete();
actor2d->Delete();
lut2d->Delete();
timer->Delete();
return !retVal;
}
<commit_msg>BUG: This hack is no longer useful.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestHyperOctreeDual.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/
// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT
#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeDualGridContourFilter.h"
#include "vtkContourFilter.h"
#include "vtkProperty.h"
#include "vtkDataSetMapper.h"
#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeFractalSource.h"
#include "vtkSphere.h"
#include "vtkCamera.h"
int TestHyperOctreeDual(int argc, char* argv[])
{
// Standard rendering classes
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
vtkTimerLog *timer=vtkTimerLog::New();
// 3D
vtkHyperOctreeFractalSource* source3d = vtkHyperOctreeFractalSource::New();
source3d->SetMaximumNumberOfIterations(17);
source3d->SetMaximumLevel(7);
source3d->SetMinimumLevel(3);
cout<<"update source3d..."<<endl;
timer->StartTimer();
source3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated3d"<<endl;
cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeDualGridContourFilter *contour3d;
contour3d = vtkHyperOctreeDualGridContourFilter::New();
contour3d->SetNumberOfContours(2);
contour3d->SetValue(0,4.5);
contour3d->SetValue(1,10.5);
contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
cout<<"update contour3d..."<<endl;
timer->StartTimer();
contour3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour3d updated"<<endl;
cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut3d = vtkLookupTable::New();
lut3d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
mapper3d->SetScalarRange(0, 17);
vtkActor *actor3d = vtkActor::New();
actor3d->SetMapper(mapper3d);
renderer->AddActor(actor3d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
writer3d->SetFileName("contour3d.vtp");
writer3d->SetDataModeToAscii();
writer3d->Write();
writer3d->Delete();
#endif // #ifdef WRITE_RESULT
// 2D
vtkHyperOctreeFractalSource* source2d = vtkHyperOctreeFractalSource::New();
source2d->SetDimension(2);
source2d->SetMaximumNumberOfIterations(17);
source2d->SetMaximumLevel(7);
source2d->SetMinimumLevel(4);
cout<<"update source2d..."<<endl;
timer->StartTimer();
source2d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated2d"<<endl;
cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut2d = vtkLookupTable::New();
lut2d->SetHueRange (0.667, 0.0);
vtkDataSetMapper *mapper2d = vtkDataSetMapper::New();
mapper2d->SetInputConnection(0,source2d->GetOutputPort(0));
mapper2d->SetLookupTable(lut2d);
mapper2d->SetScalarRange(0, 17);
vtkActor *actor2d = vtkActor::New();
actor2d->SetPosition(2.5,0,0);
actor2d->SetOrientation(180,0,0);
actor2d->SetMapper(mapper2d);
actor2d->GetProperty()->SetRepresentationToWireframe();
actor2d->GetProperty()->SetAmbient(1.0);
actor2d->GetProperty()->SetDiffuse(0.0);
renderer->AddActor(actor2d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
writer2d->SetInputConnection(0,source2d->GetOutputPort(0));
writer2d->SetFileName("dual2d.vtp");
writer2d->SetDataModeToAscii();
writer2d->Write();
writer2d->Delete();
#endif // #ifdef WRITE_RESULT
vtkContourFilter *contourDS=vtkContourFilter::New();
contourDS->SetNumberOfContours(2);
contourDS->SetValue(0,4.5);
contourDS->SetValue(1,10.5);
contourDS->SetInputConnection(0,source3d->GetOutputPort(0));
cout<<"update contour data set..."<<endl;
timer->StartTimer();
contourDS->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour data set updated"<<endl;
cout<<"contour data set time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lutDS = vtkLookupTable::New();
lutDS->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapperDS = vtkPolyDataMapper::New();
mapperDS->SetInputConnection(0,contourDS->GetOutputPort(0));
mapperDS->SetLookupTable(lutDS);
mapperDS->SetScalarRange(0, 17);
vtkActor *actorDS = vtkActor::New();
actorDS->SetPosition(2.5,2.5,0);
actorDS->SetMapper(mapperDS);
renderer->AddActor(actorDS);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writerDS=vtkXMLPolyDataWriter::New();
writerDS->SetInputConnection(0,contourDS->GetOutputPort(0));
writerDS->SetFileName("contourDS.vtp");
writerDS->SetDataModeToAscii();
writerDS->Write();
writerDS->Delete();
#endif // #ifdef WRITE_RESULT
// Standard testing code.
renderer->SetBackground(0.5,0.5,0.5);
renWin->SetSize(300,300);
vtkCamera *cam=renderer->GetActiveCamera();
renderer->ResetCamera();
cam->Azimuth(180);
cam->Zoom(1.35);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
renderer->Delete();
renWin->Delete();
iren->Delete();
contourDS->Delete();
lutDS->Delete();
mapperDS->Delete();
actorDS->Delete();
source3d->Delete();
contour3d->Delete();
mapper3d->Delete();
actor3d->Delete();
lut3d->Delete();
source2d->Delete();
mapper2d->Delete();
actor2d->Delete();
lut2d->Delete();
timer->Delete();
return !retVal;
}
<|endoftext|> |
<commit_before>#include "clustering/administration/main/import.hpp"
#include "arch/io/network.hpp"
#include "clustering/administration/admin_tracker.hpp"
#include "clustering/administration/auto_reconnect.hpp"
#include "clustering/administration/issues/local.hpp"
#include "clustering/administration/logger.hpp"
#include "clustering/administration/main/initial_join.hpp"
#include "clustering/administration/main/json_import.hpp"
#include "clustering/administration/main/watchable_fields.hpp"
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/network_logger.hpp"
#include "clustering/administration/perfmon_collection_repo.hpp"
#include "clustering/administration/proc_stats.hpp"
#include "clustering/administration/sys_stats.hpp"
#include "extproc/pool.hpp"
#include "http/json.hpp"
#include "rpc/connectivity/multiplexer.hpp"
#include "rpc/directory/read_manager.hpp"
#include "rpc/directory/write_manager.hpp"
#include "rpc/semilattice/semilattice_manager.hpp"
#include "rpc/semilattice/view/field.hpp"
#include "utils.hpp"
bool do_json_importation(const boost::shared_ptr<semilattice_readwrite_view_t<databases_semilattice_metadata_t> > &databases,
const boost::shared_ptr<semilattice_readwrite_view_t<cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > > > &namespaces,
namespace_repo_t<rdb_protocol_t> *repo, json_importer_t *importer,
std::string db_name, std::string table_name, signal_t *interruptor);
bool run_json_import(extproc::spawner_t::info_t *spawner_info, UNUSED io_backender_t *backender, std::set<peer_address_t> joins, int ports_port, int ports_client_port, std::string db_name, std::string table_name, json_importer_t *importer, signal_t *stop_cond) {
guarantee(spawner_info);
extproc::pool_group_t extproc_pool_group(spawner_info, extproc::pool_group_t::DEFAULTS);
machine_id_t machine_id = generate_uuid();
local_issue_tracker_t local_issue_tracker;
thread_pool_log_writer_t log_writer(&local_issue_tracker);
connectivity_cluster_t connectivity_cluster;
message_multiplexer_t message_multiplexer(&connectivity_cluster);
message_multiplexer_t::client_t mailbox_manager_client(&message_multiplexer, 'M');
mailbox_manager_t mailbox_manager(&mailbox_manager_client);
message_multiplexer_t::client_t::run_t mailbox_manager_client_run(&mailbox_manager_client, &mailbox_manager);
message_multiplexer_t::client_t semilattice_manager_client(&message_multiplexer, 'S');
semilattice_manager_t<cluster_semilattice_metadata_t> semilattice_manager_cluster(&semilattice_manager_client, cluster_semilattice_metadata_t());
message_multiplexer_t::client_t::run_t semilattice_manager_client_run(&semilattice_manager_client, &semilattice_manager_cluster);
log_server_t log_server(&mailbox_manager, &log_writer);
stat_manager_t stat_manager(&mailbox_manager);
metadata_change_handler_t<cluster_semilattice_metadata_t> metadata_change_handler(&mailbox_manager, semilattice_manager_cluster.get_root_view());
watchable_variable_t<cluster_directory_metadata_t> our_root_directory_variable(
cluster_directory_metadata_t(
machine_id,
get_ips(),
stat_manager.get_address(),
metadata_change_handler.get_request_mailbox_address(),
log_server.get_business_card(),
PROXY_PEER));
message_multiplexer_t::client_t directory_manager_client(&message_multiplexer, 'D');
// TODO(sam): Are we going to use the write manager at all?
directory_write_manager_t<cluster_directory_metadata_t> directory_write_manager(&directory_manager_client, our_root_directory_variable.get_watchable());
directory_read_manager_t<cluster_directory_metadata_t> directory_read_manager(connectivity_cluster.get_connectivity_service());
message_multiplexer_t::client_t::run_t directory_manager_client_run(&directory_manager_client, &directory_read_manager);
network_logger_t network_logger(
connectivity_cluster.get_me(),
directory_read_manager.get_root_view(),
metadata_field(&cluster_semilattice_metadata_t::machines, semilattice_manager_cluster.get_root_view()));
message_multiplexer_t::run_t message_multiplexer_run(&message_multiplexer);
connectivity_cluster_t::run_t connectivity_cluster_run(&connectivity_cluster, ports_port, &message_multiplexer_run, ports_client_port);
if (0 == ports_port) {
ports_port = connectivity_cluster_run.get_port();
} else {
guarantee(ports_port == connectivity_cluster_run.get_port());
}
logINF("Listening for intracluster traffic on port %d.\n", ports_port);
auto_reconnector_t auto_reconnector(
&connectivity_cluster,
&connectivity_cluster_run,
directory_read_manager.get_root_view()->subview(
field_getter_t<machine_id_t, cluster_directory_metadata_t>(&cluster_directory_metadata_t::machine_id)),
metadata_field(&cluster_semilattice_metadata_t::machines, semilattice_manager_cluster.get_root_view()));
// Skipped field_copier_t, for fun.
admin_tracker_t admin_tracker(
semilattice_manager_cluster.get_root_view(), directory_read_manager.get_root_view());
perfmon_collection_t proc_stats_collection;
perfmon_membership_t proc_stats_membership(&get_global_perfmon_collection(), &proc_stats_collection, "proc");
proc_stats_collector_t proc_stats_collector(&proc_stats_collection);
perfmon_collection_t sys_stats_collection;
perfmon_membership_t sys_stats_membership(&get_global_perfmon_collection(), &sys_stats_collection, "sys");
const char *bs_filepath = "";
sys_stats_collector_t sys_stats_collector(bs_filepath, &sys_stats_collection);
scoped_ptr_t<initial_joiner_t> initial_joiner;
if (!joins.empty()) {
initial_joiner.init(new initial_joiner_t(&connectivity_cluster, &connectivity_cluster_run, joins));
try {
wait_interruptible(initial_joiner->get_ready_signal(), stop_cond);
} catch (interrupted_exc_t) {
return false;
}
}
perfmon_collection_repo_t perfmon_repo(&get_global_perfmon_collection());
// Namespace repos
// (rdb only)
rdb_protocol_t::context_t rdb_ctx(&extproc_pool_group,
NULL,
semilattice_manager_cluster.get_root_view(),
&directory_read_manager,
machine_id);
namespace_repo_t<rdb_protocol_t> rdb_namespace_repo(&mailbox_manager,
directory_read_manager.get_root_view()->subview(
field_getter_t<namespaces_directory_metadata_t<rdb_protocol_t>, cluster_directory_metadata_t>(&cluster_directory_metadata_t::rdb_namespaces)),
&rdb_ctx);
//This is an annoying chicken and egg problem here
rdb_ctx.ns_repo = &rdb_namespace_repo;
// TODO: Handle interrupted exceptions?
return do_json_importation(metadata_field(&cluster_semilattice_metadata_t::databases, semilattice_manager_cluster.get_root_view()),
metadata_field(&cluster_semilattice_metadata_t::rdb_namespaces, semilattice_manager_cluster.get_root_view()),
&rdb_namespace_repo, importer, db_name, table_name, stop_cond);
}
bool get_or_create_namespace(const boost::shared_ptr<semilattice_readwrite_view_t<cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > > > &namespaces,
database_id_t db_id,
std::string table_name,
namespace_id_t *namespace_out) {
namespaces_semilattice_metadata_t<rdb_protocol_t> ns = *namespaces->get();
metadata_searcher_t<namespace_semilattice_metadata_t<rdb_protocol_t> > searcher(&ns.namespaces);
const char *error;
std::map<namespace_id_t, deletable_t<namespace_semilattice_metadata_t<rdb_protocol_t> > >::iterator it = searcher.find_uniq(namespace_predicate_t(table_name, db_id), &error);
if (error != METADATA_SUCCESS) {
*namespace_out = namespace_id_t();
return false;
} else {
*namespace_out = it->first;
return true;
}
}
bool get_or_create_database(const boost::shared_ptr<semilattice_readwrite_view_t<databases_semilattice_metadata_t> > &databases, std::string db_name, database_id_t *db_out) {
std::map<database_id_t, deletable_t<database_semilattice_metadata_t> > dbmap = databases->get().databases;
metadata_searcher_t<database_semilattice_metadata_t> searcher(&dbmap);
const char *error;
std::map<database_id_t, deletable_t<database_semilattice_metadata_t> >::iterator it = searcher.find_uniq(db_name, &error);
if (error != METADATA_SUCCESS) {
// TODO(sam): Actually support _creating_ the database.
*db_out = database_id_t();
return false;
} else {
*db_out = it->first;
return true;
}
}
bool do_json_importation(const boost::shared_ptr<semilattice_readwrite_view_t<databases_semilattice_metadata_t> > &databases,
const boost::shared_ptr<semilattice_readwrite_view_t<cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > > > &namespaces,
namespace_repo_t<rdb_protocol_t> *repo, json_importer_t *importer,
std::string db_name, std::string table_name, signal_t *interruptor) {
database_id_t db_id;
if (!get_or_create_database(databases, db_name, &db_id)) {
return false;
}
namespace_id_t namespace_id;
if (!get_or_create_namespace(namespaces, db_id, table_name, &namespace_id)) {
return false;
}
// TODO(sam): What if construction fails? An exception is thrown?
namespace_repo_t<rdb_protocol_t>::access_t access(repo, namespace_id, interruptor);
UNUSED namespace_interface_t<rdb_protocol_t> *ni = access.get_namespace_if();
// bogus implementation
for (scoped_cJSON_t json; importer->get_json(&json); json.reset(NULL)) {
debugf("json: %s\n", json.Print().c_str());
}
debugf("do_json_importation ... returning bogus success!\n");
return true;
}
<commit_msg>Separate unimplemented branches for METADATA_ERR_NONE.<commit_after>#include "clustering/administration/main/import.hpp"
#include "arch/io/network.hpp"
#include "clustering/administration/admin_tracker.hpp"
#include "clustering/administration/auto_reconnect.hpp"
#include "clustering/administration/issues/local.hpp"
#include "clustering/administration/logger.hpp"
#include "clustering/administration/main/initial_join.hpp"
#include "clustering/administration/main/json_import.hpp"
#include "clustering/administration/main/watchable_fields.hpp"
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/network_logger.hpp"
#include "clustering/administration/perfmon_collection_repo.hpp"
#include "clustering/administration/proc_stats.hpp"
#include "clustering/administration/sys_stats.hpp"
#include "extproc/pool.hpp"
#include "http/json.hpp"
#include "rpc/connectivity/multiplexer.hpp"
#include "rpc/directory/read_manager.hpp"
#include "rpc/directory/write_manager.hpp"
#include "rpc/semilattice/semilattice_manager.hpp"
#include "rpc/semilattice/view/field.hpp"
#include "utils.hpp"
bool do_json_importation(const boost::shared_ptr<semilattice_readwrite_view_t<databases_semilattice_metadata_t> > &databases,
const boost::shared_ptr<semilattice_readwrite_view_t<cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > > > &namespaces,
namespace_repo_t<rdb_protocol_t> *repo, json_importer_t *importer,
std::string db_name, std::string table_name, signal_t *interruptor);
bool run_json_import(extproc::spawner_t::info_t *spawner_info, UNUSED io_backender_t *backender, std::set<peer_address_t> joins, int ports_port, int ports_client_port, std::string db_name, std::string table_name, json_importer_t *importer, signal_t *stop_cond) {
guarantee(spawner_info);
extproc::pool_group_t extproc_pool_group(spawner_info, extproc::pool_group_t::DEFAULTS);
machine_id_t machine_id = generate_uuid();
local_issue_tracker_t local_issue_tracker;
thread_pool_log_writer_t log_writer(&local_issue_tracker);
connectivity_cluster_t connectivity_cluster;
message_multiplexer_t message_multiplexer(&connectivity_cluster);
message_multiplexer_t::client_t mailbox_manager_client(&message_multiplexer, 'M');
mailbox_manager_t mailbox_manager(&mailbox_manager_client);
message_multiplexer_t::client_t::run_t mailbox_manager_client_run(&mailbox_manager_client, &mailbox_manager);
message_multiplexer_t::client_t semilattice_manager_client(&message_multiplexer, 'S');
semilattice_manager_t<cluster_semilattice_metadata_t> semilattice_manager_cluster(&semilattice_manager_client, cluster_semilattice_metadata_t());
message_multiplexer_t::client_t::run_t semilattice_manager_client_run(&semilattice_manager_client, &semilattice_manager_cluster);
log_server_t log_server(&mailbox_manager, &log_writer);
stat_manager_t stat_manager(&mailbox_manager);
metadata_change_handler_t<cluster_semilattice_metadata_t> metadata_change_handler(&mailbox_manager, semilattice_manager_cluster.get_root_view());
watchable_variable_t<cluster_directory_metadata_t> our_root_directory_variable(
cluster_directory_metadata_t(
machine_id,
get_ips(),
stat_manager.get_address(),
metadata_change_handler.get_request_mailbox_address(),
log_server.get_business_card(),
PROXY_PEER));
message_multiplexer_t::client_t directory_manager_client(&message_multiplexer, 'D');
// TODO(sam): Are we going to use the write manager at all?
directory_write_manager_t<cluster_directory_metadata_t> directory_write_manager(&directory_manager_client, our_root_directory_variable.get_watchable());
directory_read_manager_t<cluster_directory_metadata_t> directory_read_manager(connectivity_cluster.get_connectivity_service());
message_multiplexer_t::client_t::run_t directory_manager_client_run(&directory_manager_client, &directory_read_manager);
network_logger_t network_logger(
connectivity_cluster.get_me(),
directory_read_manager.get_root_view(),
metadata_field(&cluster_semilattice_metadata_t::machines, semilattice_manager_cluster.get_root_view()));
message_multiplexer_t::run_t message_multiplexer_run(&message_multiplexer);
connectivity_cluster_t::run_t connectivity_cluster_run(&connectivity_cluster, ports_port, &message_multiplexer_run, ports_client_port);
if (0 == ports_port) {
ports_port = connectivity_cluster_run.get_port();
} else {
guarantee(ports_port == connectivity_cluster_run.get_port());
}
logINF("Listening for intracluster traffic on port %d.\n", ports_port);
auto_reconnector_t auto_reconnector(
&connectivity_cluster,
&connectivity_cluster_run,
directory_read_manager.get_root_view()->subview(
field_getter_t<machine_id_t, cluster_directory_metadata_t>(&cluster_directory_metadata_t::machine_id)),
metadata_field(&cluster_semilattice_metadata_t::machines, semilattice_manager_cluster.get_root_view()));
// Skipped field_copier_t, for fun.
admin_tracker_t admin_tracker(
semilattice_manager_cluster.get_root_view(), directory_read_manager.get_root_view());
perfmon_collection_t proc_stats_collection;
perfmon_membership_t proc_stats_membership(&get_global_perfmon_collection(), &proc_stats_collection, "proc");
proc_stats_collector_t proc_stats_collector(&proc_stats_collection);
perfmon_collection_t sys_stats_collection;
perfmon_membership_t sys_stats_membership(&get_global_perfmon_collection(), &sys_stats_collection, "sys");
const char *bs_filepath = "";
sys_stats_collector_t sys_stats_collector(bs_filepath, &sys_stats_collection);
scoped_ptr_t<initial_joiner_t> initial_joiner;
if (!joins.empty()) {
initial_joiner.init(new initial_joiner_t(&connectivity_cluster, &connectivity_cluster_run, joins));
try {
wait_interruptible(initial_joiner->get_ready_signal(), stop_cond);
} catch (interrupted_exc_t) {
return false;
}
}
perfmon_collection_repo_t perfmon_repo(&get_global_perfmon_collection());
// Namespace repos
// (rdb only)
rdb_protocol_t::context_t rdb_ctx(&extproc_pool_group,
NULL,
semilattice_manager_cluster.get_root_view(),
&directory_read_manager,
machine_id);
namespace_repo_t<rdb_protocol_t> rdb_namespace_repo(&mailbox_manager,
directory_read_manager.get_root_view()->subview(
field_getter_t<namespaces_directory_metadata_t<rdb_protocol_t>, cluster_directory_metadata_t>(&cluster_directory_metadata_t::rdb_namespaces)),
&rdb_ctx);
//This is an annoying chicken and egg problem here
rdb_ctx.ns_repo = &rdb_namespace_repo;
// TODO: Handle interrupted exceptions?
return do_json_importation(metadata_field(&cluster_semilattice_metadata_t::databases, semilattice_manager_cluster.get_root_view()),
metadata_field(&cluster_semilattice_metadata_t::rdb_namespaces, semilattice_manager_cluster.get_root_view()),
&rdb_namespace_repo, importer, db_name, table_name, stop_cond);
}
bool get_or_create_namespace(const boost::shared_ptr<semilattice_readwrite_view_t<cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > > > &namespaces,
database_id_t db_id,
std::string table_name,
namespace_id_t *namespace_out) {
namespaces_semilattice_metadata_t<rdb_protocol_t> ns = *namespaces->get();
metadata_searcher_t<namespace_semilattice_metadata_t<rdb_protocol_t> > searcher(&ns.namespaces);
const char *error;
std::map<namespace_id_t, deletable_t<namespace_semilattice_metadata_t<rdb_protocol_t> > >::iterator it = searcher.find_uniq(namespace_predicate_t(table_name, db_id), &error);
if (error == METADATA_SUCCESS) {
*namespace_out = it->first;
return true;
} else if (error == METADATA_ERR_NONE) {
// TODO(sam): impl this.
*namespace_out = namespace_id_t();
return false;
} else {
*namespace_out = namespace_id_t();
return false;
}
}
bool get_or_create_database(const boost::shared_ptr<semilattice_readwrite_view_t<databases_semilattice_metadata_t> > &databases, std::string db_name, database_id_t *db_out) {
std::map<database_id_t, deletable_t<database_semilattice_metadata_t> > dbmap = databases->get().databases;
metadata_searcher_t<database_semilattice_metadata_t> searcher(&dbmap);
const char *error;
std::map<database_id_t, deletable_t<database_semilattice_metadata_t> >::iterator it = searcher.find_uniq(db_name, &error);
if (error == METADATA_SUCCESS) {
*db_out = it->first;
return true;
} else if (error == METADATA_ERR_NONE) {
// TODO(sam): Impl this.
*db_out = database_id_t();
return false;
} else {
// TODO(sam): Actually support _creating_ the database.
*db_out = database_id_t();
return false;
}
}
bool do_json_importation(const boost::shared_ptr<semilattice_readwrite_view_t<databases_semilattice_metadata_t> > &databases,
const boost::shared_ptr<semilattice_readwrite_view_t<cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > > > &namespaces,
namespace_repo_t<rdb_protocol_t> *repo, json_importer_t *importer,
std::string db_name, std::string table_name, signal_t *interruptor) {
database_id_t db_id;
if (!get_or_create_database(databases, db_name, &db_id)) {
return false;
}
namespace_id_t namespace_id;
if (!get_or_create_namespace(namespaces, db_id, table_name, &namespace_id)) {
return false;
}
// TODO(sam): What if construction fails? An exception is thrown?
namespace_repo_t<rdb_protocol_t>::access_t access(repo, namespace_id, interruptor);
UNUSED namespace_interface_t<rdb_protocol_t> *ni = access.get_namespace_if();
// bogus implementation
for (scoped_cJSON_t json; importer->get_json(&json); json.reset(NULL)) {
debugf("json: %s\n", json.Print().c_str());
}
debugf("do_json_importation ... returning bogus success!\n");
return true;
}
<|endoftext|> |
<commit_before>#include "MacauPrior.h"
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/linop.h>
#include <ios>
using namespace smurff;
MacauPrior::MacauPrior()
: NormalPrior()
{
}
MacauPrior::MacauPrior(std::shared_ptr<BaseSession> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE;
tol = SideInfoConfig::TOL_DEFAULT_VALUE;
enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE;
}
MacauPrior::~MacauPrior()
{
}
void MacauPrior::init()
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_cols(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
std::uint64_t dim = Features->cols();
FtF_plus_beta.resize(dim, dim);
Features->At_mul_A(FtF_plus_beta);
FtF_plus_beta.diagonal().array() += beta_precision;
}
Uhat.resize(this->num_latent(), Features->rows());
Uhat.setZero();
m_beta = std::make_shared<Eigen::MatrixXd>(this->num_latent(), Features->cols());
m_beta->setZero();
m_session->model().setLinkMatrix(m_mode, m_beta);
}
void MacauPrior::update_prior()
{
COUNTER("update_prior");
// residual (Uhat is later overwritten):
Uhat.noalias() = U() - Uhat;
Eigen::MatrixXd BBt = smurff::linop::A_mul_At_combo(*m_beta);
// sampling Gaussian
std::tie(this->mu, this->Lambda) = CondNormalWishart(Uhat, this->mu0, this->b0, this->WI + beta_precision * BBt, this->df + m_beta->cols());
sample_beta();
Features->compute_uhat(Uhat, *m_beta);
if (enable_beta_precision_sampling)
{
double old_beta = beta_precision;
beta_precision = sample_beta_precision(*m_beta, this->Lambda, beta_precision_nu0, beta_precision_mu0);
FtF_plus_beta.diagonal().array() += beta_precision - old_beta;
}
}
const Eigen::VectorXd MacauPrior::getMu(int n) const
{
return this->mu + Uhat.col(n);
}
void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
const int num_feat = m_beta->cols();
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
HyperU = (U() + MvNormal_prec(Lambda, num_cols())).colwise() - mu;
Ft_y = Features->A_mul_B(HyperU);
HyperU2 = MvNormal_prec(Lambda, num_feat);
#pragma omp parallel for schedule(static)
for (int f = 0; f < num_feat; f++)
{
for (int d = 0; d < num_latent(); d++)
{
Ft_y(d, f) += std::sqrt(beta_precision) * HyperU2(d, f);
}
}
}
void MacauPrior::sample_beta()
{
COUNTER("sample_beta");
if (use_FtF)
sample_beta_direct();
else
sample_beta_cg();
}
void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a)
{
//FIXME: remove old code
// old code
// side information
Features = side_info_a;
beta_precision = beta_precision_a;
tol = tolerance_a;
use_FtF = direct_a;
enable_beta_precision_sampling = enable_beta_precision_sampling_a;
throw_on_cholesky_error = throw_on_cholesky_error_a;
// new code
// side information
side_info_values.push_back(side_info_a);
beta_precision_values.push_back(beta_precision_a);
tol_values.push_back(tolerance_a);
direct_values.push_back(direct_a);
enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a);
throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a);
// other code
// Hyper-prior for beta_precision (mean 1.0, var of 1e+3):
beta_precision_mu0 = 1.0;
beta_precision_nu0 = 1e-3;
}
bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const
{
NormalPrior::save(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, *m_beta);
return true;
}
void MacauPrior::restore(std::shared_ptr<const StepFile> sf)
{
NormalPrior::restore(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, *m_beta);
}
std::ostream& MacauPrior::info(std::ostream &os, std::string indent)
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: ";
Features->print(os);
os << indent << " Method: ";
if (use_FtF)
{
os << "Cholesky Decomposition";
double needs_gb = (double)Features->cols() / 1024. * (double)Features->cols() / 1024. / 1024.;
if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)";
os << std::endl;
} else {
os << "CG Solver" << std::endl;
os << indent << " with tolerance: " << std::scientific << tol << std::fixed << std::endl;
}
os << indent << " BetaPrecision: " << beta_precision << std::endl;
return os;
}
std::ostream& MacauPrior::status(std::ostream &os, std::string indent) const
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "blockcg iter = " << blockcg_iter << std::endl;
os << indent << "FtF_plus_beta= " << FtF_plus_beta.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << m_beta->norm() << std::endl;
os << indent << "beta_precision = " << beta_precision << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
// direct method
void MacauPrior::sample_beta_direct()
{
this->compute_Ft_y_omp(Ft_y);
*m_beta = FtF_plus_beta.llt().solve(Ft_y.transpose()).transpose();
}
std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
const int D = beta.rows();
Eigen::MatrixXd BB(D, D);
smurff::linop::A_mul_At_combo(BB, beta);
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace());
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
void MacauPrior::sample_beta_cg()
{
Eigen::MatrixXd Ft_y;
this->compute_Ft_y_omp(Ft_y);
blockcg_iter = Features->solve_blockcg(*m_beta, beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error);
}
<commit_msg>ENH: print CG info on one line<commit_after>#include "MacauPrior.h"
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/linop.h>
#include <ios>
using namespace smurff;
MacauPrior::MacauPrior()
: NormalPrior()
{
}
MacauPrior::MacauPrior(std::shared_ptr<BaseSession> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE;
tol = SideInfoConfig::TOL_DEFAULT_VALUE;
enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE;
}
MacauPrior::~MacauPrior()
{
}
void MacauPrior::init()
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_cols(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
std::uint64_t dim = Features->cols();
FtF_plus_beta.resize(dim, dim);
Features->At_mul_A(FtF_plus_beta);
FtF_plus_beta.diagonal().array() += beta_precision;
}
Uhat.resize(this->num_latent(), Features->rows());
Uhat.setZero();
m_beta = std::make_shared<Eigen::MatrixXd>(this->num_latent(), Features->cols());
m_beta->setZero();
m_session->model().setLinkMatrix(m_mode, m_beta);
}
void MacauPrior::update_prior()
{
COUNTER("update_prior");
// residual (Uhat is later overwritten):
Uhat.noalias() = U() - Uhat;
Eigen::MatrixXd BBt = smurff::linop::A_mul_At_combo(*m_beta);
// sampling Gaussian
std::tie(this->mu, this->Lambda) = CondNormalWishart(Uhat, this->mu0, this->b0, this->WI + beta_precision * BBt, this->df + m_beta->cols());
sample_beta();
Features->compute_uhat(Uhat, *m_beta);
if (enable_beta_precision_sampling)
{
double old_beta = beta_precision;
beta_precision = sample_beta_precision(*m_beta, this->Lambda, beta_precision_nu0, beta_precision_mu0);
FtF_plus_beta.diagonal().array() += beta_precision - old_beta;
}
}
const Eigen::VectorXd MacauPrior::getMu(int n) const
{
return this->mu + Uhat.col(n);
}
void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
const int num_feat = m_beta->cols();
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
HyperU = (U() + MvNormal_prec(Lambda, num_cols())).colwise() - mu;
Ft_y = Features->A_mul_B(HyperU);
HyperU2 = MvNormal_prec(Lambda, num_feat);
#pragma omp parallel for schedule(static)
for (int f = 0; f < num_feat; f++)
{
for (int d = 0; d < num_latent(); d++)
{
Ft_y(d, f) += std::sqrt(beta_precision) * HyperU2(d, f);
}
}
}
void MacauPrior::sample_beta()
{
COUNTER("sample_beta");
if (use_FtF)
sample_beta_direct();
else
sample_beta_cg();
}
void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a)
{
//FIXME: remove old code
// old code
// side information
Features = side_info_a;
beta_precision = beta_precision_a;
tol = tolerance_a;
use_FtF = direct_a;
enable_beta_precision_sampling = enable_beta_precision_sampling_a;
throw_on_cholesky_error = throw_on_cholesky_error_a;
// new code
// side information
side_info_values.push_back(side_info_a);
beta_precision_values.push_back(beta_precision_a);
tol_values.push_back(tolerance_a);
direct_values.push_back(direct_a);
enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a);
throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a);
// other code
// Hyper-prior for beta_precision (mean 1.0, var of 1e+3):
beta_precision_mu0 = 1.0;
beta_precision_nu0 = 1e-3;
}
bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const
{
NormalPrior::save(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, *m_beta);
return true;
}
void MacauPrior::restore(std::shared_ptr<const StepFile> sf)
{
NormalPrior::restore(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, *m_beta);
}
std::ostream& MacauPrior::info(std::ostream &os, std::string indent)
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: ";
Features->print(os);
os << indent << " Method: ";
if (use_FtF)
{
os << "Cholesky Decomposition";
double needs_gb = (double)Features->cols() / 1024. * (double)Features->cols() / 1024. / 1024.;
if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)";
os << std::endl;
} else {
os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl;
}
os << indent << " BetaPrecision: " << beta_precision << std::endl;
return os;
}
std::ostream& MacauPrior::status(std::ostream &os, std::string indent) const
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "blockcg iter = " << blockcg_iter << std::endl;
os << indent << "FtF_plus_beta= " << FtF_plus_beta.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << m_beta->norm() << std::endl;
os << indent << "beta_precision = " << beta_precision << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
// direct method
void MacauPrior::sample_beta_direct()
{
this->compute_Ft_y_omp(Ft_y);
*m_beta = FtF_plus_beta.llt().solve(Ft_y.transpose()).transpose();
}
std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
const int D = beta.rows();
Eigen::MatrixXd BB(D, D);
smurff::linop::A_mul_At_combo(BB, beta);
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace());
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
void MacauPrior::sample_beta_cg()
{
Eigen::MatrixXd Ft_y;
this->compute_Ft_y_omp(Ft_y);
blockcg_iter = Features->solve_blockcg(*m_beta, beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error);
}
<|endoftext|> |
<commit_before>#include "TensorUtils.h"
#include <SmurffCpp/Utils/Error.h>
Eigen::MatrixXd smurff::tensor_utils::dense_to_eigen(const smurff::TensorConfig& tensorConfig)
{
if(!tensorConfig.isDense())
THROWERROR("tensor config should be dense");
if(tensorConfig.getNModes() != 2)
THROWERROR("Invalid number of dimensions. Tensor can not be converted to matrix.");
std::vector<double> Yvalues = tensorConfig.getValues(); //eigen map can not take const values pointer. have to make copy
return Eigen::Map<Eigen::MatrixXd>(Yvalues.data(), tensorConfig.getDims()[0], tensorConfig.getDims()[1]);
}
Eigen::MatrixXd smurff::tensor_utils::dense_to_eigen(smurff::TensorConfig& tensorConfig)
{
const smurff::TensorConfig& tc = tensorConfig;
return smurff::tensor_utils::dense_to_eigen(tc);
}
template<>
Eigen::SparseMatrix<double> smurff::tensor_utils::sparse_to_eigen<const smurff::TensorConfig>(const smurff::TensorConfig& tensorConfig)
{
if(tensorConfig.isDense())
THROWERROR("tensor config should be sparse");
if(tensorConfig.getNModes() != 2)
THROWERROR("Invalid number of dimensions. Tensor can not be converted to matrix.");
std::shared_ptr<std::vector<std::uint32_t> > columnsPtr = tensorConfig.getColumnsPtr();
std::shared_ptr<std::vector<double> > valuesPtr = tensorConfig.getValuesPtr();
Eigen::SparseMatrix<double> out(tensorConfig.getDims()[0], tensorConfig.getDims()[1]);
std::vector<Eigen::Triplet<double> > triplets;
for(std::uint64_t i = 0; i < tensorConfig.getNNZ(); i++)
{
double val = valuesPtr->operator[](i);
std::uint32_t row = columnsPtr->operator[](i);
std::uint32_t col = columnsPtr->operator[](i + tensorConfig.getNNZ());
triplets.push_back(Eigen::Triplet<double>(row, col, val));
}
out.setFromTriplets(triplets.begin(), triplets.end());
return out;
}
template<>
Eigen::SparseMatrix<double> smurff::tensor_utils::sparse_to_eigen<smurff::TensorConfig>(smurff::TensorConfig& tensorConfig)
{
return smurff::tensor_utils::sparse_to_eigen<const smurff::TensorConfig>(tensorConfig);
}
smurff::MatrixConfig smurff::tensor_utils::tensor_to_matrix(const smurff::TensorConfig& tensorConfig)
{
if(tensorConfig.getNModes() != 2)
THROWERROR("Invalid number of dimentions. Tensor can not be converted to matrix.");
if(tensorConfig.isDense())
{
return smurff::MatrixConfig(tensorConfig.getDims()[0], tensorConfig.getDims()[1],
tensorConfig.getValues(),
tensorConfig.getNoiseConfig());
}
else if(tensorConfig.isBinary())
{
return smurff::MatrixConfig(tensorConfig.getDims()[0], tensorConfig.getDims()[1],
tensorConfig.getColumns(),
tensorConfig.getNoiseConfig(),
tensorConfig.isScarce());
}
else
{
return smurff::MatrixConfig(tensorConfig.getDims()[0], tensorConfig.getDims()[1],
tensorConfig.getColumns(), tensorConfig.getValues(),
tensorConfig.getNoiseConfig(),
tensorConfig.isScarce());
}
}
std::ostream& smurff::tensor_utils::operator << (std::ostream& os, const TensorConfig& tc)
{
const std::vector<double>& values = tc.getValues();
const std::vector<std::uint32_t>& columns = tc.getColumns();
os << "columns: " << std::endl;
for(std::uint64_t i = 0; i < columns.size(); i++)
os << columns[i] << ", ";
os << std::endl;
os << "values: " << std::endl;
for(std::uint64_t i = 0; i < values.size(); i++)
os << values[i] << ", ";
os << std::endl;
if(tc.getNModes() == 2)
{
os << "dims: " << tc.getDims()[0] << " " << tc.getDims()[1] << std::endl;
Eigen::SparseMatrix<double> X(tc.getDims()[0], tc.getDims()[1]);
std::vector<Eigen::Triplet<double> > triplets;
for(std::uint64_t i = 0; i < tc.getNNZ(); i++)
triplets.push_back(Eigen::Triplet<double>(columns[i], columns[i + tc.getNNZ()], values[i]));
os << "NTriplets: " << triplets.size() << std::endl;
X.setFromTriplets(triplets.begin(), triplets.end());
os << X << std::endl;
}
return os;
}
Eigen::MatrixXd smurff::tensor_utils::slice( const TensorConfig& tensorConfig
, const std::array<std::uint64_t, 2>& fixedDims
, const std::unordered_map<std::uint64_t, std::uint32_t>& dimCoords)
{
if (fixedDims[0] == fixedDims[1])
THROWERROR("fixedDims should contain 2 unique dimension numbers");
for (const std::uint64_t& fd : fixedDims)
if (fd > tensorConfig.getNModes() - 1)
THROWERROR("fixedDims should contain only valid for tensorConfig dimension numbers");
if (dimCoords.size() != (tensorConfig.getNModes() - 2))
THROWERROR("dimsCoords.size() should be the same as tensorConfig.getNModes() - 2");
for (const std::unordered_map<std::uint64_t, std::uint32_t>::value_type& dc : dimCoords)
{
if (dc.first == fixedDims[0] || dc.first == fixedDims[1])
THROWERROR("dimCoords and fixedDims should not intersect");
if (dc.first >= tensorConfig.getNModes())
THROWERROR("dimCoords should contain only valid for tensorConfig dimension numbers");
if (dc.second >= tensorConfig.getDims()[dc.first])
THROWERROR("dimCoords should contain valid coord values for corresponding dimensions");
}
std::unordered_map<std::uint64_t, std::vector<std::uint32_t>::const_iterator> dimColumns;
for (const std::unordered_map<std::uint64_t, std::uint32_t>::value_type& dc : dimCoords)
{
std::size_t dimOffset = dc.first * tensorConfig.getValues().size();
dimColumns[dc.first] = tensorConfig.getColumns().begin() + dimOffset;
}
Eigen::MatrixXd sliceMatrix(tensorConfig.getDims()[fixedDims[0]], tensorConfig.getDims()[fixedDims[1]]);
for (std::size_t i = 0; i < tensorConfig.getValues().size(); i++)
{
bool dimCoordsMatchColumns =
std::accumulate( dimCoords.begin()
, dimCoords.end()
, true
, [&](bool acc, const std::unordered_map<std::uint64_t, std::uint32_t>::value_type& dc)
{
return acc & (*(dimColumns[dc.first] + i) == dc.second);
}
);
if (dimCoordsMatchColumns)
{
std::uint32_t d0_coord =
tensorConfig.getColumns()[fixedDims[0] * tensorConfig.getValues().size() + i];
std::uint32_t d1_coord =
tensorConfig.getColumns()[fixedDims[1] * tensorConfig.getValues().size() + i];
sliceMatrix(d0_coord, d1_coord) = tensorConfig.getValues()[i];
}
}
return sliceMatrix;
}
<commit_msg>add missing include<commit_after>#include <numeric>
#include "TensorUtils.h"
#include <SmurffCpp/Utils/Error.h>
Eigen::MatrixXd smurff::tensor_utils::dense_to_eigen(const smurff::TensorConfig& tensorConfig)
{
if(!tensorConfig.isDense())
THROWERROR("tensor config should be dense");
if(tensorConfig.getNModes() != 2)
THROWERROR("Invalid number of dimensions. Tensor can not be converted to matrix.");
std::vector<double> Yvalues = tensorConfig.getValues(); //eigen map can not take const values pointer. have to make copy
return Eigen::Map<Eigen::MatrixXd>(Yvalues.data(), tensorConfig.getDims()[0], tensorConfig.getDims()[1]);
}
Eigen::MatrixXd smurff::tensor_utils::dense_to_eigen(smurff::TensorConfig& tensorConfig)
{
const smurff::TensorConfig& tc = tensorConfig;
return smurff::tensor_utils::dense_to_eigen(tc);
}
template<>
Eigen::SparseMatrix<double> smurff::tensor_utils::sparse_to_eigen<const smurff::TensorConfig>(const smurff::TensorConfig& tensorConfig)
{
if(tensorConfig.isDense())
THROWERROR("tensor config should be sparse");
if(tensorConfig.getNModes() != 2)
THROWERROR("Invalid number of dimensions. Tensor can not be converted to matrix.");
std::shared_ptr<std::vector<std::uint32_t> > columnsPtr = tensorConfig.getColumnsPtr();
std::shared_ptr<std::vector<double> > valuesPtr = tensorConfig.getValuesPtr();
Eigen::SparseMatrix<double> out(tensorConfig.getDims()[0], tensorConfig.getDims()[1]);
std::vector<Eigen::Triplet<double> > triplets;
for(std::uint64_t i = 0; i < tensorConfig.getNNZ(); i++)
{
double val = valuesPtr->operator[](i);
std::uint32_t row = columnsPtr->operator[](i);
std::uint32_t col = columnsPtr->operator[](i + tensorConfig.getNNZ());
triplets.push_back(Eigen::Triplet<double>(row, col, val));
}
out.setFromTriplets(triplets.begin(), triplets.end());
return out;
}
template<>
Eigen::SparseMatrix<double> smurff::tensor_utils::sparse_to_eigen<smurff::TensorConfig>(smurff::TensorConfig& tensorConfig)
{
return smurff::tensor_utils::sparse_to_eigen<const smurff::TensorConfig>(tensorConfig);
}
smurff::MatrixConfig smurff::tensor_utils::tensor_to_matrix(const smurff::TensorConfig& tensorConfig)
{
if(tensorConfig.getNModes() != 2)
THROWERROR("Invalid number of dimentions. Tensor can not be converted to matrix.");
if(tensorConfig.isDense())
{
return smurff::MatrixConfig(tensorConfig.getDims()[0], tensorConfig.getDims()[1],
tensorConfig.getValues(),
tensorConfig.getNoiseConfig());
}
else if(tensorConfig.isBinary())
{
return smurff::MatrixConfig(tensorConfig.getDims()[0], tensorConfig.getDims()[1],
tensorConfig.getColumns(),
tensorConfig.getNoiseConfig(),
tensorConfig.isScarce());
}
else
{
return smurff::MatrixConfig(tensorConfig.getDims()[0], tensorConfig.getDims()[1],
tensorConfig.getColumns(), tensorConfig.getValues(),
tensorConfig.getNoiseConfig(),
tensorConfig.isScarce());
}
}
std::ostream& smurff::tensor_utils::operator << (std::ostream& os, const TensorConfig& tc)
{
const std::vector<double>& values = tc.getValues();
const std::vector<std::uint32_t>& columns = tc.getColumns();
os << "columns: " << std::endl;
for(std::uint64_t i = 0; i < columns.size(); i++)
os << columns[i] << ", ";
os << std::endl;
os << "values: " << std::endl;
for(std::uint64_t i = 0; i < values.size(); i++)
os << values[i] << ", ";
os << std::endl;
if(tc.getNModes() == 2)
{
os << "dims: " << tc.getDims()[0] << " " << tc.getDims()[1] << std::endl;
Eigen::SparseMatrix<double> X(tc.getDims()[0], tc.getDims()[1]);
std::vector<Eigen::Triplet<double> > triplets;
for(std::uint64_t i = 0; i < tc.getNNZ(); i++)
triplets.push_back(Eigen::Triplet<double>(columns[i], columns[i + tc.getNNZ()], values[i]));
os << "NTriplets: " << triplets.size() << std::endl;
X.setFromTriplets(triplets.begin(), triplets.end());
os << X << std::endl;
}
return os;
}
Eigen::MatrixXd smurff::tensor_utils::slice( const TensorConfig& tensorConfig
, const std::array<std::uint64_t, 2>& fixedDims
, const std::unordered_map<std::uint64_t, std::uint32_t>& dimCoords)
{
if (fixedDims[0] == fixedDims[1])
THROWERROR("fixedDims should contain 2 unique dimension numbers");
for (const std::uint64_t& fd : fixedDims)
if (fd > tensorConfig.getNModes() - 1)
THROWERROR("fixedDims should contain only valid for tensorConfig dimension numbers");
if (dimCoords.size() != (tensorConfig.getNModes() - 2))
THROWERROR("dimsCoords.size() should be the same as tensorConfig.getNModes() - 2");
for (const std::unordered_map<std::uint64_t, std::uint32_t>::value_type& dc : dimCoords)
{
if (dc.first == fixedDims[0] || dc.first == fixedDims[1])
THROWERROR("dimCoords and fixedDims should not intersect");
if (dc.first >= tensorConfig.getNModes())
THROWERROR("dimCoords should contain only valid for tensorConfig dimension numbers");
if (dc.second >= tensorConfig.getDims()[dc.first])
THROWERROR("dimCoords should contain valid coord values for corresponding dimensions");
}
std::unordered_map<std::uint64_t, std::vector<std::uint32_t>::const_iterator> dimColumns;
for (const std::unordered_map<std::uint64_t, std::uint32_t>::value_type& dc : dimCoords)
{
std::size_t dimOffset = dc.first * tensorConfig.getValues().size();
dimColumns[dc.first] = tensorConfig.getColumns().begin() + dimOffset;
}
Eigen::MatrixXd sliceMatrix(tensorConfig.getDims()[fixedDims[0]], tensorConfig.getDims()[fixedDims[1]]);
for (std::size_t i = 0; i < tensorConfig.getValues().size(); i++)
{
bool dimCoordsMatchColumns =
std::accumulate( dimCoords.begin()
, dimCoords.end()
, true
, [&](bool acc, const std::unordered_map<std::uint64_t, std::uint32_t>::value_type& dc)
{
return acc & (*(dimColumns[dc.first] + i) == dc.second);
}
);
if (dimCoordsMatchColumns)
{
std::uint32_t d0_coord =
tensorConfig.getColumns()[fixedDims[0] * tensorConfig.getValues().size() + i];
std::uint32_t d1_coord =
tensorConfig.getColumns()[fixedDims[1] * tensorConfig.getValues().size() + i];
sliceMatrix(d0_coord, d1_coord) = tensorConfig.getValues()[i];
}
}
return sliceMatrix;
}
<|endoftext|> |
<commit_before>/* Sirikata Utilities -- Sirikata Logging Utility
* Logging.hpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SIRIKATA_LOGGING_HPP_
#define _SIRIKATA_LOGGING_HPP_
extern "C" SIRIKATA_EXPORT void* Sirikata_Logging_OptionValue_defaultLevel;
extern "C" SIRIKATA_EXPORT void* Sirikata_Logging_OptionValue_atLeastLevel;
extern "C" SIRIKATA_EXPORT void* Sirikata_Logging_OptionValue_moduleLevel;
namespace Sirikata {
class OptionValue;
namespace Logging {
enum LOGGING_LEVEL {
fatal=1,
error=8,
warning=64,
warn=warning,
info=512,
debug=4096,
detailed=8192,
insane=32768
};
SIRIKATA_FUNCTION_EXPORT const String& LogModuleString(const char* base);
SIRIKATA_FUNCTION_EXPORT const char* LogLevelString(LOGGING_LEVEL lvl, const char* lvl_as_string);
// Public so the macros work efficiently instead of another call
extern "C" SIRIKATA_EXPORT std::ostream* SirikataLogStream;
SIRIKATA_FUNCTION_EXPORT void setLogStream(std::ostream* logfs);
SIRIKATA_FUNCTION_EXPORT void finishLog();
} }
#if 1
# ifdef DEBUG_ALL
# define SILOGP(module,lvl) true
# else
//needs to use unsafeAs because the LOGGING_LEVEL typeinfos are not preserved across dll lines
# define SILOGP(module,lvl) \
( \
std::max( reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_atLeastLevel)->unsafeAs<Sirikata::Logging::LOGGING_LEVEL>(), \
reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_defaultLevel)->unsafeAs<Sirikata::Logging::LOGGING_LEVEL>()) \
>=Sirikata::Logging::lvl && \
( (reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().find(#module)==reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().end() && \
reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_defaultLevel)->unsafeAs<Sirikata::Logging::LOGGING_LEVEL>()>=(Sirikata::Logging::lvl)) \
|| (reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().find(#module)!=reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().end() && \
reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >()[#module]>=Sirikata::Logging::lvl)))
# endif
# define SILOGNOCR(module,lvl,value) \
do { \
if (SILOGP(module,lvl)) { \
std::ostringstream __log_stream; \
__log_stream << value; \
(*Sirikata::Logging::SirikataLogStream) << __log_stream.str(); \
} \
} while (0)
# define SILOGBARE(module,lvl,value) SILOGNOCR(module,lvl,value << std::endl)
#else
# define SILOGP(module,lvl) false
# define SILOGNOCR(module,lvl,value)
# define SILOGBARE(module,lvl,value)
#endif
#define SILOG(module,lvl,value) SILOGBARE(module,lvl, "[" << Sirikata::Logging::LogModuleString(#module) << "] " << Sirikata::Logging::LogLevelString(Sirikata::Logging::lvl, #lvl) << ": " << value)
#if SIRIKATA_PLATFORM == PLATFORM_LINUX
// FIXME only works on GCC
#define NOT_IMPLEMENTED_MSG (Sirikata::String("Not implemented reached in ") + Sirikata::String(__PRETTY_FUNCTION__))
#else
#define NOT_IMPLEMENTED_MSG (Sirikata::String("NOT IMPLEMENTED"))
#endif
#define NOT_IMPLEMENTED(module) SILOG(module,error,NOT_IMPLEMENTED_MSG)
#if SIRIKATA_PLATFORM == PLATFORM_LINUX
// FIXME only works on GCC
#define DEPRECATED_MSG (Sirikata::String("DEPRECATED reached in ") + Sirikata::String(__PRETTY_FUNCTION__))
#else
#define DEPRECATED_MSG (Sirikata::String("DEPRECATED"))
#endif
#define DEPRECATED(module) SILOG(module,warning,DEPRECATED_MSG)
#endif
<commit_msg>Put logging endl with the output stream instead of the one used to collect output into a single stream. Fixes #419.<commit_after>/* Sirikata Utilities -- Sirikata Logging Utility
* Logging.hpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SIRIKATA_LOGGING_HPP_
#define _SIRIKATA_LOGGING_HPP_
extern "C" SIRIKATA_EXPORT void* Sirikata_Logging_OptionValue_defaultLevel;
extern "C" SIRIKATA_EXPORT void* Sirikata_Logging_OptionValue_atLeastLevel;
extern "C" SIRIKATA_EXPORT void* Sirikata_Logging_OptionValue_moduleLevel;
namespace Sirikata {
class OptionValue;
namespace Logging {
enum LOGGING_LEVEL {
fatal=1,
error=8,
warning=64,
warn=warning,
info=512,
debug=4096,
detailed=8192,
insane=32768
};
SIRIKATA_FUNCTION_EXPORT const String& LogModuleString(const char* base);
SIRIKATA_FUNCTION_EXPORT const char* LogLevelString(LOGGING_LEVEL lvl, const char* lvl_as_string);
// Public so the macros work efficiently instead of another call
extern "C" SIRIKATA_EXPORT std::ostream* SirikataLogStream;
SIRIKATA_FUNCTION_EXPORT void setLogStream(std::ostream* logfs);
SIRIKATA_FUNCTION_EXPORT void finishLog();
} }
#if 1
# ifdef DEBUG_ALL
# define SILOGP(module,lvl) true
# else
//needs to use unsafeAs because the LOGGING_LEVEL typeinfos are not preserved across dll lines
# define SILOGP(module,lvl) \
( \
std::max( reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_atLeastLevel)->unsafeAs<Sirikata::Logging::LOGGING_LEVEL>(), \
reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_defaultLevel)->unsafeAs<Sirikata::Logging::LOGGING_LEVEL>()) \
>=Sirikata::Logging::lvl && \
( (reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().find(#module)==reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().end() && \
reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_defaultLevel)->unsafeAs<Sirikata::Logging::LOGGING_LEVEL>()>=(Sirikata::Logging::lvl)) \
|| (reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().find(#module)!=reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >().end() && \
reinterpret_cast<Sirikata::OptionValue*>(Sirikata_Logging_OptionValue_moduleLevel)->unsafeAs<std::tr1::unordered_map<std::string,Sirikata::Logging::LOGGING_LEVEL> >()[#module]>=Sirikata::Logging::lvl)))
# endif
# define SILOGNOCR(module,lvl,value) \
do { \
if (SILOGP(module,lvl)) { \
std::ostringstream __log_stream; \
__log_stream << value; \
(*Sirikata::Logging::SirikataLogStream) << __log_stream.str() << std::endl; \
} \
} while (0)
# define SILOGBARE(module,lvl,value) SILOGNOCR(module,lvl,value)
#else
# define SILOGP(module,lvl) false
# define SILOGNOCR(module,lvl,value)
# define SILOGBARE(module,lvl,value)
#endif
#define SILOG(module,lvl,value) SILOGBARE(module,lvl, "[" << Sirikata::Logging::LogModuleString(#module) << "] " << Sirikata::Logging::LogLevelString(Sirikata::Logging::lvl, #lvl) << ": " << value)
#if SIRIKATA_PLATFORM == PLATFORM_LINUX
// FIXME only works on GCC
#define NOT_IMPLEMENTED_MSG (Sirikata::String("Not implemented reached in ") + Sirikata::String(__PRETTY_FUNCTION__))
#else
#define NOT_IMPLEMENTED_MSG (Sirikata::String("NOT IMPLEMENTED"))
#endif
#define NOT_IMPLEMENTED(module) SILOG(module,error,NOT_IMPLEMENTED_MSG)
#if SIRIKATA_PLATFORM == PLATFORM_LINUX
// FIXME only works on GCC
#define DEPRECATED_MSG (Sirikata::String("DEPRECATED reached in ") + Sirikata::String(__PRETTY_FUNCTION__))
#else
#define DEPRECATED_MSG (Sirikata::String("DEPRECATED"))
#endif
#define DEPRECATED(module) SILOG(module,warning,DEPRECATED_MSG)
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include <caf/actor.hpp>
#include <caf/actor_system.hpp>
#include <caf/event_based_actor.hpp>
namespace vast::detail {
template <class Container>
caf::actor spawn_container_source(caf::actor_system& system, caf::actor dst,
Container elements) {
using namespace caf;
struct outer_state {
/// Name of this actor in log events.
const char* name = "container-source";
};
auto f = [](stateful_actor<outer_state>* self, actor dest, Container xs) {
using iterator = typename Container::iterator;
using value_type = typename Container::value_type;
struct state {
Container xs;
iterator i;
iterator e;
};
self->make_source(
dest,
[&](state& st) {
st.xs = std::move(xs);
st.i = st.xs.begin();
st.e = st.xs.end();
},
[](state& st, downstream<value_type>& out, size_t num) {
size_t pushed = 0;
while (pushed < num && st.i != st.e) {
out.push(std::move(*st.i++));
++pushed;
}
},
[](const state& st) {
return st.i == st.e;
}
);
};
return system.spawn(f, std::move(dst), std::move(elements));
}
} // namespace vast::detail
<commit_msg>Support typed actors<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include <caf/actor.hpp>
#include <caf/actor_system.hpp>
#include <caf/event_based_actor.hpp>
namespace vast::detail {
template <class Handle, class Container>
caf::actor spawn_container_source(caf::actor_system& system, Handle dst,
Container elements) {
using namespace caf;
struct outer_state {
/// Name of this actor in log events.
const char* name = "container-source";
};
auto f = [](stateful_actor<outer_state>* self, Handle dest, Container xs) {
using iterator = typename Container::iterator;
using value_type = typename Container::value_type;
struct state {
Container xs;
iterator i;
iterator e;
};
self->make_source(
dest,
[&](state& st) {
st.xs = std::move(xs);
st.i = st.xs.begin();
st.e = st.xs.end();
},
[](state& st, downstream<value_type>& out, size_t num) {
size_t pushed = 0;
while (pushed < num && st.i != st.e) {
out.push(std::move(*st.i++));
++pushed;
}
},
[](const state& st) {
return st.i == st.e;
}
);
};
return system.spawn(f, std::move(dst), std::move(elements));
}
} // namespace vast::detail
<|endoftext|> |
<commit_before>#include "Player.hpp"
PCWSTR szTitle = L"BasicPlayback";
PCWSTR szWindowClass = L"MFBASICPLAYBACK";
HINSTANCE g_hInstance; // current instance
BOOL g_bRepaintClient = TRUE; // Repaint the application client area?
CPlayer *g_pPlayer = NULL; // Global player object.
// Note: After WM_CREATE is processed, g_pPlayer remains valid until the
// window is destroyed.
// Forward declarations of functions included in this code module:
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK OpenUrlDialogProc(HWND, UINT, WPARAM, LPARAM);
void NotifyError(HWND hwnd, const WCHAR *sErrorMessage, HRESULT hr);
void UpdateUI(HWND hwnd, PlayerState state);
HRESULT AllocGetWindowText(HWND hwnd, WCHAR **pszText, DWORD *pcchLen);
// Message handlers
LRESULT OnCreateWindow(HWND hwnd);
void OnFileOpen(HWND hwnd);
void OnOpenURL(HWND hwnd);
void OnPlayerEvent(HWND hwnd, WPARAM pUnkPtr);
void OnPaint(HWND hwnd);
void OnResize(WORD width, WORD height);
void OnKeyPress(WPARAM key);
// OpenUrlDialogInfo: Contains data passed to the "Open URL" dialog proc.
struct OpenUrlDialogInfo
{
WCHAR *pszURL;
DWORD cch;
};
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow)
{
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
MSG msg;
ZeroMemory(&msg, sizeof(msg));
// Perform application initialization.
if (!InitInstance(hInstance, nCmdShow))
{
NotifyError(NULL, L"Could not initialize the application.",
HRESULT_FROM_WIN32(GetLastError()));
return FALSE;
}
// Main message loop.
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Clean up.
if (g_pPlayer)
{
g_pPlayer->Shutdown();
SafeRelease(&g_pPlayer);
}
return 0;
}
// Create the application window.
BOOL InitInstance(HINSTANCE hInst, int nCmdShow)
{
HWND hwnd;
WNDCLASSEX wcex;
g_hInstance = hInst; // Store the instance handle.
// Register the window class.
ZeroMemory(&wcex, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInst;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MFPLAYBACK);
wcex.lpszClassName = szWindowClass;
if (RegisterClassEx(&wcex) == 0)
{
return FALSE;
}
// Create the application window.
hwnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL);
if (hwnd == 0)
{
return FALSE;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
return TRUE;
}
// Message handler for the main window.
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return OnCreateWindow(hwnd);
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDM_EXIT:
DestroyWindow(hwnd);
break;
case ID_FILE_OPENFILE:
OnFileOpen(hwnd);
break;
case ID_FILE_OPENURL:
OnOpenURL(hwnd);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
break;
case WM_PAINT:
OnPaint(hwnd);
break;
case WM_SIZE:
OnResize(LOWORD(lParam), HIWORD(lParam));
break;
case WM_ERASEBKGND:
// Suppress window erasing, to reduce flickering while the video is playing.
return 1;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_CHAR:
OnKeyPress(wParam);
break;
case WM_APP_PLAYER_EVENT:
OnPlayerEvent(hwnd, wParam);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
// Open an audio/video file.
void OnFileOpen(HWND hwnd)
{
IFileOpenDialog *pFileOpen = NULL;
IShellItem *pItem = NULL;
PWSTR pszFilePath = NULL;
// Create the FileOpenDialog object.
HRESULT hr = CoCreateInstance(__uuidof(FileOpenDialog), NULL,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFileOpen));
if (FAILED(hr))
{
goto done;
}
// Show the Open dialog box.
hr = pFileOpen->Show(NULL);
if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))
{
// The user canceled the dialog. Do not treat as an error.
hr = S_OK;
goto done;
}
else if (FAILED(hr))
{
goto done;
}
// Get the file name from the dialog box.
hr = pFileOpen->GetResult(&pItem);
if (FAILED(hr))
{
goto done;
}
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);
if (FAILED(hr))
{
goto done;
}
// Display the file name to the user.
hr = g_pPlayer->OpenURL(pszFilePath);
if (SUCCEEDED(hr))
{
UpdateUI(hwnd, OpenPending);
}
done:
if (FAILED(hr))
{
NotifyError(hwnd, L"Could not open the file.", hr);
UpdateUI(hwnd, Closed);
}
CoTaskMemFree(pszFilePath);
SafeRelease(&pItem);
SafeRelease(&pFileOpen);
}
// Open a media file from a URL.
void OnOpenURL(HWND hwnd)
{
HRESULT hr = S_OK;
// Pass in an OpenUrlDialogInfo structure to the dialog. The dialog
// fills in this structure with the URL. The dialog proc allocates
// the memory for the string.
OpenUrlDialogInfo url;
ZeroMemory(&url, sizeof(&url));
// Show the Open URL dialog.
if (IDOK == DialogBoxParam(g_hInstance, MAKEINTRESOURCE(IDD_OPENURL), hwnd,
OpenUrlDialogProc, (LPARAM)&url))
{
// Open the file with the playback object.
hr = g_pPlayer->OpenURL(url.pszURL);
if (SUCCEEDED(hr))
{
UpdateUI(hwnd, OpenPending);
}
else
{
NotifyError(hwnd, L"Could not open this URL.", hr);
UpdateUI(hwnd, Closed);
}
}
// The caller must free the URL string.
CoTaskMemFree(url.pszURL);
}
// Handler for WM_CREATE message.
LRESULT OnCreateWindow(HWND hwnd)
{
// Initialize the player object.
HRESULT hr = CPlayer::CreateInstance(hwnd, hwnd, &g_pPlayer);
if (SUCCEEDED(hr))
{
UpdateUI(hwnd, Closed);
return 0; // Success.
}
else
{
NotifyError(NULL, L"Could not initialize the player object.", hr);
return -1; // Destroy the window
}
}
// Handler for WM_PAINT messages.
void OnPaint(HWND hwnd)
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
if (g_pPlayer && g_pPlayer->HasVideo())
{
// Video is playing. Ask the player to repaint.
g_pPlayer->Repaint();
}
else
{
// The video is not playing, so we must paint the application window.
RECT rc;
GetClientRect(hwnd, &rc);
FillRect(hdc, &rc, (HBRUSH) COLOR_WINDOW);
}
EndPaint(hwnd, &ps);
}
// Handler for WM_SIZE messages.
void OnResize(WORD width, WORD height)
{
if (g_pPlayer)
{
g_pPlayer->ResizeVideo(width, height);
}
}
// Handler for WM_CHAR messages.
void OnKeyPress(WPARAM key)
{
switch (key)
{
// Space key toggles between running and paused
case VK_SPACE:
if (g_pPlayer->GetState() == Started)
{
g_pPlayer->Pause();
}
else if (g_pPlayer->GetState() == Paused)
{
g_pPlayer->Play();
}
break;
}
}
// Handler for Media Session events.
void OnPlayerEvent(HWND hwnd, WPARAM pUnkPtr)
{
HRESULT hr = g_pPlayer->HandleEvent(pUnkPtr);
if (FAILED(hr))
{
NotifyError(hwnd, L"An error occurred.", hr);
}
UpdateUI(hwnd, g_pPlayer->GetState());
}
// Update the application UI to reflect the current state.
void UpdateUI(HWND hwnd, PlayerState state)
{
BOOL bWaiting = FALSE;
BOOL bPlayback = FALSE;
assert(g_pPlayer != NULL);
switch (state)
{
case OpenPending:
bWaiting = TRUE;
break;
case Started:
bPlayback = TRUE;
break;
case Paused:
bPlayback = TRUE;
break;
}
HMENU hMenu = GetMenu(hwnd);
UINT uEnable = MF_BYCOMMAND | (bWaiting ? MF_GRAYED : MF_ENABLED);
EnableMenuItem(hMenu, ID_FILE_OPENFILE, uEnable);
EnableMenuItem(hMenu, ID_FILE_OPENURL, uEnable);
if (bPlayback && g_pPlayer->HasVideo())
{
g_bRepaintClient = FALSE;
}
else
{
g_bRepaintClient = TRUE;
}
}
// Show a message box with an error message.
void NotifyError(HWND hwnd, PCWSTR pszErrorMessage, HRESULT hrErr)
{
const size_t MESSAGE_LEN = 512;
WCHAR message[MESSAGE_LEN];
if (SUCCEEDED(StringCchPrintf(message, MESSAGE_LEN, L"%s (HRESULT = 0x%X)",
pszErrorMessage, hrErr)))
{
MessageBox(hwnd, message, NULL, MB_OK | MB_ICONERROR);
}
}
// Dialog proc for the "Open URL" dialog.
INT_PTR CALLBACK OpenUrlDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
static OpenUrlDialogInfo *pUrl = NULL;
BOOL result = FALSE;
switch (message)
{
case WM_INITDIALOG:
// The caller sends a pointer to an OpenUrlDialogInfo structure as the
// lParam. This structure stores the URL.
pUrl = (OpenUrlDialogInfo*)lParam;
return (INT_PTR)TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
if (pUrl)
{
// Get the URL from the edit box in the dialog. This function
// allocates memory. The caller must call CoTaskMemAlloc.
if (SUCCEEDED(AllocGetWindowText(GetDlgItem(hDlg, IDC_EDIT_URL),
&pUrl->pszURL, &pUrl->cch)))
{
result = TRUE;
}
}
EndDialog(hDlg, result ? IDOK : IDABORT);
break;
case IDCANCEL:
EndDialog(hDlg, LOWORD(IDCANCEL));
break;
}
return (INT_PTR)FALSE;
}
return (INT_PTR)FALSE;
}
// Helper function to get text from a window.
//
// This function allocates a buffer and returns it in pszText. The caller must
// call CoTaskMemFree on the buffer.
//
// hwnd: Handle to the window.
// pszText: Receives a pointer to the string.
// pcchLen: Receives the length of the string, in characters, not including
// the terminating NULL character.
HRESULT AllocGetWindowText(HWND hwnd, WCHAR **pszText, DWORD *pcchLen)
{
if (pszText == NULL || pcchLen == NULL)
{
return E_POINTER;
}
*pszText = NULL;
int cch = GetWindowTextLength(hwnd);
if (cch < 0)
{
return E_UNEXPECTED;
}
PWSTR pszTmp = (PWSTR)CoTaskMemAlloc(sizeof(WCHAR) * (cch + 1));
// Includes room for terminating NULL character
if (!pszTmp)
{
return E_OUTOFMEMORY;
}
if (cch == 0)
{
pszTmp[0] = L'\0'; // No text.
}
else
{
int res = GetWindowText(hwnd, pszTmp, (cch + 1));
// Size includes terminating null character.
// GetWindowText returns 0 if (a) there is no text or (b) it failed.
// We checked for (a) already, so 0 means failure here.
if (res == 0)
{
CoTaskMemFree(pszTmp);
return __HRESULT_FROM_WIN32(GetLastError());
}
}
// If we got here, szTmp is valid, so return it to the caller.
*pszText = pszTmp;
// Return the length NOT including the '\0'.
*pcchLen = static_cast<DWORD>(cch);
return S_OK;
}
<commit_msg>mfplay: remove trailing whitespace in winmain<commit_after>#include "gtest/gtest.h"
#include "Player.hpp"
PCWSTR szTitle = L"BasicPlayback";
PCWSTR szWindowClass = L"MFBASICPLAYBACK";
HINSTANCE g_hInstance; // current instance
BOOL g_bRepaintClient = TRUE; // Repaint the application client area?
CPlayer *g_pPlayer = NULL; // Global player object.
// Note: After WM_CREATE is processed, g_pPlayer remains valid until the
// window is destroyed.
// Forward declarations of functions included in this code module:
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK OpenUrlDialogProc(HWND, UINT, WPARAM, LPARAM);
void NotifyError(HWND hwnd, const WCHAR *sErrorMessage, HRESULT hr);
void UpdateUI(HWND hwnd, PlayerState state);
HRESULT AllocGetWindowText(HWND hwnd, WCHAR **pszText, DWORD *pcchLen);
// Message handlers
LRESULT OnCreateWindow(HWND hwnd);
void OnFileOpen(HWND hwnd);
void OnOpenURL(HWND hwnd);
void OnPlayerEvent(HWND hwnd, WPARAM pUnkPtr);
void OnPaint(HWND hwnd);
void OnResize(WORD width, WORD height);
void OnKeyPress(WPARAM key);
// OpenUrlDialogInfo: Contains data passed to the "Open URL" dialog proc.
struct OpenUrlDialogInfo
{
WCHAR *pszURL;
DWORD cch;
};
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow)
{
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
MSG msg;
ZeroMemory(&msg, sizeof(msg));
// Perform application initialization.
if (!InitInstance(hInstance, nCmdShow))
{
NotifyError(NULL, L"Could not initialize the application.",
HRESULT_FROM_WIN32(GetLastError()));
return FALSE;
}
// Main message loop.
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Clean up.
if (g_pPlayer)
{
g_pPlayer->Shutdown();
SafeRelease(&g_pPlayer);
}
return 0;
}
// Create the application window.
BOOL InitInstance(HINSTANCE hInst, int nCmdShow)
{
HWND hwnd;
WNDCLASSEX wcex;
g_hInstance = hInst; // Store the instance handle.
// Register the window class.
ZeroMemory(&wcex, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInst;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MFPLAYBACK);
wcex.lpszClassName = szWindowClass;
if (RegisterClassEx(&wcex) == 0)
{
return FALSE;
}
// Create the application window.
hwnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL);
if (hwnd == 0)
{
return FALSE;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
return TRUE;
}
// Message handler for the main window.
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return OnCreateWindow(hwnd);
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDM_EXIT:
DestroyWindow(hwnd);
break;
case ID_FILE_OPENFILE:
OnFileOpen(hwnd);
break;
case ID_FILE_OPENURL:
OnOpenURL(hwnd);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
break;
case WM_PAINT:
OnPaint(hwnd);
break;
case WM_SIZE:
OnResize(LOWORD(lParam), HIWORD(lParam));
break;
case WM_ERASEBKGND:
// Suppress window erasing, to reduce flickering while the video is playing.
return 1;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_CHAR:
OnKeyPress(wParam);
break;
case WM_APP_PLAYER_EVENT:
OnPlayerEvent(hwnd, wParam);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
// Open an audio/video file.
void OnFileOpen(HWND hwnd)
{
IFileOpenDialog *pFileOpen = NULL;
IShellItem *pItem = NULL;
PWSTR pszFilePath = NULL;
// Create the FileOpenDialog object.
HRESULT hr = CoCreateInstance(__uuidof(FileOpenDialog), NULL,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFileOpen));
if (FAILED(hr))
{
goto done;
}
// Show the Open dialog box.
hr = pFileOpen->Show(NULL);
if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))
{
// The user canceled the dialog. Do not treat as an error.
hr = S_OK;
goto done;
}
else if (FAILED(hr))
{
goto done;
}
// Get the file name from the dialog box.
hr = pFileOpen->GetResult(&pItem);
if (FAILED(hr))
{
goto done;
}
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);
if (FAILED(hr))
{
goto done;
}
// Display the file name to the user.
hr = g_pPlayer->OpenURL(pszFilePath);
if (SUCCEEDED(hr))
{
UpdateUI(hwnd, OpenPending);
}
done:
if (FAILED(hr))
{
NotifyError(hwnd, L"Could not open the file.", hr);
UpdateUI(hwnd, Closed);
}
CoTaskMemFree(pszFilePath);
SafeRelease(&pItem);
SafeRelease(&pFileOpen);
}
// Open a media file from a URL.
void OnOpenURL(HWND hwnd)
{
HRESULT hr = S_OK;
// Pass in an OpenUrlDialogInfo structure to the dialog. The dialog
// fills in this structure with the URL. The dialog proc allocates
// the memory for the string.
OpenUrlDialogInfo url;
ZeroMemory(&url, sizeof(&url));
// Show the Open URL dialog.
if (IDOK == DialogBoxParam(g_hInstance, MAKEINTRESOURCE(IDD_OPENURL), hwnd,
OpenUrlDialogProc, (LPARAM)&url))
{
// Open the file with the playback object.
hr = g_pPlayer->OpenURL(url.pszURL);
if (SUCCEEDED(hr))
{
UpdateUI(hwnd, OpenPending);
}
else
{
NotifyError(hwnd, L"Could not open this URL.", hr);
UpdateUI(hwnd, Closed);
}
}
// The caller must free the URL string.
CoTaskMemFree(url.pszURL);
}
// Handler for WM_CREATE message.
LRESULT OnCreateWindow(HWND hwnd)
{
// Initialize the player object.
HRESULT hr = CPlayer::CreateInstance(hwnd, hwnd, &g_pPlayer);
if (SUCCEEDED(hr))
{
UpdateUI(hwnd, Closed);
return 0; // Success.
}
else
{
NotifyError(NULL, L"Could not initialize the player object.", hr);
return -1; // Destroy the window
}
}
// Handler for WM_PAINT messages.
void OnPaint(HWND hwnd)
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
if (g_pPlayer && g_pPlayer->HasVideo())
{
// Video is playing. Ask the player to repaint.
g_pPlayer->Repaint();
}
else
{
// The video is not playing, so we must paint the application window.
RECT rc;
GetClientRect(hwnd, &rc);
FillRect(hdc, &rc, (HBRUSH) COLOR_WINDOW);
}
EndPaint(hwnd, &ps);
}
// Handler for WM_SIZE messages.
void OnResize(WORD width, WORD height)
{
if (g_pPlayer)
{
g_pPlayer->ResizeVideo(width, height);
}
}
// Handler for WM_CHAR messages.
void OnKeyPress(WPARAM key)
{
switch (key)
{
// Space key toggles between running and paused
case VK_SPACE:
if (g_pPlayer->GetState() == Started)
{
g_pPlayer->Pause();
}
else if (g_pPlayer->GetState() == Paused)
{
g_pPlayer->Play();
}
break;
}
}
// Handler for Media Session events.
void OnPlayerEvent(HWND hwnd, WPARAM pUnkPtr)
{
HRESULT hr = g_pPlayer->HandleEvent(pUnkPtr);
if (FAILED(hr))
{
NotifyError(hwnd, L"An error occurred.", hr);
}
UpdateUI(hwnd, g_pPlayer->GetState());
}
// Update the application UI to reflect the current state.
void UpdateUI(HWND hwnd, PlayerState state)
{
BOOL bWaiting = FALSE;
BOOL bPlayback = FALSE;
assert(g_pPlayer != NULL);
switch (state)
{
case OpenPending:
bWaiting = TRUE;
break;
case Started:
bPlayback = TRUE;
break;
case Paused:
bPlayback = TRUE;
break;
}
HMENU hMenu = GetMenu(hwnd);
UINT uEnable = MF_BYCOMMAND | (bWaiting ? MF_GRAYED : MF_ENABLED);
EnableMenuItem(hMenu, ID_FILE_OPENFILE, uEnable);
EnableMenuItem(hMenu, ID_FILE_OPENURL, uEnable);
if (bPlayback && g_pPlayer->HasVideo())
{
g_bRepaintClient = FALSE;
}
else
{
g_bRepaintClient = TRUE;
}
}
// Show a message box with an error message.
void NotifyError(HWND hwnd, PCWSTR pszErrorMessage, HRESULT hrErr)
{
const size_t MESSAGE_LEN = 512;
WCHAR message[MESSAGE_LEN];
if (SUCCEEDED(StringCchPrintf(message, MESSAGE_LEN, L"%s (HRESULT = 0x%X)",
pszErrorMessage, hrErr)))
{
MessageBox(hwnd, message, NULL, MB_OK | MB_ICONERROR);
}
}
// Dialog proc for the "Open URL" dialog.
INT_PTR CALLBACK OpenUrlDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
static OpenUrlDialogInfo *pUrl = NULL;
BOOL result = FALSE;
switch (message)
{
case WM_INITDIALOG:
// The caller sends a pointer to an OpenUrlDialogInfo structure as the
// lParam. This structure stores the URL.
pUrl = (OpenUrlDialogInfo*)lParam;
return (INT_PTR)TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
if (pUrl)
{
// Get the URL from the edit box in the dialog. This function
// allocates memory. The caller must call CoTaskMemAlloc.
if (SUCCEEDED(AllocGetWindowText(GetDlgItem(hDlg, IDC_EDIT_URL),
&pUrl->pszURL, &pUrl->cch)))
{
result = TRUE;
}
}
EndDialog(hDlg, result ? IDOK : IDABORT);
break;
case IDCANCEL:
EndDialog(hDlg, LOWORD(IDCANCEL));
break;
}
return (INT_PTR)FALSE;
}
return (INT_PTR)FALSE;
}
// Helper function to get text from a window.
//
// This function allocates a buffer and returns it in pszText. The caller must
// call CoTaskMemFree on the buffer.
//
// hwnd: Handle to the window.
// pszText: Receives a pointer to the string.
// pcchLen: Receives the length of the string, in characters, not including
// the terminating NULL character.
HRESULT AllocGetWindowText(HWND hwnd, WCHAR **pszText, DWORD *pcchLen)
{
if (pszText == NULL || pcchLen == NULL)
{
return E_POINTER;
}
*pszText = NULL;
int cch = GetWindowTextLength(hwnd);
if (cch < 0)
{
return E_UNEXPECTED;
}
PWSTR pszTmp = (PWSTR)CoTaskMemAlloc(sizeof(WCHAR) * (cch + 1));
// Includes room for terminating NULL character
if (!pszTmp)
{
return E_OUTOFMEMORY;
}
if (cch == 0)
{
pszTmp[0] = L'\0'; // No text.
}
else
{
int res = GetWindowText(hwnd, pszTmp, (cch + 1));
// Size includes terminating null character.
// GetWindowText returns 0 if (a) there is no text or (b) it failed.
// We checked for (a) already, so 0 means failure here.
if (res == 0)
{
CoTaskMemFree(pszTmp);
return __HRESULT_FROM_WIN32(GetLastError());
}
}
// If we got here, szTmp is valid, so return it to the caller.
*pszText = pszTmp;
// Return the length NOT including the '\0'.
*pcchLen = static_cast<DWORD>(cch);
return S_OK;
}
<|endoftext|> |
<commit_before>/*
* FILE $Id: frpcmethodregistry.cc,v 1.2 2006-02-09 16:00:26 vasek Exp $
*
* DESCRIPTION
*
* AUTHOR
* Miroslav Talasek <[email protected]>
*
* Copyright (C) Seznam.cz a.s. 2002
* All Rights Reserved
*
* HISTORY
*
*/
#include "frpcmethodregistry.h"
#include <frpcmethod.h>
#include <frpcdefaultmethod.h>
#include <frpcheadmethod.h>
#include <frpctreebuilder.h>
#include <frpctreefeeder.h>
#include <frpcunmarshaller.h>
#include <frpcmarshaller.h>
#include <frpcstreamerror.h>
#include <frpcfault.h>
#include <frpclenerror.h>
#include <frpckeyerror.h>
#include <frpcindexerror.h>
#include <frpc.h>
#include <frpcinternals.h>
#include <memory>
#ifdef WIN32
#include <windows.h>
#endif //WIN32
namespace FRPC
{
MethodRegistry_t::TimeDiff_t::TimeDiff_t()
{
// get current time
#ifdef WIN32
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
time(&second);
usecond = (ft.dwLowDateTime / 10) % 1000000;
#else //WIN32
struct timeval now;
gettimeofday(&now, 0);
second = now.tv_sec;
usecond = now.tv_usec;
#endif //WIN32
}
MethodRegistry_t::TimeDiff_t MethodRegistry_t::TimeDiff_t::diff()
{
TimeDiff_t now;
// check for time skew
if ((now.second < second)
|| ((now.second == second) && (now.usecond < usecond)))
return TimeDiff_t(0,0);
// compute difference
if (now.usecond >= usecond)
return TimeDiff_t(now.second - second,
now.usecond - usecond);
return TimeDiff_t
(now.second - second - 1L,
1000000L - usecond + now.usecond);
}
MethodRegistry_t::MethodRegistry_t(Callbacks_t *callbacks, bool introspectionEnabled)
:callbacks(callbacks), introspectionEnabled(introspectionEnabled),
defaultMethod(0),headMethod(0)
{
if(introspectionEnabled)
{
registerMethod("system.listMethods",boundMethod(&MethodRegistry_t::listMethods, *this),
"A:", "List all registered methods");
registerMethod("system.methodHelp",boundMethod(&MethodRegistry_t::methodHelp, *this),
"s:s", "Return given method help");
registerMethod("system.methodSignature",boundMethod(&MethodRegistry_t::methodSignature,
*this), "A:s", "Return given method signature");
registerMethod("system.multicall",boundMethod(&MethodRegistry_t::muticall,
*this), "A:A", "Call given methods");
}
}
void MethodRegistry_t::registerMethod(const std::string &methodName, Method_t *method,
const std::string signature , const std::string help )
{
methodMap.insert(std::make_pair(methodName, RegistryEntry_t(method, signature, help)));
}
void MethodRegistry_t::registerDefaultMethod(DefaultMethod_t *defaultMethod)
{
if(this->defaultMethod != 0)
delete this->defaultMethod;
this->defaultMethod = defaultMethod;
}
void MethodRegistry_t::registerHeadMethod(HeadMethod_t *headMethod)
{
if(this->headMethod != 0)
delete this->headMethod;
this->headMethod = headMethod;
}
MethodRegistry_t::~MethodRegistry_t()
{
for(std::map<std::string, RegistryEntry_t>::iterator i = methodMap.begin();
i != methodMap.end(); ++i)
{
delete i->second.method;
}
}
/*
namespace
{
const long BUFFER_SIZE = 1<<16;
}
*/
long MethodRegistry_t::processCall(const std::string &clientIP, const std::string &methodName,
Array_t ¶ms,
Writer_t &writer, long typeOut)
{
Pool_t pool;
std::auto_ptr<Marshaller_t> marshaller(Marshaller_t::create(typeOut, writer));
TimeDiff_t timeD;
TreeFeeder_t feeder(*marshaller);
try
{
Value_t &retValue = processCall(clientIP, methodName, params, pool);
marshaller->packMethodResponse();
feeder.feedValue(retValue);
marshaller->flush();
}
catch(const StreamError_t &streamError)
{
if(callbacks)
callbacks->postProcess(methodName, clientIP, params,Fault_t(FRPC_PARSE_ERROR,
streamError.message()),timeD.diff());
marshaller->packFault(FRPC_PARSE_ERROR,streamError.message().c_str());
marshaller->flush();
}
catch(const Fault_t &fault)
{
if(callbacks)
callbacks->postProcess(methodName, clientIP, params, fault,timeD.diff());
marshaller->packFault(fault.errorNum(),fault.message().c_str());
marshaller->flush();
}
return 0;
}
Value_t& MethodRegistry_t::processCall(const std::string &clientIP, const std::string &methodName,
Array_t ¶ms,
Pool_t &pool)
{
TimeDiff_t timeD;
Value_t *result;
try
{
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
methodName);
if(pos == methodMap.end())
{
//if default method registered call it
if(!defaultMethod)
{
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
methodName.c_str());
}
else
{
if(callbacks)
callbacks->preProcess(methodName, clientIP, params);
result = &(defaultMethod->call(pool, methodName,params));
if(callbacks)
callbacks->postProcess(methodName, clientIP, params, *result,timeD.diff());
}
}
else
{
if(callbacks)
callbacks->preProcess(methodName, clientIP, params);
result = &(pos->second.method->call(pool, params));
if(callbacks)
callbacks->postProcess(methodName, clientIP, params, *result,timeD.diff());
}
}
catch(const TypeError_t &typeError)
{
throw Fault_t(FRPC_TYPE_ERROR,typeError.message());
}
catch(const LenError_t &lenError)
{
throw Fault_t(FRPC_TYPE_ERROR,lenError.message());
}
catch(const KeyError_t &keyError)
{
throw Fault_t(FRPC_INDEX_ERROR,keyError.message());
}
catch(const IndexError_t &indexError)
{
throw Fault_t(FRPC_INDEX_ERROR,indexError.message());
}
catch(const StreamError_t &streamError)
{
throw Fault_t(FRPC_PARSE_ERROR,streamError.message());
}
return *result;
}
Value_t& MethodRegistry_t::processCall(const std::string &clientIP, Reader_t &reader,
long typeIn, Pool_t &pool)
{
TreeBuilder_t builder(pool);
std::auto_ptr<UnMarshaller_t> unmarshaller(UnMarshaller_t::create(typeIn, builder));
char buffer[BUFFER_SIZE];
long readed;
Value_t *result;
try
{
while((readed = reader.read(buffer,BUFFER_SIZE)))
{
unmarshaller->unMarshall(buffer, readed,
UnMarshaller_t::TYPE_METHOD_CALL);
}
result = &(processCall(builder.getUnMarshaledMethodName(), clientIP,
Array(builder.getUnMarshaledData()),pool));
}
catch(const StreamError_t &streamError)
{
throw Fault_t(FRPC_PARSE_ERROR,streamError.message());
}
return *result;
}
long MethodRegistry_t::processCall(const std::string &clientIP, Reader_t &reader,
long typeIn, Writer_t &writer, long typeOut)
{
Pool_t pool;
TreeBuilder_t builder(pool);
std::auto_ptr<UnMarshaller_t> unmarshaller(UnMarshaller_t::create(typeIn, builder));
std::auto_ptr<Marshaller_t> marshaller(Marshaller_t::create(typeOut, writer));
Value_t *retValue;
TreeFeeder_t feeder(*marshaller);
char buffer[BUFFER_SIZE];
long readed;
try
{
while((readed = reader.read(buffer,BUFFER_SIZE)))
{
unmarshaller->unMarshall(buffer, readed,
UnMarshaller_t::TYPE_METHOD_CALL);
}
retValue = &(processCall(builder.getUnMarshaledMethodName(), clientIP,
Array(builder.getUnMarshaledData()),pool));
marshaller->packMethodResponse();
feeder.feedValue(*retValue);
marshaller->flush();
}
catch(const StreamError_t &streamError)
{
marshaller->packFault(FRPC_PARSE_ERROR,streamError.message().c_str());
marshaller->flush();
}
catch(const Fault_t &fault)
{
marshaller->packFault(fault.errorNum(),fault.message().c_str());
marshaller->flush();
}
return 0;
}
long MethodRegistry_t::headCall()
{
//if head method registered call it
if(!headMethod)
{
return -1;
}
else
{
if(headMethod->call())
return 0;
else
return 1;
}
}
//*******************system methods************************************
Value_t& MethodRegistry_t::listMethods(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 0)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 0 arguments but %d argumet(s) given",
params.size());
Array_t &retArray = pool.Array();
for(std::map<std::string, RegistryEntry_t>::iterator i = methodMap.begin();
i != methodMap.end(); ++i)
{
retArray.append(pool.String(i->first));
}
return retArray;
}
Value_t& MethodRegistry_t::methodHelp(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 1)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 1 argument but %d argumet(s) given",
params.size());
params.checkItems("s");
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
String(params[0]).getString());
if(pos == methodMap.end())
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
String(params[0]).getString().c_str());
return pool.String(pos->second.help);
}
Value_t& MethodRegistry_t::methodSignature(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 1)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 1 argument but %d argumet(s) given",
params.size());
params.checkItems("s");
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
String(params[0]).getString());
if(pos == methodMap.end())
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
String(params[0]).getString().c_str());
//build array signature
Array_t &array = pool.Array();
Array_t *actual = &(pool.Array());
array.append(*actual);
for(unsigned long i = 0; i <= pos->second.signature.size(); i++)
{
switch(pos->second.signature[i])
{
case 'A':
actual->append(pool.String("array"));
break;
case 'S':
actual->append(pool.String("struct"));
break;
case 'B':
actual->append(pool.String("binary"));
break;
case 'D':
actual->append(pool.String("dateTime"));
break;
case 'b':
actual->append(pool.String("bool"));
break;
case 'd':
actual->append(pool.String("double"));
break;
case 'i':
actual->append(pool.String("int"));
break;
case 's':
actual->append(pool.String("string"));
break;
case ':':
break;
case ',':
actual = &(pool.Array());
array.append(*actual);
break;
default:
break;
}
}
return array;
}
Value_t& MethodRegistry_t::muticall(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 1)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 1 argument but %d argumet(s) given",
params.size());
params.checkItems("A");
Array_t &array = pool.Array();
for(Array_t::const_iterator pos = Array(params[0]).begin(); pos != Array(params[0]).end();
++pos)
{
if((*pos)->getType() != Struct_t::TYPE)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_TYPE_ERROR),
"faultString",pool.String("Parameter must be struct")));
continue;
}
try
{
Struct_t &strct = Struct(**pos);
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
String(strct["methodName"]).getString());
if(pos == methodMap.end())
{
//if default method registered call it
if(!defaultMethod)
{
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
String(strct["methodName"]).getString().c_str());
}
else
{
array.append(pool.Array(defaultMethod->call(pool,
String(strct["methodName"]).getString(),
Array(strct["params"]))));
}
}
else
{
array.append(pool.Array(pos->second.method->call(pool,
Array(strct["params"]))));
}
}
catch(const TypeError_t &typeError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_TYPE_ERROR),
"faultString",pool.String(typeError.message())));
}
catch(const LenError_t &lenError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_TYPE_ERROR),
"faultString",pool.String(lenError.message())));
}
catch(const KeyError_t &keyError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_INDEX_ERROR),
"faultString",pool.String(keyError.message())));
}
catch(const IndexError_t &indexError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_INDEX_ERROR),
"faultString",pool.String(indexError.message())));
}
catch(const Fault_t &fault)
{
array.append(pool.Struct("faultCode",pool.Int(fault.errorNum()),
"faultString",pool.String(fault.message())));
}
}
return array;
}
}
<commit_msg>preprocess is called even if method is not known and no default method is registered<commit_after>/*
* FILE $Id: frpcmethodregistry.cc,v 1.3 2006-03-02 13:55:39 vasek Exp $
*
* DESCRIPTION
*
* AUTHOR
* Miroslav Talasek <[email protected]>
*
* Copyright (C) Seznam.cz a.s. 2002
* All Rights Reserved
*
* HISTORY
*
*/
#include "frpcmethodregistry.h"
#include <frpcmethod.h>
#include <frpcdefaultmethod.h>
#include <frpcheadmethod.h>
#include <frpctreebuilder.h>
#include <frpctreefeeder.h>
#include <frpcunmarshaller.h>
#include <frpcmarshaller.h>
#include <frpcstreamerror.h>
#include <frpcfault.h>
#include <frpclenerror.h>
#include <frpckeyerror.h>
#include <frpcindexerror.h>
#include <frpc.h>
#include <frpcinternals.h>
#include <memory>
#ifdef WIN32
#include <windows.h>
#endif //WIN32
namespace FRPC
{
MethodRegistry_t::TimeDiff_t::TimeDiff_t()
{
// get current time
#ifdef WIN32
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
time(&second);
usecond = (ft.dwLowDateTime / 10) % 1000000;
#else //WIN32
struct timeval now;
gettimeofday(&now, 0);
second = now.tv_sec;
usecond = now.tv_usec;
#endif //WIN32
}
MethodRegistry_t::TimeDiff_t MethodRegistry_t::TimeDiff_t::diff()
{
TimeDiff_t now;
// check for time skew
if ((now.second < second)
|| ((now.second == second) && (now.usecond < usecond)))
return TimeDiff_t(0,0);
// compute difference
if (now.usecond >= usecond)
return TimeDiff_t(now.second - second,
now.usecond - usecond);
return TimeDiff_t
(now.second - second - 1L,
1000000L - usecond + now.usecond);
}
MethodRegistry_t::MethodRegistry_t(Callbacks_t *callbacks, bool introspectionEnabled)
:callbacks(callbacks), introspectionEnabled(introspectionEnabled),
defaultMethod(0),headMethod(0)
{
if(introspectionEnabled)
{
registerMethod("system.listMethods",boundMethod(&MethodRegistry_t::listMethods, *this),
"A:", "List all registered methods");
registerMethod("system.methodHelp",boundMethod(&MethodRegistry_t::methodHelp, *this),
"s:s", "Return given method help");
registerMethod("system.methodSignature",boundMethod(&MethodRegistry_t::methodSignature,
*this), "A:s", "Return given method signature");
registerMethod("system.multicall",boundMethod(&MethodRegistry_t::muticall,
*this), "A:A", "Call given methods");
}
}
void MethodRegistry_t::registerMethod(const std::string &methodName, Method_t *method,
const std::string signature , const std::string help )
{
methodMap.insert(std::make_pair(methodName, RegistryEntry_t(method, signature, help)));
}
void MethodRegistry_t::registerDefaultMethod(DefaultMethod_t *defaultMethod)
{
if(this->defaultMethod != 0)
delete this->defaultMethod;
this->defaultMethod = defaultMethod;
}
void MethodRegistry_t::registerHeadMethod(HeadMethod_t *headMethod)
{
if(this->headMethod != 0)
delete this->headMethod;
this->headMethod = headMethod;
}
MethodRegistry_t::~MethodRegistry_t()
{
for(std::map<std::string, RegistryEntry_t>::iterator i = methodMap.begin();
i != methodMap.end(); ++i)
{
delete i->second.method;
}
}
/*
namespace
{
const long BUFFER_SIZE = 1<<16;
}
*/
long MethodRegistry_t::processCall(const std::string &clientIP, const std::string &methodName,
Array_t ¶ms,
Writer_t &writer, long typeOut)
{
Pool_t pool;
std::auto_ptr<Marshaller_t> marshaller(Marshaller_t::create(typeOut, writer));
TimeDiff_t timeD;
TreeFeeder_t feeder(*marshaller);
try
{
Value_t &retValue = processCall(clientIP, methodName, params, pool);
marshaller->packMethodResponse();
feeder.feedValue(retValue);
marshaller->flush();
}
catch(const StreamError_t &streamError)
{
if(callbacks)
callbacks->postProcess(methodName, clientIP, params,Fault_t(FRPC_PARSE_ERROR,
streamError.message()),timeD.diff());
marshaller->packFault(FRPC_PARSE_ERROR,streamError.message().c_str());
marshaller->flush();
}
catch(const Fault_t &fault)
{
if(callbacks)
callbacks->postProcess(methodName, clientIP, params, fault,timeD.diff());
marshaller->packFault(fault.errorNum(),fault.message().c_str());
marshaller->flush();
}
return 0;
}
Value_t& MethodRegistry_t::processCall(const std::string &clientIP, const std::string &methodName,
Array_t ¶ms,
Pool_t &pool)
{
TimeDiff_t timeD;
Value_t *result;
try
{
std::map<std::string, RegistryEntry_t>::const_iterator
pos = methodMap.find(methodName);
if (pos == methodMap.end()){
if (callbacks)
callbacks->preProcess(methodName, clientIP, params);
// if not default method generate fault
if (!defaultMethod)
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR, "Method %s not found",
methodName.c_str());
result = &(defaultMethod->call(pool, methodName,params));
if (callbacks)
callbacks->postProcess(methodName, clientIP, params, *result,
timeD.diff());
} else {
if(callbacks)
callbacks->preProcess(methodName, clientIP, params);
result = &(pos->second.method->call(pool, params));
if(callbacks)
callbacks->postProcess(methodName, clientIP, params, *result,
timeD.diff());
}
}
catch(const TypeError_t &typeError)
{
throw Fault_t(FRPC_TYPE_ERROR,typeError.message());
}
catch(const LenError_t &lenError)
{
throw Fault_t(FRPC_TYPE_ERROR,lenError.message());
}
catch(const KeyError_t &keyError)
{
throw Fault_t(FRPC_INDEX_ERROR,keyError.message());
}
catch(const IndexError_t &indexError)
{
throw Fault_t(FRPC_INDEX_ERROR,indexError.message());
}
catch(const StreamError_t &streamError)
{
throw Fault_t(FRPC_PARSE_ERROR,streamError.message());
}
return *result;
}
Value_t& MethodRegistry_t::processCall(const std::string &clientIP, Reader_t &reader,
long typeIn, Pool_t &pool)
{
TreeBuilder_t builder(pool);
std::auto_ptr<UnMarshaller_t> unmarshaller(UnMarshaller_t::create(typeIn, builder));
char buffer[BUFFER_SIZE];
long readed;
Value_t *result;
try
{
while((readed = reader.read(buffer,BUFFER_SIZE)))
{
unmarshaller->unMarshall(buffer, readed,
UnMarshaller_t::TYPE_METHOD_CALL);
}
result = &(processCall(builder.getUnMarshaledMethodName(), clientIP,
Array(builder.getUnMarshaledData()),pool));
}
catch(const StreamError_t &streamError)
{
throw Fault_t(FRPC_PARSE_ERROR,streamError.message());
}
return *result;
}
long MethodRegistry_t::processCall(const std::string &clientIP, Reader_t &reader,
long typeIn, Writer_t &writer, long typeOut)
{
Pool_t pool;
TreeBuilder_t builder(pool);
std::auto_ptr<UnMarshaller_t> unmarshaller(UnMarshaller_t::create(typeIn, builder));
std::auto_ptr<Marshaller_t> marshaller(Marshaller_t::create(typeOut, writer));
Value_t *retValue;
TreeFeeder_t feeder(*marshaller);
char buffer[BUFFER_SIZE];
long readed;
try
{
while((readed = reader.read(buffer,BUFFER_SIZE)))
{
unmarshaller->unMarshall(buffer, readed,
UnMarshaller_t::TYPE_METHOD_CALL);
}
retValue = &(processCall(builder.getUnMarshaledMethodName(), clientIP,
Array(builder.getUnMarshaledData()),pool));
marshaller->packMethodResponse();
feeder.feedValue(*retValue);
marshaller->flush();
}
catch(const StreamError_t &streamError)
{
marshaller->packFault(FRPC_PARSE_ERROR,streamError.message().c_str());
marshaller->flush();
}
catch(const Fault_t &fault)
{
marshaller->packFault(fault.errorNum(),fault.message().c_str());
marshaller->flush();
}
return 0;
}
long MethodRegistry_t::headCall()
{
//if head method registered call it
if(!headMethod)
{
return -1;
}
else
{
if(headMethod->call())
return 0;
else
return 1;
}
}
//*******************system methods************************************
Value_t& MethodRegistry_t::listMethods(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 0)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 0 arguments but %d argumet(s) given",
params.size());
Array_t &retArray = pool.Array();
for(std::map<std::string, RegistryEntry_t>::iterator i = methodMap.begin();
i != methodMap.end(); ++i)
{
retArray.append(pool.String(i->first));
}
return retArray;
}
Value_t& MethodRegistry_t::methodHelp(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 1)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 1 argument but %d argumet(s) given",
params.size());
params.checkItems("s");
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
String(params[0]).getString());
if(pos == methodMap.end())
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
String(params[0]).getString().c_str());
return pool.String(pos->second.help);
}
Value_t& MethodRegistry_t::methodSignature(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 1)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 1 argument but %d argumet(s) given",
params.size());
params.checkItems("s");
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
String(params[0]).getString());
if(pos == methodMap.end())
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
String(params[0]).getString().c_str());
//build array signature
Array_t &array = pool.Array();
Array_t *actual = &(pool.Array());
array.append(*actual);
for(unsigned long i = 0; i <= pos->second.signature.size(); i++)
{
switch(pos->second.signature[i])
{
case 'A':
actual->append(pool.String("array"));
break;
case 'S':
actual->append(pool.String("struct"));
break;
case 'B':
actual->append(pool.String("binary"));
break;
case 'D':
actual->append(pool.String("dateTime"));
break;
case 'b':
actual->append(pool.String("bool"));
break;
case 'd':
actual->append(pool.String("double"));
break;
case 'i':
actual->append(pool.String("int"));
break;
case 's':
actual->append(pool.String("string"));
break;
case ':':
break;
case ',':
actual = &(pool.Array());
array.append(*actual);
break;
default:
break;
}
}
return array;
}
Value_t& MethodRegistry_t::muticall(Pool_t &pool, Array_t ¶ms)
{
if(params.size() != 1)
throw Fault_t(FRPC_TYPE_ERROR,"Method required 1 argument but %d argumet(s) given",
params.size());
params.checkItems("A");
Array_t &array = pool.Array();
for(Array_t::const_iterator pos = Array(params[0]).begin(); pos != Array(params[0]).end();
++pos)
{
if((*pos)->getType() != Struct_t::TYPE)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_TYPE_ERROR),
"faultString",pool.String("Parameter must be struct")));
continue;
}
try
{
Struct_t &strct = Struct(**pos);
std::map<std::string, RegistryEntry_t>::const_iterator pos = methodMap.find(
String(strct["methodName"]).getString());
if(pos == methodMap.end())
{
//if default method registered call it
if(!defaultMethod)
{
throw Fault_t(FRPC_NO_SUCH_METHOD_ERROR,"Method %s not found",
String(strct["methodName"]).getString().c_str());
}
else
{
array.append(pool.Array(defaultMethod->call(pool,
String(strct["methodName"]).getString(),
Array(strct["params"]))));
}
}
else
{
array.append(pool.Array(pos->second.method->call(pool,
Array(strct["params"]))));
}
}
catch(const TypeError_t &typeError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_TYPE_ERROR),
"faultString",pool.String(typeError.message())));
}
catch(const LenError_t &lenError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_TYPE_ERROR),
"faultString",pool.String(lenError.message())));
}
catch(const KeyError_t &keyError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_INDEX_ERROR),
"faultString",pool.String(keyError.message())));
}
catch(const IndexError_t &indexError)
{
array.append(pool.Struct("faultCode",pool.Int(FRPC_INDEX_ERROR),
"faultString",pool.String(indexError.message())));
}
catch(const Fault_t &fault)
{
array.append(pool.Struct("faultCode",pool.Int(fault.errorNum()),
"faultString",pool.String(fault.message())));
}
}
return array;
}
}
<|endoftext|> |
<commit_before>// SciTE - Scintilla based Text Editor
/** @file DirectorExtension.cxx
** Extension for communicating with a director program.
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <commctrl.h>
#include "Platform.h"
#include "PropSet.h"
#include "Scintilla.h"
#include "Accessor.h"
#include "Extender.h"
#include "DirectorExtension.h"
#include "SciTE.h"
#include "SciTEBase.h"
static ExtensionAPI *host = 0;
static DirectorExtension *pde = 0;
static HWND wDirector = 0;
static HWND wCorrespondent = 0;
static HWND wReceiver = 0;
static bool startedByDirector = false;
static bool shuttingDown = false;
unsigned int SDI = 0;
static void SendDirector(const char *verb, const char *arg = 0) {
if ((wDirector != 0) || (wCorrespondent != 0)) {
HWND wDestination = wCorrespondent;
SString addressedMessage;
if (wDestination) {
addressedMessage += ":";
SString address(reinterpret_cast<int>(wDestination));
addressedMessage += address;
addressedMessage += ":";
} else {
wDestination = wDirector;
}
addressedMessage += verb;
addressedMessage += ":";
if (arg)
addressedMessage += arg;
char *slashedMessage = Slash(addressedMessage.c_str());
if (slashedMessage) {
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.cbData = strlen(slashedMessage);
cds.lpData = reinterpret_cast<void *>(
const_cast<char *>(slashedMessage));
::SendMessage(wDestination, WM_COPYDATA,
reinterpret_cast<WPARAM>(wReceiver),
reinterpret_cast<LPARAM>(&cds));
delete []slashedMessage;
}
}
}
static void SendDirector(const char *verb, sptr_t arg) {
SString s(arg);
::SendDirector(verb, s.c_str());
}
static void CheckEnvironment(ExtensionAPI *host) {
if (host && !shuttingDown) {
if (!wDirector) {
char *director = host->Property("director.hwnd");
if (director && *director) {
startedByDirector = true;
wDirector = reinterpret_cast<HWND>(atoi(director));
// Director is just seen so identify this to it
::SendDirector("identity", reinterpret_cast<sptr_t>(wReceiver));
}
delete []director;
}
char number[32];
sprintf(number, "%0d", reinterpret_cast<int>(wReceiver));
host->SetProperty("WindowID", number);
}
}
static char DirectorExtension_ClassName[] = "DirectorExtension";
static LRESULT HandleCopyData(LPARAM lParam) {
COPYDATASTRUCT *pcds = reinterpret_cast<COPYDATASTRUCT *>(lParam);
// Copy into an temporary buffer to ensure \0 terminated
if (pde && pcds->lpData) {
char *dataCopy = new char[pcds->cbData + 1];
if (dataCopy) {
strncpy(dataCopy, reinterpret_cast<char *>(pcds->lpData), pcds->cbData);
dataCopy[pcds->cbData] = '\0';
pde->HandleStringMessage(dataCopy);
delete []dataCopy;
}
}
return 0;
}
LRESULT PASCAL DirectorExtension_WndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
if (iMessage == WM_COPYDATA) {
return HandleCopyData(lParam);
} else if (iMessage == SDI) {
return SDI;
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
static void DirectorExtension_Register(HINSTANCE hInstance) {
WNDCLASS wndclass;
wndclass.style = 0;
wndclass.lpfnWndProc = DirectorExtension_WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = 0;
wndclass.hCursor = NULL;
wndclass.hbrBackground = NULL;
wndclass.lpszMenuName = 0;
wndclass.lpszClassName = DirectorExtension_ClassName;
if (!::RegisterClass(&wndclass))
::exit(FALSE);
}
DirectorExtension::DirectorExtension() {
pde = this;
}
DirectorExtension::~DirectorExtension() {
pde = 0;
}
bool DirectorExtension::Initialise(ExtensionAPI *host_) {
host = host_;
SDI = ::RegisterWindowMessage("SciTEDirectorInterface");
HINSTANCE hInstance = reinterpret_cast<HINSTANCE>(
host->GetInstance());
DirectorExtension_Register(hInstance);
wReceiver = ::CreateWindow(
DirectorExtension_ClassName,
DirectorExtension_ClassName,
0,
0, 0, 0, 0,
0,
0,
hInstance,
0);
if (!wReceiver)
::exit(FALSE);
// Make the frame window handle available so the director can activate it.
::SetWindowLong(wReceiver, GWL_USERDATA,
reinterpret_cast<LONG>(((SciTEBase*)host)->GetID()));
CheckEnvironment(host);
return true;
}
bool DirectorExtension::Finalise() {
::SendDirector("closing");
if (wReceiver)
::DestroyWindow(wReceiver);
wReceiver = 0;
return true;
}
bool DirectorExtension::Clear() {
return true;
}
bool DirectorExtension::Load(const char *) {
return true;
}
bool DirectorExtension::OnOpen(const char *path) {
CheckEnvironment(host);
if (*path) {
::SendDirector("opened", path);
}
return true;
}
bool DirectorExtension::OnSwitchFile(const char *path) {
CheckEnvironment(host);
if (*path) {
::SendDirector("switched", path);
}
return true;
};
bool DirectorExtension::OnSave(const char *path) {
CheckEnvironment(host);
if (*path) {
::SendDirector("saved", path);
}
return true;
}
bool DirectorExtension::OnChar(char) {
return false;
}
bool DirectorExtension::OnExecute(const char *) {
return false;
}
bool DirectorExtension::OnSavePointReached() {
return false;
}
bool DirectorExtension::OnSavePointLeft() {
return false;
}
bool DirectorExtension::OnStyle(unsigned int, int, int, Accessor *) {
return false;
}
// These should probably have arguments
bool DirectorExtension::OnDoubleClick() {
return false;
}
bool DirectorExtension::OnUpdateUI() {
return false;
}
bool DirectorExtension::OnMarginClick() {
return false;
}
bool DirectorExtension::OnMacro(const char *command, const char *params) {
SendDirector(command, params);
return true;
}
bool DirectorExtension::SendProperty(const char *prop) {
CheckEnvironment(host);
if (*prop) {
::SendDirector("property", prop);
}
return true;
}
void DirectorExtension::HandleStringMessage(const char *message) {
// Message may contain multiple commands separated by '\n'
// Reentrance trouble - if this function is reentered, the wCorrespondent may
// be set to zero before time.
WordList wlMessage(true);
wlMessage.Set(message);
for (int i = 0; i < wlMessage.len; i++) {
// Message format is [:return address:]command:argument
char *cmd = wlMessage[i];
if (*cmd == ':') {
// There is a return address
char *colon = strchr(cmd + 1, ':');
if (colon) {
*colon = '\0';
wCorrespondent = reinterpret_cast<HWND>(atoi(cmd + 1));
cmd = colon + 1;
}
}
if (isprefix(cmd, "identity:")) {
char *arg = strchr(cmd, ':');
if (arg)
wDirector = reinterpret_cast<HWND>(atoi(arg + 1));
} else if (isprefix(cmd, "closing:")) {
wDirector = 0;
if (startedByDirector) {
shuttingDown = true;
host->ShutDown();
shuttingDown = false;
}
} else if (host) {
host->Perform(cmd);
}
wCorrespondent = 0;
}
}
#ifdef _MSC_VER
// Unreferenced inline functions are OK
#pragma warning(disable: 4514)
#endif
<commit_msg>Execute sends macro:run command to director.<commit_after>// SciTE - Scintilla based Text Editor
/** @file DirectorExtension.cxx
** Extension for communicating with a director program.
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <commctrl.h>
#include "Platform.h"
#include "PropSet.h"
#include "Scintilla.h"
#include "Accessor.h"
#include "Extender.h"
#include "DirectorExtension.h"
#include "SciTE.h"
#include "SciTEBase.h"
static ExtensionAPI *host = 0;
static DirectorExtension *pde = 0;
static HWND wDirector = 0;
static HWND wCorrespondent = 0;
static HWND wReceiver = 0;
static bool startedByDirector = false;
static bool shuttingDown = false;
unsigned int SDI = 0;
static void SendDirector(const char *verb, const char *arg = 0) {
if ((wDirector != 0) || (wCorrespondent != 0)) {
HWND wDestination = wCorrespondent;
SString addressedMessage;
if (wDestination) {
addressedMessage += ":";
SString address(reinterpret_cast<int>(wDestination));
addressedMessage += address;
addressedMessage += ":";
} else {
wDestination = wDirector;
}
addressedMessage += verb;
addressedMessage += ":";
if (arg)
addressedMessage += arg;
char *slashedMessage = Slash(addressedMessage.c_str());
if (slashedMessage) {
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.cbData = strlen(slashedMessage);
cds.lpData = reinterpret_cast<void *>(
const_cast<char *>(slashedMessage));
::SendMessage(wDestination, WM_COPYDATA,
reinterpret_cast<WPARAM>(wReceiver),
reinterpret_cast<LPARAM>(&cds));
delete []slashedMessage;
}
}
}
static void SendDirector(const char *verb, sptr_t arg) {
SString s(arg);
::SendDirector(verb, s.c_str());
}
static void CheckEnvironment(ExtensionAPI *host) {
if (host && !shuttingDown) {
if (!wDirector) {
char *director = host->Property("director.hwnd");
if (director && *director) {
startedByDirector = true;
wDirector = reinterpret_cast<HWND>(atoi(director));
// Director is just seen so identify this to it
::SendDirector("identity", reinterpret_cast<sptr_t>(wReceiver));
}
delete []director;
}
char number[32];
sprintf(number, "%0d", reinterpret_cast<int>(wReceiver));
host->SetProperty("WindowID", number);
}
}
static char DirectorExtension_ClassName[] = "DirectorExtension";
static LRESULT HandleCopyData(LPARAM lParam) {
COPYDATASTRUCT *pcds = reinterpret_cast<COPYDATASTRUCT *>(lParam);
// Copy into an temporary buffer to ensure \0 terminated
if (pde && pcds->lpData) {
char *dataCopy = new char[pcds->cbData + 1];
if (dataCopy) {
strncpy(dataCopy, reinterpret_cast<char *>(pcds->lpData), pcds->cbData);
dataCopy[pcds->cbData] = '\0';
pde->HandleStringMessage(dataCopy);
delete []dataCopy;
}
}
return 0;
}
LRESULT PASCAL DirectorExtension_WndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
if (iMessage == WM_COPYDATA) {
return HandleCopyData(lParam);
} else if (iMessage == SDI) {
return SDI;
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
static void DirectorExtension_Register(HINSTANCE hInstance) {
WNDCLASS wndclass;
wndclass.style = 0;
wndclass.lpfnWndProc = DirectorExtension_WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = 0;
wndclass.hCursor = NULL;
wndclass.hbrBackground = NULL;
wndclass.lpszMenuName = 0;
wndclass.lpszClassName = DirectorExtension_ClassName;
if (!::RegisterClass(&wndclass))
::exit(FALSE);
}
DirectorExtension::DirectorExtension() {
pde = this;
}
DirectorExtension::~DirectorExtension() {
pde = 0;
}
bool DirectorExtension::Initialise(ExtensionAPI *host_) {
host = host_;
SDI = ::RegisterWindowMessage("SciTEDirectorInterface");
HINSTANCE hInstance = reinterpret_cast<HINSTANCE>(
host->GetInstance());
DirectorExtension_Register(hInstance);
wReceiver = ::CreateWindow(
DirectorExtension_ClassName,
DirectorExtension_ClassName,
0,
0, 0, 0, 0,
0,
0,
hInstance,
0);
if (!wReceiver)
::exit(FALSE);
// Make the frame window handle available so the director can activate it.
::SetWindowLong(wReceiver, GWL_USERDATA,
reinterpret_cast<LONG>(((SciTEBase*)host)->GetID()));
CheckEnvironment(host);
return true;
}
bool DirectorExtension::Finalise() {
::SendDirector("closing");
if (wReceiver)
::DestroyWindow(wReceiver);
wReceiver = 0;
return true;
}
bool DirectorExtension::Clear() {
return true;
}
bool DirectorExtension::Load(const char *) {
return true;
}
bool DirectorExtension::OnOpen(const char *path) {
CheckEnvironment(host);
if (*path) {
::SendDirector("opened", path);
}
return true;
}
bool DirectorExtension::OnSwitchFile(const char *path) {
CheckEnvironment(host);
if (*path) {
::SendDirector("switched", path);
}
return true;
};
bool DirectorExtension::OnSave(const char *path) {
CheckEnvironment(host);
if (*path) {
::SendDirector("saved", path);
}
return true;
}
bool DirectorExtension::OnChar(char) {
return false;
}
bool DirectorExtension::OnExecute(const char *cmd) {
CheckEnvironment(host);
::SendDirector("macro:run", cmd);
return true;
}
bool DirectorExtension::OnSavePointReached() {
return false;
}
bool DirectorExtension::OnSavePointLeft() {
return false;
}
bool DirectorExtension::OnStyle(unsigned int, int, int, Accessor *) {
return false;
}
// These should probably have arguments
bool DirectorExtension::OnDoubleClick() {
return false;
}
bool DirectorExtension::OnUpdateUI() {
return false;
}
bool DirectorExtension::OnMarginClick() {
return false;
}
bool DirectorExtension::OnMacro(const char *command, const char *params) {
SendDirector(command, params);
return true;
}
bool DirectorExtension::SendProperty(const char *prop) {
CheckEnvironment(host);
if (*prop) {
::SendDirector("property", prop);
}
return true;
}
void DirectorExtension::HandleStringMessage(const char *message) {
// Message may contain multiple commands separated by '\n'
// Reentrance trouble - if this function is reentered, the wCorrespondent may
// be set to zero before time.
WordList wlMessage(true);
wlMessage.Set(message);
for (int i = 0; i < wlMessage.len; i++) {
// Message format is [:return address:]command:argument
char *cmd = wlMessage[i];
if (*cmd == ':') {
// There is a return address
char *colon = strchr(cmd + 1, ':');
if (colon) {
*colon = '\0';
wCorrespondent = reinterpret_cast<HWND>(atoi(cmd + 1));
cmd = colon + 1;
}
}
if (isprefix(cmd, "identity:")) {
char *arg = strchr(cmd, ':');
if (arg)
wDirector = reinterpret_cast<HWND>(atoi(arg + 1));
} else if (isprefix(cmd, "closing:")) {
wDirector = 0;
if (startedByDirector) {
shuttingDown = true;
host->ShutDown();
shuttingDown = false;
}
} else if (host) {
host->Perform(cmd);
}
wCorrespondent = 0;
}
}
#ifdef _MSC_VER
// Unreferenced inline functions are OK
#pragma warning(disable: 4514)
#endif
<|endoftext|> |
<commit_before>/**
* \file
* \brief PySceneManager class implementation.
* \author Thomas Moeller
* \details
*
* Copyright (C) the PyInventor contributors. All rights reserved.
* This file is part of PyInventor, distributed under the BSD 3-Clause
* License. For full terms see the included COPYING file.
*/
#include <Inventor/SoSceneManager.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoMouseButtonEvent.h>
#include <Inventor/events/SoKeyboardEvent.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/engines/SoEngine.h>
#include <Inventor/elements/SoGLLazyElement.h> // for GL.h, whose location is distribution specific under system/ or sys/
#include <Inventor/SoDB.h>
#ifdef TGS_VERSION
#include <Inventor/events/SoMouseWheelEvent.h>
#endif
#include "PySceneManager.h"
#pragma warning ( disable : 4127 ) // conditional expression is constant in Py_DECREF
#pragma warning ( disable : 4244 ) // possible loss of data when converting int to short in SbVec2s
PyTypeObject *PySceneManager::getType()
{
static PyMemberDef members[] =
{
{"scene", T_OBJECT_EX, offsetof(Object, scene), 0, "scene graph"},
{"redisplay", T_OBJECT_EX, offsetof(Object, renderCallback), 0, "render callback"},
{NULL} /* Sentinel */
};
static PyMethodDef methods[] =
{
{"render", (PyCFunction) render, METH_NOARGS, "Renders the scene into an OpenGL context" },
{"resize", (PyCFunction) resize, METH_VARARGS, "Sets the window size" },
{"mouse_button", (PyCFunction) mouse_button, METH_VARARGS, "Sends mouse button event into the scene for processing" },
{"mouse_move", (PyCFunction) mouse_move, METH_VARARGS, "Sends mouse move event into the scene for processing" },
{"key", (PyCFunction) key, METH_VARARGS, "Sends keyboard event into the scene for processing" },
{NULL} /* Sentinel */
};
static PyTypeObject managerType =
{
PyVarObject_HEAD_INIT(NULL, 0)
"SceneManager", /* tp_name */
sizeof(Object), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) tp_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
(setattrofunc)tp_setattro, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, /* tp_flags */
"Scene manager object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
methods, /* tp_methods */
members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc) tp_init, /* tp_init */
0, /* tp_alloc */
tp_new, /* tp_new */
};
return &managerType;
}
void PySceneManager::tp_dealloc(Object* self)
{
if (self->sceneManager)
{
delete self->sceneManager;
}
Py_XDECREF(self->scene);
Py_XDECREF(self->renderCallback);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* PySceneManager::tp_new(PyTypeObject *type, PyObject* /*args*/, PyObject* /*kwds*/)
{
PySceneObject::initSoDB();
Object *self = (Object *)type->tp_alloc(type, 0);
if (self != NULL)
{
self->scene = 0;
self->renderCallback = 0;
self->sceneManager = 0;
}
return (PyObject *) self;
}
int PySceneManager::tp_init(Object *self, PyObject * /*args*/, PyObject * /*kwds*/)
{
self->scene = PySceneObject::createWrapper("Separator");
self->sceneManager = new SoSceneManager();
if (self->scene && self->sceneManager)
{
self->sceneManager->setSceneGraph((SoNode*) ((PySceneObject::Object*) self->scene)->inventorObject);
}
self->sceneManager->setRenderCallback(renderCBFunc, self);
self->sceneManager->activate();
Py_INCREF(Py_None);
self->renderCallback = Py_None;
return 0;
}
int PySceneManager::tp_setattro(Object* self, PyObject *attrname, PyObject *value)
{
int result = 0;
result = PyObject_GenericSetAttr((PyObject*) self, attrname, value);
const char *attr = PyUnicode_AsUTF8(attrname);
if (attr && (strcmp(attr, "scene") == 0))
{
if (PyNode_Check(self->scene))
{
SoFieldContainer *fc = ((PySceneObject::Object*) self->scene)->inventorObject;
if (fc && fc->isOfType(SoNode::getClassTypeId()))
{
self->sceneManager->setSceneGraph((SoNode*) fc);
self->sceneManager->scheduleRedraw();
}
else
{
PyErr_SetString(PyExc_IndexError, "Scene object must be of type SoNode");
}
}
else
{
PyErr_SetString(PyExc_IndexError, "Scene must be of type Node");
}
}
return result;
}
void PySceneManager::renderCBFunc(void *userdata, SoSceneManager * /*mgr*/)
{
Object *self = (Object *) userdata;
if ((self != NULL) && (self->renderCallback != NULL) && PyCallable_Check(self->renderCallback))
{
PyObject *value = PyObject_CallObject(self->renderCallback, NULL);
if (value != NULL)
{
Py_DECREF(value);
}
}
}
PyObject* PySceneManager::render(Object *self)
{
self->sceneManager->render();
// need to flush or nothing will be shown on OS X
glFlush();
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::resize(Object *self, PyObject *args)
{
int width = 0, height = 0;
if (PyArg_ParseTuple(args, "ii", &width, &height))
{
// for Coin both setWindowSize() and setSize() must be called
// in order to get correct rendering and event handling
self->sceneManager->setWindowSize(SbVec2s(width, height));
self->sceneManager->setSize(SbVec2s(width, height));
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::mouse_button(Object *self, PyObject *args)
{
int button = 0, state = 0, x = 0, y = 0;
if (PyArg_ParseTuple(args, "iiii", &button, &state, &x, &y))
{
y = self->sceneManager->getWindowSize()[1] - y;
#ifdef TGS_VERSION
// Coin does not have wheel event (yet)
if (button > 2)
{
// wheel
SoMouseWheelEvent ev;
ev.setTime(SbTime::getTimeOfDay());
ev.setDelta(state ? -120 : 120);
if (self->sceneManager->processEvent(&ev))
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
else
#endif
{
SoMouseButtonEvent ev;
ev.setTime(SbTime::getTimeOfDay());
ev.setPosition(SbVec2s(x, y));
ev.setButton((SoMouseButtonEvent::Button) (button + 1));
ev.setState(state ? SoMouseButtonEvent::UP : SoMouseButtonEvent::DOWN);
if (self->sceneManager->processEvent(&ev))
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::mouse_move(Object *self, PyObject *args)
{
int x = 0, y = 0;
if (PyArg_ParseTuple(args, "ii", &x, &y))
{
y = self->sceneManager->getWindowSize()[1] - y;
SoLocation2Event ev;
ev.setTime(SbTime::getTimeOfDay());
ev.setPosition(SbVec2s(x, y));
if (self->sceneManager->processEvent(&ev))
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::key(Object *self, PyObject *args)
{
char key;
if (PyArg_ParseTuple(args, "c", &key))
{
bool mapped = true;
SoKeyboardEvent ev;
ev.setTime(SbTime::getTimeOfDay());
if ((key >= 'a') && (key <= 'z'))
{
ev.setKey(SoKeyboardEvent::Key(SoKeyboardEvent::A + (key - 'a')));
}
else if ((key >= 'A') && (key <= 'Z'))
{
ev.setKey(SoKeyboardEvent::Key(SoKeyboardEvent::A + (key - 'Z')));
ev.setShiftDown(TRUE);
}
else switch (key)
{
case '\n':
case '\r': ev.setKey(SoKeyboardEvent::RETURN); break;
case '\t': ev.setKey(SoKeyboardEvent::TAB); break;
case ' ': ev.setKey(SoKeyboardEvent::SPACE); break;
case ',': ev.setKey(SoKeyboardEvent::COMMA); break;
case '.': ev.setKey(SoKeyboardEvent::PERIOD); break;
case '=': ev.setKey(SoKeyboardEvent::EQUAL); break;
case '-': ev.setKey(SoKeyboardEvent::PAD_SUBTRACT); break;
case '+': ev.setKey(SoKeyboardEvent::PAD_ADD); break;
case '/': ev.setKey(SoKeyboardEvent::PAD_DIVIDE); break;
case '*': ev.setKey(SoKeyboardEvent::PAD_MULTIPLY); break;
case '\x1b': ev.setKey(SoKeyboardEvent::ESCAPE); break;
case '\x08': ev.setKey(SoKeyboardEvent::BACKSPACE); break;
default:
mapped = false;
}
if (mapped)
{
ev.setState(SoButtonEvent::DOWN);
SbBool processed = self->sceneManager->processEvent(&ev);
ev.setState(SoButtonEvent::UP);
processed |= self->sceneManager->processEvent(&ev);
if (processed)
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
<commit_msg>Added setting background color via scene manager init.<commit_after>/**
* \file
* \brief PySceneManager class implementation.
* \author Thomas Moeller
* \details
*
* Copyright (C) the PyInventor contributors. All rights reserved.
* This file is part of PyInventor, distributed under the BSD 3-Clause
* License. For full terms see the included COPYING file.
*/
#include <Inventor/SoSceneManager.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoMouseButtonEvent.h>
#include <Inventor/events/SoKeyboardEvent.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/engines/SoEngine.h>
#include <Inventor/elements/SoGLLazyElement.h> // for GL.h, whose location is distribution specific under system/ or sys/
#include <Inventor/SoDB.h>
#ifdef TGS_VERSION
#include <Inventor/events/SoMouseWheelEvent.h>
#endif
#include "PySceneManager.h"
#pragma warning ( disable : 4127 ) // conditional expression is constant in Py_DECREF
#pragma warning ( disable : 4244 ) // possible loss of data when converting int to short in SbVec2s
PyTypeObject *PySceneManager::getType()
{
static PyMemberDef members[] =
{
{"scene", T_OBJECT_EX, offsetof(Object, scene), 0, "scene graph"},
{"redisplay", T_OBJECT_EX, offsetof(Object, renderCallback), 0, "render callback"},
{NULL} /* Sentinel */
};
static PyMethodDef methods[] =
{
{"render", (PyCFunction) render, METH_NOARGS, "Renders the scene into an OpenGL context" },
{"resize", (PyCFunction) resize, METH_VARARGS, "Sets the window size" },
{"mouse_button", (PyCFunction) mouse_button, METH_VARARGS, "Sends mouse button event into the scene for processing" },
{"mouse_move", (PyCFunction) mouse_move, METH_VARARGS, "Sends mouse move event into the scene for processing" },
{"key", (PyCFunction) key, METH_VARARGS, "Sends keyboard event into the scene for processing" },
{NULL} /* Sentinel */
};
static PyTypeObject managerType =
{
PyVarObject_HEAD_INIT(NULL, 0)
"SceneManager", /* tp_name */
sizeof(Object), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) tp_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
(setattrofunc)tp_setattro, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, /* tp_flags */
"Scene manager object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
methods, /* tp_methods */
members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc) tp_init, /* tp_init */
0, /* tp_alloc */
tp_new, /* tp_new */
};
return &managerType;
}
void PySceneManager::tp_dealloc(Object* self)
{
if (self->sceneManager)
{
delete self->sceneManager;
}
Py_XDECREF(self->scene);
Py_XDECREF(self->renderCallback);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* PySceneManager::tp_new(PyTypeObject *type, PyObject* /*args*/, PyObject* /*kwds*/)
{
PySceneObject::initSoDB();
Object *self = (Object *)type->tp_alloc(type, 0);
if (self != NULL)
{
self->scene = 0;
self->renderCallback = 0;
self->sceneManager = 0;
}
return (PyObject *) self;
}
int PySceneManager::tp_init(Object *self, PyObject *args, PyObject *kwds)
{
PyObject *background = 0;
static char *kwlist[] = { "background", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &background))
return -1;
self->scene = PySceneObject::createWrapper("Separator");
self->sceneManager = new SoSceneManager();
if (self->scene && self->sceneManager)
{
self->sceneManager->setSceneGraph((SoNode*) ((PySceneObject::Object*) self->scene)->inventorObject);
}
self->sceneManager->setRenderCallback(renderCBFunc, self);
self->sceneManager->activate();
Py_INCREF(Py_None);
self->renderCallback = Py_None;
// configure background color
if (background && PySequence_Check(background))
{
PyObject *seq = PySequence_Fast(background, "expected a sequence");
size_t n = PySequence_Size(seq);
if (n == 3)
{
SbColor color(0, 0, 0);
for (int i = 0; i < 3; ++i)
{
PyObject *seqItem = PySequence_GetItem(seq, i);
if (seqItem)
{
if (PyFloat_Check(seqItem))
color[i] = (float) PyFloat_AsDouble(seqItem);
else if (PyLong_Check(seqItem))
color[i] = (float) PyLong_AsDouble(seqItem);
}
}
if (self->sceneManager)
self->sceneManager->setBackgroundColor(color);
}
Py_XDECREF(seq);
}
return 0;
}
int PySceneManager::tp_setattro(Object* self, PyObject *attrname, PyObject *value)
{
int result = 0;
result = PyObject_GenericSetAttr((PyObject*) self, attrname, value);
const char *attr = PyUnicode_AsUTF8(attrname);
if (attr && (strcmp(attr, "scene") == 0))
{
if (PyNode_Check(self->scene))
{
SoFieldContainer *fc = ((PySceneObject::Object*) self->scene)->inventorObject;
if (fc && fc->isOfType(SoNode::getClassTypeId()))
{
self->sceneManager->setSceneGraph((SoNode*) fc);
self->sceneManager->scheduleRedraw();
}
else
{
PyErr_SetString(PyExc_IndexError, "Scene object must be of type SoNode");
}
}
else
{
PyErr_SetString(PyExc_IndexError, "Scene must be of type Node");
}
}
return result;
}
void PySceneManager::renderCBFunc(void *userdata, SoSceneManager * /*mgr*/)
{
Object *self = (Object *) userdata;
if ((self != NULL) && (self->renderCallback != NULL) && PyCallable_Check(self->renderCallback))
{
PyObject *value = PyObject_CallObject(self->renderCallback, NULL);
if (value != NULL)
{
Py_DECREF(value);
}
}
}
PyObject* PySceneManager::render(Object *self)
{
self->sceneManager->render();
// need to flush or nothing will be shown on OS X
glFlush();
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::resize(Object *self, PyObject *args)
{
int width = 0, height = 0;
if (PyArg_ParseTuple(args, "ii", &width, &height))
{
// for Coin both setWindowSize() and setSize() must be called
// in order to get correct rendering and event handling
self->sceneManager->setWindowSize(SbVec2s(width, height));
self->sceneManager->setSize(SbVec2s(width, height));
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::mouse_button(Object *self, PyObject *args)
{
int button = 0, state = 0, x = 0, y = 0;
if (PyArg_ParseTuple(args, "iiii", &button, &state, &x, &y))
{
y = self->sceneManager->getWindowSize()[1] - y;
#ifdef TGS_VERSION
// Coin does not have wheel event (yet)
if (button > 2)
{
// wheel
SoMouseWheelEvent ev;
ev.setTime(SbTime::getTimeOfDay());
ev.setDelta(state ? -120 : 120);
if (self->sceneManager->processEvent(&ev))
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
else
#endif
{
SoMouseButtonEvent ev;
ev.setTime(SbTime::getTimeOfDay());
ev.setPosition(SbVec2s(x, y));
ev.setButton((SoMouseButtonEvent::Button) (button + 1));
ev.setState(state ? SoMouseButtonEvent::UP : SoMouseButtonEvent::DOWN);
if (self->sceneManager->processEvent(&ev))
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::mouse_move(Object *self, PyObject *args)
{
int x = 0, y = 0;
if (PyArg_ParseTuple(args, "ii", &x, &y))
{
y = self->sceneManager->getWindowSize()[1] - y;
SoLocation2Event ev;
ev.setTime(SbTime::getTimeOfDay());
ev.setPosition(SbVec2s(x, y));
if (self->sceneManager->processEvent(&ev))
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* PySceneManager::key(Object *self, PyObject *args)
{
char key;
if (PyArg_ParseTuple(args, "c", &key))
{
bool mapped = true;
SoKeyboardEvent ev;
ev.setTime(SbTime::getTimeOfDay());
if ((key >= 'a') && (key <= 'z'))
{
ev.setKey(SoKeyboardEvent::Key(SoKeyboardEvent::A + (key - 'a')));
}
else if ((key >= 'A') && (key <= 'Z'))
{
ev.setKey(SoKeyboardEvent::Key(SoKeyboardEvent::A + (key - 'Z')));
ev.setShiftDown(TRUE);
}
else switch (key)
{
case '\n':
case '\r': ev.setKey(SoKeyboardEvent::RETURN); break;
case '\t': ev.setKey(SoKeyboardEvent::TAB); break;
case ' ': ev.setKey(SoKeyboardEvent::SPACE); break;
case ',': ev.setKey(SoKeyboardEvent::COMMA); break;
case '.': ev.setKey(SoKeyboardEvent::PERIOD); break;
case '=': ev.setKey(SoKeyboardEvent::EQUAL); break;
case '-': ev.setKey(SoKeyboardEvent::PAD_SUBTRACT); break;
case '+': ev.setKey(SoKeyboardEvent::PAD_ADD); break;
case '/': ev.setKey(SoKeyboardEvent::PAD_DIVIDE); break;
case '*': ev.setKey(SoKeyboardEvent::PAD_MULTIPLY); break;
case '\x1b': ev.setKey(SoKeyboardEvent::ESCAPE); break;
case '\x08': ev.setKey(SoKeyboardEvent::BACKSPACE); break;
default:
mapped = false;
}
if (mapped)
{
ev.setState(SoButtonEvent::DOWN);
SbBool processed = self->sceneManager->processEvent(&ev);
ev.setState(SoButtonEvent::UP);
processed |= self->sceneManager->processEvent(&ev);
if (processed)
{
SoDB::getSensorManager()->processDelayQueue(FALSE);
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
<|endoftext|> |
<commit_before>//
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#include "File.h"
#include "UnicodeUtil.h"
#include <streambuf>
namespace saba
{
saba::File::File()
: m_fp(nullptr)
, m_fileSize(0)
, m_badFlag(false)
{
}
File::~File()
{
Close();
}
bool File::OpenFile(const char * filepath, const char * mode)
{
if (m_fp != nullptr)
{
Close();
}
#if _WIN32
std::wstring wFilepath;
if (!TryToWString(filepath, wFilepath))
{
return false;
}
std::wstring wMode = ToWString(mode);
auto err = _wfopen_s(&m_fp, wFilepath.c_str(), wMode.c_str());
if (err != 0)
{
return false;
}
#else
m_fp = fopen(filepath, mode);
if (m_fp == nullptr)
{
return false;
}
#endif
ClearBadFlag();
Seek(0, SeekDir::End);
m_fileSize = Tell();
Seek(0, SeekDir::Begin);
if (IsBad())
{
Close();
return false;
}
return true;
}
bool File::Open(const char * filepath)
{
return OpenFile(filepath, "rb");
}
bool File::OpenText(const char * filepath)
{
return OpenFile(filepath, "r");
}
bool File::Create(const char * filepath)
{
return OpenFile(filepath, "wb");
}
bool File::CreateText(const char * filepath)
{
return OpenFile(filepath, "w");
}
void saba::File::Close()
{
if (m_fp != nullptr)
{
fclose(m_fp);
m_fp = nullptr;
m_fileSize = 0;
m_badFlag = false;
}
}
bool saba::File::IsOpen()
{
return m_fp != nullptr;
}
File::Offset File::GetSize() const
{
return m_fileSize;
}
bool File::IsBad() const
{
return m_badFlag;
}
void File::ClearBadFlag()
{
m_badFlag = false;
}
FILE * saba::File::GetFilePointer() const
{
return m_fp;
}
bool saba::File::ReadAll(std::vector<char>* buffer)
{
if (buffer == nullptr)
{
return false;
}
buffer->resize(m_fileSize);
Seek(0, SeekDir::Begin);
if (!Read(&(*buffer)[0], m_fileSize))
{
return false;
}
return true;
}
bool saba::File::Seek(Offset offset, SeekDir origin)
{
if (m_fp == nullptr)
{
return false;
}
int cOrigin = 0;
switch (origin)
{
case SeekDir::Begin:
cOrigin = SEEK_SET;
break;
case SeekDir::Current:
cOrigin = SEEK_CUR;
break;
case SeekDir::End:
cOrigin = SEEK_END;
break;
default:
return false;
}
#if _WIN32
if (_fseeki64(m_fp, offset, cOrigin) != 0)
{
m_badFlag = true;
return false;
}
#else // _WIN32
if (fseek(m_fp, offset, cOrigin) != 0)
{
m_badFlag = true;
return false;
}
#endif // _WIN32
return true;
}
File::Offset File::Tell()
{
if (m_fp == nullptr)
{
return -1;
}
#if _WIN32
return (Offset)_ftelli64(m_fp);
#else // _WIN32
return (Offset)ftell(m_fp);
#endif // _WIN32
}
TextFileReader::TextFileReader(const char * filepath)
{
Open(filepath);
}
TextFileReader::TextFileReader(const std::string & filepath)
{
Open(filepath);
}
bool TextFileReader::Open(const char * filepath)
{
#if _WIN32
std::wstring wFilepath;
if (!TryToWString(filepath, wFilepath))
{
return false;
}
m_ifs.open(wFilepath);
#else
m_ifs.open(filepath, std::ios::binary);
#endif
return m_ifs.is_open();
}
bool TextFileReader::Open(const std::string & filepath)
{
return Open(filepath.c_str());
}
void TextFileReader::Close()
{
m_ifs.close();
}
bool TextFileReader::IsOpen()
{
return m_ifs.is_open();
}
std::string TextFileReader::ReadLine()
{
if (!IsOpen() || IsEof())
{
return "";
}
std::istreambuf_iterator<char> it(m_ifs);
std::istreambuf_iterator<char> end;
std::string line;
auto outputIt = std::back_inserter(line);
while (it != end && (*it) != '\r' && (*it) != '\n')
{
(*outputIt) = (*it);
++outputIt;
++it;
}
if (it != end)
{
auto ch = *it;
++it;
if (it != end && ch == '\r' && (*it) == '\n')
{
++it;
}
}
return line;
}
void TextFileReader::ReadAllLines(std::vector<std::string>& lines)
{
lines.clear();
if (!IsOpen() || IsEof())
{
return;
}
while (!IsEof())
{
lines.emplace_back(ReadLine());
}
}
std::string TextFileReader::ReadAll()
{
std::istreambuf_iterator<char> begin(m_ifs);
std::istreambuf_iterator<char> end;
return std::string(begin, end);
}
bool TextFileReader::IsEof()
{
if (!m_ifs.is_open())
{
return m_ifs.eof();
}
if (m_ifs.eof())
{
return true;
}
int ch = m_ifs.peek();
if (ch == std::ifstream::traits_type::eof())
{
return true;
}
return false;
}
bool OpenFromUtf8Path(const std::string & filepath, std::ifstream & ifs, std::ios_base::openmode mode)
{
#if _WIN32
std::wstring wFilepath;
if (!TryToWString(filepath, wFilepath))
{
return false;
}
ifs.open(wFilepath, mode);
#else
ifs.open(filepath, mode);
#endif
return ifs.is_open();
}
}
<commit_msg>fix vs2015 build error<commit_after>//
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#include "File.h"
#include "UnicodeUtil.h"
#include <streambuf>
#include <iterator>
namespace saba
{
saba::File::File()
: m_fp(nullptr)
, m_fileSize(0)
, m_badFlag(false)
{
}
File::~File()
{
Close();
}
bool File::OpenFile(const char * filepath, const char * mode)
{
if (m_fp != nullptr)
{
Close();
}
#if _WIN32
std::wstring wFilepath;
if (!TryToWString(filepath, wFilepath))
{
return false;
}
std::wstring wMode = ToWString(mode);
auto err = _wfopen_s(&m_fp, wFilepath.c_str(), wMode.c_str());
if (err != 0)
{
return false;
}
#else
m_fp = fopen(filepath, mode);
if (m_fp == nullptr)
{
return false;
}
#endif
ClearBadFlag();
Seek(0, SeekDir::End);
m_fileSize = Tell();
Seek(0, SeekDir::Begin);
if (IsBad())
{
Close();
return false;
}
return true;
}
bool File::Open(const char * filepath)
{
return OpenFile(filepath, "rb");
}
bool File::OpenText(const char * filepath)
{
return OpenFile(filepath, "r");
}
bool File::Create(const char * filepath)
{
return OpenFile(filepath, "wb");
}
bool File::CreateText(const char * filepath)
{
return OpenFile(filepath, "w");
}
void saba::File::Close()
{
if (m_fp != nullptr)
{
fclose(m_fp);
m_fp = nullptr;
m_fileSize = 0;
m_badFlag = false;
}
}
bool saba::File::IsOpen()
{
return m_fp != nullptr;
}
File::Offset File::GetSize() const
{
return m_fileSize;
}
bool File::IsBad() const
{
return m_badFlag;
}
void File::ClearBadFlag()
{
m_badFlag = false;
}
FILE * saba::File::GetFilePointer() const
{
return m_fp;
}
bool saba::File::ReadAll(std::vector<char>* buffer)
{
if (buffer == nullptr)
{
return false;
}
buffer->resize(m_fileSize);
Seek(0, SeekDir::Begin);
if (!Read(&(*buffer)[0], m_fileSize))
{
return false;
}
return true;
}
bool saba::File::Seek(Offset offset, SeekDir origin)
{
if (m_fp == nullptr)
{
return false;
}
int cOrigin = 0;
switch (origin)
{
case SeekDir::Begin:
cOrigin = SEEK_SET;
break;
case SeekDir::Current:
cOrigin = SEEK_CUR;
break;
case SeekDir::End:
cOrigin = SEEK_END;
break;
default:
return false;
}
#if _WIN32
if (_fseeki64(m_fp, offset, cOrigin) != 0)
{
m_badFlag = true;
return false;
}
#else // _WIN32
if (fseek(m_fp, offset, cOrigin) != 0)
{
m_badFlag = true;
return false;
}
#endif // _WIN32
return true;
}
File::Offset File::Tell()
{
if (m_fp == nullptr)
{
return -1;
}
#if _WIN32
return (Offset)_ftelli64(m_fp);
#else // _WIN32
return (Offset)ftell(m_fp);
#endif // _WIN32
}
TextFileReader::TextFileReader(const char * filepath)
{
Open(filepath);
}
TextFileReader::TextFileReader(const std::string & filepath)
{
Open(filepath);
}
bool TextFileReader::Open(const char * filepath)
{
#if _WIN32
std::wstring wFilepath;
if (!TryToWString(filepath, wFilepath))
{
return false;
}
m_ifs.open(wFilepath);
#else
m_ifs.open(filepath, std::ios::binary);
#endif
return m_ifs.is_open();
}
bool TextFileReader::Open(const std::string & filepath)
{
return Open(filepath.c_str());
}
void TextFileReader::Close()
{
m_ifs.close();
}
bool TextFileReader::IsOpen()
{
return m_ifs.is_open();
}
std::string TextFileReader::ReadLine()
{
if (!IsOpen() || IsEof())
{
return "";
}
std::istreambuf_iterator<char> it(m_ifs);
std::istreambuf_iterator<char> end;
std::string line;
auto outputIt = std::back_inserter(line);
while (it != end && (*it) != '\r' && (*it) != '\n')
{
(*outputIt) = (*it);
++outputIt;
++it;
}
if (it != end)
{
auto ch = *it;
++it;
if (it != end && ch == '\r' && (*it) == '\n')
{
++it;
}
}
return line;
}
void TextFileReader::ReadAllLines(std::vector<std::string>& lines)
{
lines.clear();
if (!IsOpen() || IsEof())
{
return;
}
while (!IsEof())
{
lines.emplace_back(ReadLine());
}
}
std::string TextFileReader::ReadAll()
{
std::istreambuf_iterator<char> begin(m_ifs);
std::istreambuf_iterator<char> end;
return std::string(begin, end);
}
bool TextFileReader::IsEof()
{
if (!m_ifs.is_open())
{
return m_ifs.eof();
}
if (m_ifs.eof())
{
return true;
}
int ch = m_ifs.peek();
if (ch == std::ifstream::traits_type::eof())
{
return true;
}
return false;
}
bool OpenFromUtf8Path(const std::string & filepath, std::ifstream & ifs, std::ios_base::openmode mode)
{
#if _WIN32
std::wstring wFilepath;
if (!TryToWString(filepath, wFilepath))
{
return false;
}
ifs.open(wFilepath, mode);
#else
ifs.open(filepath, mode);
#endif
return ifs.is_open();
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <sampgdk/core.h>
#include <sampgdk/a_samp.h>
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/debug-helpers.h>
#include "SampSharp.h"
#include "ConfigReader.h"
#include "StringUtil.h"
#include "MonoUtil.h"
#include "PathUtil.h"
#include "Benchmark.h"
#include "amxplugin.cpp"
using sampgdk::logprintf;
extern void *pAMXFunctions;
PLUGIN_EXPORT unsigned int PLUGIN_CALL
Supports() {
return sampgdk::Supports() | SUPPORTS_PROCESS_TICK;
}
PLUGIN_EXPORT bool PLUGIN_CALL
Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
if (!sampgdk::Load(ppData)) {
return false;
}
//read config
ConfigReader server_cfg("server.cfg");
std::string gamemode = "gamemode/Default.GameMode.dll Default.GameMode:GameMode";
std::string path, name_space, klass, symbols;
server_cfg.GetOptionAsString("gamemode", gamemode);
server_cfg.GetOptionAsString("symbols", symbols);
std::stringstream gamemode_stream(gamemode);
std::getline(gamemode_stream, path, ' ');
std::getline(gamemode_stream, name_space, ':');
std::getline(gamemode_stream, klass, '\n');
StringUtil::TrimString(path);
StringUtil::TrimString(name_space);
StringUtil::TrimString(klass);
//init mono
#ifdef _WIN32
mono_set_dirs(PathUtil::GetLibDirectory().c_str(),
PathUtil::GetConfigDirectory().c_str());
#endif
mono_debug_init(MONO_DEBUG_FORMAT_MONO);
MonoDomain *root = mono_jit_init(PathUtil::GetPathInBin(path).c_str());
//generate symbol files
#ifdef _WIN32
if(symbols.length() > 0) {
logprintf("[SampSharp] Generating symbol files");
std::stringstream symbols_stream(symbols);
std::string file;
while (std::getline(symbols_stream, file, ' ')) {
if(file.length() > 0) {
logprintf("[SampSharp] Processing \"%s\"...", file.c_str());
MonoUtil::GenerateSymbols(file.c_str());
}
}
sampgdk::logprintf("[SampSharp] Done!\n");
}
#endif
//load gamemode
logprintf("[SampSharp] Loading gamemode: %s::%s from \"%s\".",
(char *)name_space.c_str(),
(char *)klass.c_str(),
(char *)path.c_str());
MonoImage *image = mono_assembly_get_image(
mono_assembly_open(PathUtil::GetPathInBin(path).c_str(), NULL));
auto class_from_name = mono_class_from_name(image, name_space.c_str(), klass.c_str());
if (class_from_name == NULL)
{
logprintf("[SampShart] %s::%s is not a valid Namespace:Class combination inside \"%s\".",
(char *)name_space.c_str(),
(char *)klass.c_str(),
(char *)path.c_str());
return true;
}
SampSharp::Load(root, image, class_from_name);
logprintf("[SampSharp] SampSharp is ready!\n");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL
Unload() {
SampSharp::Unload();
sampgdk::Unload();
}
PLUGIN_EXPORT void PLUGIN_CALL
ProcessTick() {
SampSharp::ProcessTick();
sampgdk::ProcessTick();
}
PLUGIN_EXPORT bool PLUGIN_CALL
OnPublicCall(AMX *amx, const char *name, cell *params, cell *retval) {
#ifdef DO_BENCHMARK
if(!strcmp(name, "OnGameModeInit")) {
Benchmark();
}
#endif
return SampSharp::ProcessPublicCall(amx, name, params, retval);
}
<commit_msg>Improved code to avoid duplicate calls to c_str for namespace/class/path strings<commit_after>#include <string>
#include <sampgdk/core.h>
#include <sampgdk/a_samp.h>
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/debug-helpers.h>
#include "SampSharp.h"
#include "ConfigReader.h"
#include "StringUtil.h"
#include "MonoUtil.h"
#include "PathUtil.h"
#include "Benchmark.h"
#include "amxplugin.cpp"
using sampgdk::logprintf;
extern void *pAMXFunctions;
PLUGIN_EXPORT unsigned int PLUGIN_CALL
Supports() {
return sampgdk::Supports() | SUPPORTS_PROCESS_TICK;
}
PLUGIN_EXPORT bool PLUGIN_CALL
Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
if (!sampgdk::Load(ppData)) {
return false;
}
//read config
ConfigReader server_cfg("server.cfg");
std::string gamemode = "gamemode/Default.GameMode.dll Default.GameMode:GameMode";
std::string path, name_space, klass, symbols;
server_cfg.GetOptionAsString("gamemode", gamemode);
server_cfg.GetOptionAsString("symbols", symbols);
std::stringstream gamemode_stream(gamemode);
std::getline(gamemode_stream, path, ' ');
std::getline(gamemode_stream, name_space, ':');
std::getline(gamemode_stream, klass, '\n');
StringUtil::TrimString(path);
StringUtil::TrimString(name_space);
StringUtil::TrimString(klass);
//init mono
#ifdef _WIN32
mono_set_dirs(PathUtil::GetLibDirectory().c_str(),
PathUtil::GetConfigDirectory().c_str());
#endif
mono_debug_init(MONO_DEBUG_FORMAT_MONO);
MonoDomain *root = mono_jit_init(PathUtil::GetPathInBin(path).c_str());
//generate symbol files
#ifdef _WIN32
if(symbols.length() > 0) {
logprintf("[SampSharp] Generating symbol files");
std::stringstream symbols_stream(symbols);
std::string file;
while (std::getline(symbols_stream, file, ' ')) {
if(file.length() > 0) {
logprintf("[SampSharp] Processing \"%s\"...", file.c_str());
MonoUtil::GenerateSymbols(file.c_str());
}
}
sampgdk::logprintf("[SampSharp] Done!\n");
}
#endif
//load gamemode
auto namespace_ctr = (char *)name_space.c_str();
auto klass_ctr = (char *)klass.c_str();
auto path_ctr = (char *)path.c_str();
logprintf("[SampSharp] Loading gamemode: %s::%s from \"%s\".",
namespace_ctr,
klass_ctr,
path_ctr);
MonoImage *image = mono_assembly_get_image(
mono_assembly_open(PathUtil::GetPathInBin(path).c_str(), NULL));
auto class_from_name = mono_class_from_name(image, namespace_ctr, klass_ctr);
if (class_from_name == NULL)
{
logprintf("[SampShart] %s::%s is not a valid Namespace:Class combination inside \"%s\".",
namespace_ctr,
klass_ctr,
path_ctr);
return true;
}
SampSharp::Load(root, image, class_from_name);
logprintf("[SampSharp] SampSharp is ready!\n");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL
Unload() {
SampSharp::Unload();
sampgdk::Unload();
}
PLUGIN_EXPORT void PLUGIN_CALL
ProcessTick() {
SampSharp::ProcessTick();
sampgdk::ProcessTick();
}
PLUGIN_EXPORT bool PLUGIN_CALL
OnPublicCall(AMX *amx, const char *name, cell *params, cell *retval) {
#ifdef DO_BENCHMARK
if(!strcmp(name, "OnGameModeInit")) {
Benchmark();
}
#endif
return SampSharp::ProcessPublicCall(amx, name, params, retval);
}
<|endoftext|> |
<commit_before>//===-- llvm/CallingConvLower.cpp - Calling Conventions -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CCState class, used for lowering and implementing
// calling conventions.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/SelectionDAGNodes.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
CCState::CCState(unsigned CC, bool isVarArg, const TargetMachine &tm,
SmallVector<CCValAssign, 16> &locs)
: CallingConv(CC), IsVarArg(isVarArg), TM(tm),
TRI(*TM.getRegisterInfo()), Locs(locs) {
// No stack is used.
StackOffset = 0;
UsedRegs.resize(TRI.getNumRegs());
}
// HandleByVal - Allocate a stack slot large enough to pass an argument by
// value. The size and alignment information of the argument is encoded in its
// parameter attribute.
void CCState::HandleByVal(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
int MinSize, int MinAlign,
ISD::ArgFlagsTy ArgFlags) {
unsigned Align = ArgFlags.getByValAlign();
unsigned Size = ArgFlags.getByValSize();
if (MinSize > (int)Size)
Size = MinSize;
if (MinAlign > (int)Align)
Align = MinAlign;
unsigned Offset = AllocateStack(Size, Align);
addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
}
/// MarkAllocated - Mark a register and all of its aliases as allocated.
void CCState::MarkAllocated(unsigned Reg) {
UsedRegs[Reg/32] |= 1 << (Reg&31);
if (const unsigned *RegAliases = TRI.getAliasSet(Reg))
for (; (Reg = *RegAliases); ++RegAliases)
UsedRegs[Reg/32] |= 1 << (Reg&31);
}
/// AnalyzeFormalArguments - Analyze an ISD::FORMAL_ARGUMENTS node,
/// incorporating info about the formals into this state.
void CCState::AnalyzeFormalArguments(SDNode *TheArgs, CCAssignFn Fn) {
unsigned NumArgs = TheArgs->getNumValues()-1;
for (unsigned i = 0; i != NumArgs; ++i) {
MVT ArgVT = TheArgs->getValueType(i);
ISD::ArgFlagsTy ArgFlags =
cast<ARG_FLAGSSDNode>(TheArgs->getOperand(3+i))->getArgFlags();
if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, *this)) {
cerr << "Formal argument #" << i << " has unhandled type "
<< ArgVT.getMVTString() << "\n";
abort();
}
}
}
/// AnalyzeReturn - Analyze the returned values of an ISD::RET node,
/// incorporating info about the result values into this state.
void CCState::AnalyzeReturn(SDNode *TheRet, CCAssignFn Fn) {
// Determine which register each value should be copied into.
for (unsigned i = 0, e = TheRet->getNumOperands() / 2; i != e; ++i) {
MVT VT = TheRet->getOperand(i*2+1).getValueType();
ISD::ArgFlagsTy ArgFlags =
cast<ARG_FLAGSSDNode>(TheRet->getOperand(i*2+2))->getArgFlags();
if (Fn(i, VT, VT, CCValAssign::Full, ArgFlags, *this)){
cerr << "Return operand #" << i << " has unhandled type "
<< VT.getMVTString() << "\n";
abort();
}
}
}
/// AnalyzeCallOperands - Analyze an ISD::CALL node, incorporating info
/// about the passed values into this state.
void CCState::AnalyzeCallOperands(SDNode *TheCall, CCAssignFn Fn) {
unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
for (unsigned i = 0; i != NumOps; ++i) {
MVT ArgVT = TheCall->getOperand(5+2*i).getValueType();
ISD::ArgFlagsTy ArgFlags =
cast<ARG_FLAGSSDNode>(TheCall->getOperand(5+2*i+1))->getArgFlags();
if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, *this)) {
cerr << "Call operand #" << i << " has unhandled type "
<< ArgVT.getMVTString() << "\n";
abort();
}
}
}
/// AnalyzeCallResult - Analyze the return values of an ISD::CALL node,
/// incorporating info about the passed values into this state.
void CCState::AnalyzeCallResult(SDNode *TheCall, CCAssignFn Fn) {
for (unsigned i = 0, e = TheCall->getNumValues() - 1; i != e; ++i) {
MVT VT = TheCall->getValueType(i);
if (Fn(i, VT, VT, CCValAssign::Full, ISD::ArgFlagsTy(), *this)) {
cerr << "Call result #" << i << " has unhandled type "
<< VT.getMVTString() << "\n";
abort();
}
}
}
<commit_msg>Correct the allocation size for CCState's UsedRegs member, which only needs one bit for each register. UsedRegs is a SmallVector sized at 16, so this eliminates a heap allocation/free for every call and return processed by Legalize on most targets.<commit_after>//===-- llvm/CallingConvLower.cpp - Calling Conventions -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CCState class, used for lowering and implementing
// calling conventions.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/SelectionDAGNodes.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
CCState::CCState(unsigned CC, bool isVarArg, const TargetMachine &tm,
SmallVector<CCValAssign, 16> &locs)
: CallingConv(CC), IsVarArg(isVarArg), TM(tm),
TRI(*TM.getRegisterInfo()), Locs(locs) {
// No stack is used.
StackOffset = 0;
UsedRegs.resize((TRI.getNumRegs()+31)/32);
}
// HandleByVal - Allocate a stack slot large enough to pass an argument by
// value. The size and alignment information of the argument is encoded in its
// parameter attribute.
void CCState::HandleByVal(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
int MinSize, int MinAlign,
ISD::ArgFlagsTy ArgFlags) {
unsigned Align = ArgFlags.getByValAlign();
unsigned Size = ArgFlags.getByValSize();
if (MinSize > (int)Size)
Size = MinSize;
if (MinAlign > (int)Align)
Align = MinAlign;
unsigned Offset = AllocateStack(Size, Align);
addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
}
/// MarkAllocated - Mark a register and all of its aliases as allocated.
void CCState::MarkAllocated(unsigned Reg) {
UsedRegs[Reg/32] |= 1 << (Reg&31);
if (const unsigned *RegAliases = TRI.getAliasSet(Reg))
for (; (Reg = *RegAliases); ++RegAliases)
UsedRegs[Reg/32] |= 1 << (Reg&31);
}
/// AnalyzeFormalArguments - Analyze an ISD::FORMAL_ARGUMENTS node,
/// incorporating info about the formals into this state.
void CCState::AnalyzeFormalArguments(SDNode *TheArgs, CCAssignFn Fn) {
unsigned NumArgs = TheArgs->getNumValues()-1;
for (unsigned i = 0; i != NumArgs; ++i) {
MVT ArgVT = TheArgs->getValueType(i);
ISD::ArgFlagsTy ArgFlags =
cast<ARG_FLAGSSDNode>(TheArgs->getOperand(3+i))->getArgFlags();
if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, *this)) {
cerr << "Formal argument #" << i << " has unhandled type "
<< ArgVT.getMVTString() << "\n";
abort();
}
}
}
/// AnalyzeReturn - Analyze the returned values of an ISD::RET node,
/// incorporating info about the result values into this state.
void CCState::AnalyzeReturn(SDNode *TheRet, CCAssignFn Fn) {
// Determine which register each value should be copied into.
for (unsigned i = 0, e = TheRet->getNumOperands() / 2; i != e; ++i) {
MVT VT = TheRet->getOperand(i*2+1).getValueType();
ISD::ArgFlagsTy ArgFlags =
cast<ARG_FLAGSSDNode>(TheRet->getOperand(i*2+2))->getArgFlags();
if (Fn(i, VT, VT, CCValAssign::Full, ArgFlags, *this)){
cerr << "Return operand #" << i << " has unhandled type "
<< VT.getMVTString() << "\n";
abort();
}
}
}
/// AnalyzeCallOperands - Analyze an ISD::CALL node, incorporating info
/// about the passed values into this state.
void CCState::AnalyzeCallOperands(SDNode *TheCall, CCAssignFn Fn) {
unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
for (unsigned i = 0; i != NumOps; ++i) {
MVT ArgVT = TheCall->getOperand(5+2*i).getValueType();
ISD::ArgFlagsTy ArgFlags =
cast<ARG_FLAGSSDNode>(TheCall->getOperand(5+2*i+1))->getArgFlags();
if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, *this)) {
cerr << "Call operand #" << i << " has unhandled type "
<< ArgVT.getMVTString() << "\n";
abort();
}
}
}
/// AnalyzeCallResult - Analyze the return values of an ISD::CALL node,
/// incorporating info about the passed values into this state.
void CCState::AnalyzeCallResult(SDNode *TheCall, CCAssignFn Fn) {
for (unsigned i = 0, e = TheCall->getNumValues() - 1; i != e; ++i) {
MVT VT = TheCall->getValueType(i);
if (Fn(i, VT, VT, CCValAssign::Full, ISD::ArgFlagsTy(), *this)) {
cerr << "Call result #" << i << " has unhandled type "
<< VT.getMVTString() << "\n";
abort();
}
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/geometry/envelope.hpp>
#include <mapnik/geometry/envelope_impl.hpp>
#include <mapnik/text/symbolizer_helpers.hpp>
namespace mapnik { namespace geometry {
template MAPNIK_DECL mapnik::box2d<double> envelope(geometry<double> const& geom);
// single
template MAPNIK_DECL mapnik::box2d<double> envelope(point<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(line_string<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(polygon<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(linear_ring<double> const& geom);
// multi
template MAPNIK_DECL mapnik::box2d<double> envelope(multi_point<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(multi_line_string<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(multi_polygon<double> const& geom);
// collection
template MAPNIK_DECL mapnik::box2d<double> envelope(geometry_collection<double> const& geom);
} // end ns geometry
} // end ns mapnik
<commit_msg>remove unused include directive<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/geometry/envelope.hpp>
#include <mapnik/geometry/envelope_impl.hpp>
namespace mapnik { namespace geometry {
template MAPNIK_DECL mapnik::box2d<double> envelope(geometry<double> const& geom);
// single
template MAPNIK_DECL mapnik::box2d<double> envelope(point<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(line_string<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(polygon<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(linear_ring<double> const& geom);
// multi
template MAPNIK_DECL mapnik::box2d<double> envelope(multi_point<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(multi_line_string<double> const& geom);
template MAPNIK_DECL mapnik::box2d<double> envelope(multi_polygon<double> const& geom);
// collection
template MAPNIK_DECL mapnik::box2d<double> envelope(geometry_collection<double> const& geom);
} // end ns geometry
} // end ns mapnik
<|endoftext|> |
<commit_before>//===-- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// \file
// This file implements a TargetTransformInfo analysis pass specific to the
// AMDGPU target machine. It uses the target's detailed information to provide
// more precise answers to certain TTI queries, while letting the target
// independent and default TTI implementations handle the rest.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUTargetMachine.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/CostTable.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
#define DEBUG_TYPE "AMDGPUtti"
// Declare the pass initialization routine locally as target-specific passes
// don't have a target-wide initialization entry point, and so we rely on the
// pass constructor initialization.
namespace llvm {
void initializeAMDGPUTTIPass(PassRegistry &);
}
namespace {
class AMDGPUTTI final : public ImmutablePass, public TargetTransformInfo {
const AMDGPUTargetMachine *TM;
const AMDGPUSubtarget *ST;
const AMDGPUTargetLowering *TLI;
/// Estimate the overhead of scalarizing an instruction. Insert and Extract
/// are set if the result needs to be inserted and/or extracted from vectors.
unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
public:
AMDGPUTTI() : ImmutablePass(ID), TM(nullptr), ST(nullptr), TLI(nullptr) {
llvm_unreachable("This pass cannot be directly constructed");
}
AMDGPUTTI(const AMDGPUTargetMachine *TM)
: ImmutablePass(ID), TM(TM), ST(TM->getSubtargetImpl()),
TLI(TM->getTargetLowering()) {
initializeAMDGPUTTIPass(*PassRegistry::getPassRegistry());
}
void initializePass() override { pushTTIStack(this); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
TargetTransformInfo::getAnalysisUsage(AU);
}
/// Pass identification.
static char ID;
/// Provide necessary pointer adjustments for the two base classes.
void *getAdjustedAnalysisPointer(const void *ID) override {
if (ID == &TargetTransformInfo::ID)
return (TargetTransformInfo *)this;
return this;
}
bool hasBranchDivergence() const override;
void getUnrollingPreferences(Loop *L,
UnrollingPreferences &UP) const override;
PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const override;
unsigned getNumberOfRegisters(bool Vector) const override;
unsigned getRegisterBitWidth(bool Vector) const override;
unsigned getMaximumUnrollFactor() const override;
/// @}
};
} // end anonymous namespace
INITIALIZE_AG_PASS(AMDGPUTTI, TargetTransformInfo, "AMDGPUtti",
"AMDGPU Target Transform Info", true, true, false)
char AMDGPUTTI::ID = 0;
ImmutablePass *
llvm::createAMDGPUTargetTransformInfoPass(const AMDGPUTargetMachine *TM) {
return new AMDGPUTTI(TM);
}
bool AMDGPUTTI::hasBranchDivergence() const { return true; }
void AMDGPUTTI::getUnrollingPreferences(Loop *L,
UnrollingPreferences &UP) const {
for (const BasicBlock *BB : L->getBlocks()) {
for (const Instruction &I : *BB) {
const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
if (!GEP || GEP->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
continue;
const Value *Ptr = GEP->getPointerOperand();
const AllocaInst *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr));
if (Alloca) {
// We want to do whatever we can to limit the number of alloca
// instructions that make it through to the code generator. allocas
// require us to use indirect addressing, which is slow and prone to
// compiler bugs. If this loop does an address calculation on an
// alloca ptr, then we want to use a higher than normal loop unroll
// threshold. This will give SROA a better chance to eliminate these
// allocas.
//
// Don't use the maximum allowed value here as it will make some
// programs way too big.
UP.Threshold = 500;
}
}
}
}
AMDGPUTTI::PopcntSupportKind
AMDGPUTTI::getPopcntSupport(unsigned TyWidth) const {
assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
return ST->hasBCNT(TyWidth) ? PSK_FastHardware : PSK_Software;
}
unsigned AMDGPUTTI::getNumberOfRegisters(bool Vec) const {
if (Vec)
return 0;
// Number of VGPRs on SI.
if (ST->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS)
return 256;
return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
}
unsigned AMDGPUTTI::getRegisterBitWidth(bool) const {
return 32;
}
unsigned AMDGPUTTI::getMaximumUnrollFactor() const {
// Semi-arbitrary large amount.
return 64;
}
<commit_msg>R600/SI: Allow partial unrolling and increase thresholds.<commit_after>//===-- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// \file
// This file implements a TargetTransformInfo analysis pass specific to the
// AMDGPU target machine. It uses the target's detailed information to provide
// more precise answers to certain TTI queries, while letting the target
// independent and default TTI implementations handle the rest.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUTargetMachine.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/CostTable.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
#define DEBUG_TYPE "AMDGPUtti"
// Declare the pass initialization routine locally as target-specific passes
// don't have a target-wide initialization entry point, and so we rely on the
// pass constructor initialization.
namespace llvm {
void initializeAMDGPUTTIPass(PassRegistry &);
}
namespace {
class AMDGPUTTI final : public ImmutablePass, public TargetTransformInfo {
const AMDGPUTargetMachine *TM;
const AMDGPUSubtarget *ST;
const AMDGPUTargetLowering *TLI;
/// Estimate the overhead of scalarizing an instruction. Insert and Extract
/// are set if the result needs to be inserted and/or extracted from vectors.
unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
public:
AMDGPUTTI() : ImmutablePass(ID), TM(nullptr), ST(nullptr), TLI(nullptr) {
llvm_unreachable("This pass cannot be directly constructed");
}
AMDGPUTTI(const AMDGPUTargetMachine *TM)
: ImmutablePass(ID), TM(TM), ST(TM->getSubtargetImpl()),
TLI(TM->getTargetLowering()) {
initializeAMDGPUTTIPass(*PassRegistry::getPassRegistry());
}
void initializePass() override { pushTTIStack(this); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
TargetTransformInfo::getAnalysisUsage(AU);
}
/// Pass identification.
static char ID;
/// Provide necessary pointer adjustments for the two base classes.
void *getAdjustedAnalysisPointer(const void *ID) override {
if (ID == &TargetTransformInfo::ID)
return (TargetTransformInfo *)this;
return this;
}
bool hasBranchDivergence() const override;
void getUnrollingPreferences(Loop *L,
UnrollingPreferences &UP) const override;
PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const override;
unsigned getNumberOfRegisters(bool Vector) const override;
unsigned getRegisterBitWidth(bool Vector) const override;
unsigned getMaximumUnrollFactor() const override;
/// @}
};
} // end anonymous namespace
INITIALIZE_AG_PASS(AMDGPUTTI, TargetTransformInfo, "AMDGPUtti",
"AMDGPU Target Transform Info", true, true, false)
char AMDGPUTTI::ID = 0;
ImmutablePass *
llvm::createAMDGPUTargetTransformInfoPass(const AMDGPUTargetMachine *TM) {
return new AMDGPUTTI(TM);
}
bool AMDGPUTTI::hasBranchDivergence() const { return true; }
void AMDGPUTTI::getUnrollingPreferences(Loop *L,
UnrollingPreferences &UP) const {
UP.Threshold = 300; // Twice the default.
UP.Count = UINT_MAX;
UP.Partial = true;
// TODO: Do we want runtime unrolling?
for (const BasicBlock *BB : L->getBlocks()) {
for (const Instruction &I : *BB) {
const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
if (!GEP || GEP->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
continue;
const Value *Ptr = GEP->getPointerOperand();
const AllocaInst *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr));
if (Alloca) {
// We want to do whatever we can to limit the number of alloca
// instructions that make it through to the code generator. allocas
// require us to use indirect addressing, which is slow and prone to
// compiler bugs. If this loop does an address calculation on an
// alloca ptr, then we want to use a higher than normal loop unroll
// threshold. This will give SROA a better chance to eliminate these
// allocas.
//
// Don't use the maximum allowed value here as it will make some
// programs way too big.
UP.Threshold = 800;
}
}
}
}
AMDGPUTTI::PopcntSupportKind
AMDGPUTTI::getPopcntSupport(unsigned TyWidth) const {
assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
return ST->hasBCNT(TyWidth) ? PSK_FastHardware : PSK_Software;
}
unsigned AMDGPUTTI::getNumberOfRegisters(bool Vec) const {
if (Vec)
return 0;
// Number of VGPRs on SI.
if (ST->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS)
return 256;
return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
}
unsigned AMDGPUTTI::getRegisterBitWidth(bool) const {
return 32;
}
unsigned AMDGPUTTI::getMaximumUnrollFactor() const {
// Semi-arbitrary large amount.
return 64;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "string_list.h"
#include "read_multiple_logs.h"
#include "check_events.h"
MULTI_LOG_HASH_INSTANCE; // For the multi-log-file code...
CHECK_EVENTS_HASH_INSTANCE; // For the event checking code...
int main(int argc, char **argv)
{
int result = 0;
if ( argc <= 1 || (argc >= 2 && !strcmp("-usage", argv[1])) ) {
printf("Usage: condor_check_userlogs <log file 1> "
"[log file 2] ... [log file n]\n");
exit(0);
}
// Set up dprintf.
Termlog = true;
dprintf_config("condor_check_userlogs");
DebugFlags = D_ALWAYS;
StringList logFiles;
for ( int argnum = 1; argnum < argc; ++argnum ) {
logFiles.append(argv[argnum]);
}
logFiles.rewind();
ReadMultipleUserLogs ru;
char *filename;
while ( (filename = logFiles.next()) ) {
MyString filestring( filename );
CondorError errstack;
if ( !ru.monitorLogFile( filestring, false, errstack ) ) {
fprintf( stderr, "Error monitoring log file %s: %s\n", filename,
errstack.getFullText() );
result = 1;
}
}
bool logsMissing = false;
CheckEvents ce;
int totalSubmitted = 0;
int netSubmitted = 0;
bool done = false;
while( !done ) {
ULogEvent* e = NULL;
MyString errorMsg;
ULogEventOutcome outcome = ru.readEvent( e );
switch (outcome) {
case ULOG_NO_EVENT:
case ULOG_RD_ERROR:
case ULOG_UNK_ERROR:
printf( "Log outcome: %s\n", ULogEventOutcomeNames[outcome] );
done = true;
break;
case ULOG_OK:
printf( "Log event: %s (%d.%d.%d)",
ULogEventNumberNames[e->eventNumber],
e->cluster, e->proc, e->subproc );
if ( ce.CheckAnEvent(e, errorMsg) != CheckEvents::EVENT_OKAY ) {
fprintf(stderr, "%s\n", errorMsg.Value());
result = 1;
}
if( e->eventNumber == ULOG_SUBMIT ) {
SubmitEvent* ee = (SubmitEvent*) e;
printf( " (\"%s\")", ee->submitEventLogNotes );
++totalSubmitted;
++netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
if( e->eventNumber == ULOG_JOB_HELD ) {
JobHeldEvent* ee = (JobHeldEvent*) e;
printf( " (code=%d subcode=%d)", ee->getReasonCode(),
ee->getReasonSubCode());
}
if( e->eventNumber == ULOG_JOB_TERMINATED ) {
--netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
if( e->eventNumber == ULOG_JOB_ABORTED ) {
--netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
if( e->eventNumber == ULOG_EXECUTABLE_ERROR ) {
--netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
printf( "\n" );
break;
default:
fprintf(stderr, "Unexpected read event outcome!\n");
result = 1;
break;
}
}
logFiles.rewind();
while ( (filename = logFiles.next()) ) {
MyString filestring( filename );
CondorError errstack;
if ( !ru.unmonitorLogFile( filestring, errstack ) ) {
fprintf( stderr, "Error unmonitoring log file %s: %s\n", filename,
errstack.getFullText() );
result = 1;
}
}
MyString errorMsg;
CheckEvents::check_event_result_t checkAllResult =
ce.CheckAllJobs(errorMsg);
if ( checkAllResult != CheckEvents::EVENT_OKAY ) {
fprintf(stderr, "%s\n", errorMsg.Value());
fprintf(stderr, "CheckAllJobs() result: %s\n",
CheckEvents::ResultToString(checkAllResult));
result = 1;
}
if ( result == 0 ) {
if ( !logsMissing ) {
printf("Log(s) are okay\n");
} else {
printf("Log(s) may be okay\n");
printf( "Some logs cannot be read\n");
}
} else {
printf("Log(s) have error(s)\n");
}
return result;
}
<commit_msg>Fixed coverity-found bug.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "string_list.h"
#include "read_multiple_logs.h"
#include "check_events.h"
MULTI_LOG_HASH_INSTANCE; // For the multi-log-file code...
CHECK_EVENTS_HASH_INSTANCE; // For the event checking code...
int main(int argc, char **argv)
{
int result = 0;
if ( argc <= 1 || (argc >= 2 && !strcmp("-usage", argv[1])) ) {
printf("Usage: condor_check_userlogs <log file 1> "
"[log file 2] ... [log file n]\n");
exit(0);
}
// Set up dprintf.
Termlog = true;
dprintf_config("condor_check_userlogs");
DebugFlags = D_ALWAYS;
StringList logFiles;
for ( int argnum = 1; argnum < argc; ++argnum ) {
logFiles.append(argv[argnum]);
}
logFiles.rewind();
ReadMultipleUserLogs ru;
char *filename;
while ( (filename = logFiles.next()) ) {
MyString filestring( filename );
CondorError errstack;
if ( !ru.monitorLogFile( filestring, false, errstack ) ) {
fprintf( stderr, "Error monitoring log file %s: %s\n", filename,
errstack.getFullText() );
result = 1;
}
}
bool logsMissing = false;
CheckEvents ce;
int totalSubmitted = 0;
int netSubmitted = 0;
bool done = false;
while( !done ) {
ULogEvent* e = NULL;
MyString errorMsg;
ULogEventOutcome outcome = ru.readEvent( e );
switch (outcome) {
case ULOG_RD_ERROR:
case ULOG_UNK_ERROR:
logsMissing = true;
case ULOG_NO_EVENT:
printf( "Log outcome: %s\n", ULogEventOutcomeNames[outcome] );
done = true;
break;
case ULOG_OK:
printf( "Log event: %s (%d.%d.%d)",
ULogEventNumberNames[e->eventNumber],
e->cluster, e->proc, e->subproc );
if ( ce.CheckAnEvent(e, errorMsg) != CheckEvents::EVENT_OKAY ) {
fprintf(stderr, "%s\n", errorMsg.Value());
result = 1;
}
if( e->eventNumber == ULOG_SUBMIT ) {
SubmitEvent* ee = (SubmitEvent*) e;
printf( " (\"%s\")", ee->submitEventLogNotes );
++totalSubmitted;
++netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
if( e->eventNumber == ULOG_JOB_HELD ) {
JobHeldEvent* ee = (JobHeldEvent*) e;
printf( " (code=%d subcode=%d)", ee->getReasonCode(),
ee->getReasonSubCode());
}
if( e->eventNumber == ULOG_JOB_TERMINATED ) {
--netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
if( e->eventNumber == ULOG_JOB_ABORTED ) {
--netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
if( e->eventNumber == ULOG_EXECUTABLE_ERROR ) {
--netSubmitted;
printf( "\n Total submitted: %d; net submitted: %d\n",
totalSubmitted, netSubmitted );
}
printf( "\n" );
break;
default:
fprintf(stderr, "Unexpected read event outcome!\n");
result = 1;
break;
}
}
logFiles.rewind();
while ( (filename = logFiles.next()) ) {
MyString filestring( filename );
CondorError errstack;
if ( !ru.unmonitorLogFile( filestring, errstack ) ) {
fprintf( stderr, "Error unmonitoring log file %s: %s\n", filename,
errstack.getFullText() );
result = 1;
}
}
MyString errorMsg;
CheckEvents::check_event_result_t checkAllResult =
ce.CheckAllJobs(errorMsg);
if ( checkAllResult != CheckEvents::EVENT_OKAY ) {
fprintf(stderr, "%s\n", errorMsg.Value());
fprintf(stderr, "CheckAllJobs() result: %s\n",
CheckEvents::ResultToString(checkAllResult));
result = 1;
}
if ( result == 0 ) {
if ( !logsMissing ) {
printf("Log(s) are okay\n");
} else {
printf("Log(s) may be okay\n");
printf( "Some logs cannot be read\n");
}
} else {
printf("Log(s) have error(s)\n");
}
return result;
}
<|endoftext|> |
<commit_before>#ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
#define ITERTOOLS_SAMPLE_CLASSES_HPP
#include <iostream>
#include <utility>
#include <cstddef>
namespace itertest {
class MoveOnly {
private:
int i; // not an aggregate
public:
MoveOnly(int v)
: i{v}
{ }
MoveOnly(const MoveOnly&) = delete;
MoveOnly& operator=(const MoveOnly&) = delete;
MoveOnly(MoveOnly&& other) noexcept
: i{other.i}
{ }
MoveOnly& operator=(MoveOnly&& other) noexcept {
this->i = other.i;
return *this;
}
// for std::next_permutation compatibility
friend bool operator<(const MoveOnly& lhs, const MoveOnly& rhs) {
return lhs.i < rhs.i;
}
friend std::ostream& operator<<(
std::ostream& out, const MoveOnly& self) {
return out << self.i;
}
};
class DerefByValue {
private:
static constexpr std::size_t N = 3;
int array[N] = {0};
public:
DerefByValue() = default;
class Iterator {
private:
int *current;
public:
Iterator() = default;
Iterator(int *p)
: current{p}
{ }
bool operator!=(const Iterator& other) const {
return this->current != other.current;
}
// for testing, iterator derefences to an int instead of
// an int&
int operator*() {
return *this->current;
}
Iterator& operator++() {
++this->current;
return *this;
}
};
Iterator begin() {
return {this->array};
}
Iterator end() {
return {this->array + N};
}
};
}
#endif // #ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
<commit_msg>adds DerefByValueFancy with random access iterator<commit_after>#ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
#define ITERTOOLS_SAMPLE_CLASSES_HPP
#include <iostream>
#include <utility>
#include <cstddef>
namespace itertest {
class MoveOnly {
private:
int i; // not an aggregate
public:
MoveOnly(int v)
: i{v}
{ }
MoveOnly(const MoveOnly&) = delete;
MoveOnly& operator=(const MoveOnly&) = delete;
MoveOnly(MoveOnly&& other) noexcept
: i{other.i}
{ }
MoveOnly& operator=(MoveOnly&& other) noexcept {
this->i = other.i;
return *this;
}
// for std::next_permutation compatibility
friend bool operator<(const MoveOnly& lhs, const MoveOnly& rhs) {
return lhs.i < rhs.i;
}
friend std::ostream& operator<<(
std::ostream& out, const MoveOnly& self) {
return out << self.i;
}
};
class DerefByValue {
private:
static constexpr std::size_t N = 3;
int array[N] = {0, 1, 2};
public:
DerefByValue() = default;
class Iterator {
private:
int *current;
public:
Iterator() = default;
Iterator(int *p)
: current{p}
{ }
bool operator!=(const Iterator& other) const {
return this->current != other.current;
}
// for testing, iterator derefences to an int instead of
// an int&
int operator*() {
return *this->current;
}
Iterator& operator++() {
++this->current;
return *this;
}
};
Iterator begin() {
return {this->array};
}
Iterator end() {
return {this->array + N};
}
};
class DerefByValueFancy {
private:
static constexpr std::size_t N = 3;
int array[N] = {0, 1, 2};
public:
DerefByValueFancy() = default;
int *begin() {
return this->array;
}
int *end() {
return this->array + N;
}
};
}
#endif // #ifndef ITERTOOLS_SAMPLE_CLASSES_HPP
<|endoftext|> |
<commit_before>/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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. */
#ifndef PLANNING_CPP_UAV_H
#define PLANNING_CPP_UAV_H
#include <vector>
#include <cassert>
#include "../ext/dubins.h"
#include "waypoint.hpp"
#include "../utils.hpp"
#include "dubins3d.hpp"
#include "dubinswind.hpp"
namespace SAOP {
struct UAV {
UAV(const double max_air_speed, const double max_angular_velocity, const double max_pitch_angle) :
_max_angular_velocity(max_angular_velocity),
_max_air_speed(max_air_speed),
_min_turn_radius(max_air_speed / max_angular_velocity),
_max_pitch_angle(max_pitch_angle) {}
UAV(const UAV& uav) = default;
double max_angular_velocity() const {
return _max_angular_velocity;
}
double max_air_speed() const {
return _max_air_speed;
}
double min_turn_radius() const {
return _min_turn_radius;
}
double max_pitch_angle() const {
return _max_pitch_angle;
}
double view_width() const {
return _view_width;
}
double view_depth() const {
return _view_depth;
}
/** Returns the Dubins travel distance between the two waypoints. */
double travel_distance(const Waypoint& origin, const Waypoint& target) const {
DubinsPath path = dubins_path(origin, target);
return dubins_path_length(&path);
}
/** Returns the Dubins travel distance between the two waypoints. */
double travel_distance(const Waypoint3d& origin, const Waypoint3d& target) const {
Dubins3dPathLength path(origin, target, _min_turn_radius, _max_pitch_angle);
return path.L;
}
/** Returns the travel time between the two waypoints. */
double travel_time(const Waypoint& origin, const Waypoint& target) const {
return travel_distance(origin, target) / _max_air_speed;
}
/** Returns the travel time between the two waypoints. */
double travel_time(const Waypoint3d& origin, const Waypoint3d& target) const {
return travel_distance(origin, target) / _max_air_speed;
}
/** Returns the travel time between the two waypoints. */
double travel_time(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind) const {
try {
DubinsWind path(origin, target, wind, _min_turn_radius, _max_pitch_angle);
return path.T();
} catch (const DubinsWindPathNotFoundException&) {
return std::numeric_limits<double>::infinity();
}
}
/* Determine whether the UAV is turning*/
bool is_turning(const Waypoint3d& prev, const Waypoint3d& current) const {
// r = dist(prev, current) / (current.dir - prev.dir)
// roll = atan(v^2/(r*g))
return !ALMOST_EQUAL(prev.dir, current.dir);
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint>
path_sampling(const Waypoint& origin, const Waypoint& target, double step_size) const {
ASSERT(step_size > 0);
const double length = travel_distance(origin, target);
DubinsPath path = dubins_path(origin, target);
std::vector<Waypoint> waypoints;
for (double it = 0; it < length; it += step_size) {
double q[3];
dubins_path_sample(&path, it, q);
Waypoint wp(q[0], q[1], q[2]);
waypoints.push_back(wp);
}
waypoints.push_back(target);
return waypoints;
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint3d>
path_sampling(const Waypoint3d& origin, const Waypoint3d& target, double step_size) const {
ASSERT(step_size > 0);
Dubins3dPath path = Dubins3dPath(origin, target, _min_turn_radius, _max_pitch_angle);
std::vector<Waypoint3d> waypoints;
for (double it = 0; it < path.L_2d; it += step_size) {
waypoints.push_back(path.sample(it));
}
waypoints.push_back(target);
return waypoints;
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint3d>
path_sampling(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind,
double step_size) const {
ASSERT(step_size > 0);
DubinsWind path = DubinsWind(origin, target, wind, _max_air_speed, _min_turn_radius);
return path.sampled(step_size);
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint3d>
path_sampling_airframe(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind,
double step_size) const {
ASSERT(step_size > 0);
DubinsWind path = DubinsWind(origin, target, wind, _max_air_speed, _min_turn_radius);
return path.sampled_airframe(step_size);
}
/* Returns a sequence of waypoints with its corresponding time following the dubins trajectory,
* one every step_size distance units. */
std::pair<std::vector<Waypoint3d>, std::vector<double>>
path_sampling_with_time(const Waypoint3d& origin, const Waypoint3d& target, double step_size,
double t_start) const {
ASSERT(step_size > 0);
Dubins3dPath path = Dubins3dPath(origin, target, _min_turn_radius, _max_pitch_angle);
std::vector<Waypoint3d> waypoints;
std::vector<double> times;
for (double it = 0; it < path.L_2d; it += step_size) {
waypoints.push_back(path.sample(it));
times.push_back(t_start + it / _max_air_speed);
}
waypoints.push_back(target);
times.push_back(t_start + path.L_2d / _max_air_speed);
return {waypoints, times};
}
/** Rotates the given segment on the center of the visibility area. */
Segment rotate_on_visibility_center(const Segment& segment, double target_dir) const {
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
const double new_segment_start_x = vis_center_x - cos(target_dir) * visibility_depth / 2;
const double new_segment_start_y = vis_center_y - sin(target_dir) * visibility_depth / 2;
return Segment(Waypoint(new_segment_start_x, new_segment_start_y, target_dir), segment.length);
}
/** Rotates the given segment on the center of the visibility area. */
Segment3d rotate_on_visibility_center(const Segment3d& segment, double target_dir) const {
ASSERT(ALMOST_EQUAL(segment.start.z, segment.end.z));
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
const double new_segment_start_x = vis_center_x - cos(target_dir) * visibility_depth / 2;
const double new_segment_start_y = vis_center_y - sin(target_dir) * visibility_depth / 2;
return Segment3d(Waypoint3d(new_segment_start_x, new_segment_start_y, segment.start.z, target_dir),
segment.length);
}
/** Builds a new segment of the given length and direction,
* such that (x_coords, y_coords) is at the center of the visibility area. */
Segment observation_segment(double x_coords, double y_coords, double dir, double length) const {
const double visibility_depth = length + _view_depth;
const double segment_start_x = x_coords - cos(dir) * visibility_depth / 2;
const double segment_start_y = y_coords - sin(dir) * visibility_depth / 2;
return Segment(Waypoint(segment_start_x, segment_start_y, dir), length);
}
/** Builds a new segment of the given length and direction,
* such that (x_coords, y_coords) is at the center of the visibility area. */
Segment3d
observation_segment(double x_coords, double y_coords, double z_coords, double dir, double length) const {
const double visibility_depth = length + _view_depth;
const double segment_start_x = x_coords - cos(dir) * visibility_depth / 2;
const double segment_start_y = y_coords - sin(dir) * visibility_depth / 2;
return Segment3d(Waypoint3d(segment_start_x, segment_start_y, z_coords, dir), length);
}
Waypoint visibility_center(const Segment& segment) const {
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
return Waypoint(vis_center_x, vis_center_y, segment.start.dir);
}
Waypoint3d visibility_center(const Segment3d& segment) const {
ASSERT(ALMOST_EQUAL(segment.start.z, segment.end.z));
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
return Waypoint3d(vis_center_x, vis_center_y, segment.start.z, segment.start.dir);
}
private:
double _max_angular_velocity;
double _max_air_speed;
double _min_turn_radius;
double _max_pitch_angle; /* aka gamma_max */
double _view_width = 100;
double _view_depth = 70;
DubinsPath dubins_path(const Waypoint& origin, const Waypoint& target) const {
DubinsPath path;
double orig[3] = {origin.x, origin.y, origin.dir};
double dest[3] = {target.x, target.y, target.dir};
// ugly hack to be compatible with dubins implementation that expects a double[3] in place of each Waypoint
int ret = dubins_init(orig, dest, _min_turn_radius, &path);
ASSERT(ret == 0);
return path;
}
};
}
#endif //PLANNING_CPP_UAV_H
<commit_msg>Add path_sampling_with_time to UAV<commit_after>/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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. */
#ifndef PLANNING_CPP_UAV_H
#define PLANNING_CPP_UAV_H
#include <vector>
#include <cassert>
#include "../ext/dubins.h"
#include "waypoint.hpp"
#include "../utils.hpp"
#include "dubins3d.hpp"
#include "dubinswind.hpp"
namespace SAOP {
struct UAV {
UAV(const double max_air_speed, const double max_angular_velocity, const double max_pitch_angle) :
_max_angular_velocity(max_angular_velocity),
_max_air_speed(max_air_speed),
_min_turn_radius(max_air_speed / max_angular_velocity),
_max_pitch_angle(max_pitch_angle) {}
UAV(const UAV& uav) = default;
double max_angular_velocity() const {
return _max_angular_velocity;
}
double max_air_speed() const {
return _max_air_speed;
}
double min_turn_radius() const {
return _min_turn_radius;
}
double max_pitch_angle() const {
return _max_pitch_angle;
}
double view_width() const {
return _view_width;
}
double view_depth() const {
return _view_depth;
}
/** Returns the Dubins travel distance between the two waypoints. */
double travel_distance(const Waypoint& origin, const Waypoint& target) const {
DubinsPath path = dubins_path(origin, target);
return dubins_path_length(&path);
}
/** Returns the Dubins travel distance between the two waypoints. */
double travel_distance(const Waypoint3d& origin, const Waypoint3d& target) const {
Dubins3dPathLength path(origin, target, _min_turn_radius, _max_pitch_angle);
return path.L;
}
/** Returns the travel time between the two waypoints. */
double travel_time(const Waypoint& origin, const Waypoint& target) const {
return travel_distance(origin, target) / _max_air_speed;
}
/** Returns the travel time between the two waypoints. */
double travel_time(const Waypoint3d& origin, const Waypoint3d& target) const {
return travel_distance(origin, target) / _max_air_speed;
}
/** Returns the travel time between the two waypoints. */
double travel_time(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind) const {
try {
DubinsWind path(origin, target, wind, _min_turn_radius, _max_pitch_angle);
return path.T();
} catch (const DubinsWindPathNotFoundException&) {
return std::numeric_limits<double>::infinity();
}
}
/* Determine whether the UAV is turning*/
bool is_turning(const Waypoint3d& prev, const Waypoint3d& current) const {
// r = dist(prev, current) / (current.dir - prev.dir)
// roll = atan(v^2/(r*g))
return !ALMOST_EQUAL(prev.dir, current.dir);
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint>
path_sampling(const Waypoint& origin, const Waypoint& target, double step_size) const {
ASSERT(step_size > 0);
const double length = travel_distance(origin, target);
DubinsPath path = dubins_path(origin, target);
std::vector<Waypoint> waypoints;
for (double it = 0; it < length; it += step_size) {
double q[3];
dubins_path_sample(&path, it, q);
Waypoint wp(q[0], q[1], q[2]);
waypoints.push_back(wp);
}
waypoints.push_back(target);
return waypoints;
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint3d>
path_sampling(const Waypoint3d& origin, const Waypoint3d& target, double step_size) const {
ASSERT(step_size > 0);
Dubins3dPath path = Dubins3dPath(origin, target, _min_turn_radius, _max_pitch_angle);
std::vector<Waypoint3d> waypoints;
for (double it = 0; it < path.L_2d; it += step_size) {
waypoints.push_back(path.sample(it));
}
waypoints.push_back(target);
return waypoints;
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint3d>
path_sampling(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind,
double step_size) const {
ASSERT(step_size > 0);
DubinsWind path = DubinsWind(origin, target, wind, _max_air_speed, _min_turn_radius);
return path.sampled(step_size);
}
/** Returns a sequence of waypoints following the dubins trajectory, one every step_size distance units. */
std::vector<Waypoint3d>
path_sampling_airframe(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind,
double step_size) const {
ASSERT(step_size > 0);
DubinsWind path = DubinsWind(origin, target, wind, _max_air_speed, _min_turn_radius);
return path.sampled_airframe(step_size);
}
/* Returns a sequence of waypoints with its corresponding time following the dubins trajectory,
* one every step_size distance units. */
std::pair<std::vector<Waypoint3d>, std::vector<double>>
path_sampling_with_time(const Waypoint3d& origin, const Waypoint3d& target, double step_size,
double t_start) const {
ASSERT(step_size > 0);
Dubins3dPath path = Dubins3dPath(origin, target, _min_turn_radius, _max_pitch_angle);
std::vector<Waypoint3d> waypoints;
std::vector<double> times;
for (double it = 0; it < path.L_2d; it += step_size) {
waypoints.push_back(path.sample(it));
times.push_back(t_start + it / _max_air_speed);
}
waypoints.push_back(target);
times.push_back(t_start + path.L_2d / _max_air_speed);
return {waypoints, times};
}
/* Returns a sequence of waypoints with its corresponding time following the dubins trajectory,
* one every step_size distance units. */
std::pair<std::vector<Waypoint3d>, std::vector<double>>
path_sampling_with_time(const Waypoint3d& origin, const Waypoint3d& target, const WindVector& wind,
double step_size, double t_start) const {
ASSERT(step_size > 0);
DubinsWind path = DubinsWind(origin, target, wind, _max_air_speed, _min_turn_radius);
auto wp_time = path.sampled_with_time(step_size);
auto& t = std::get<1>(wp_time);
for (auto it = t.begin(); it != t.end(); ++it) {
*it += t_start;
}
return wp_time;
}
/** Rotates the given segment on the center of the visibility area. */
Segment rotate_on_visibility_center(const Segment& segment, double target_dir) const {
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
const double new_segment_start_x = vis_center_x - cos(target_dir) * visibility_depth / 2;
const double new_segment_start_y = vis_center_y - sin(target_dir) * visibility_depth / 2;
return Segment(Waypoint(new_segment_start_x, new_segment_start_y, target_dir), segment.length);
}
/** Rotates the given segment on the center of the visibility area. */
Segment3d rotate_on_visibility_center(const Segment3d& segment, double target_dir) const {
ASSERT(ALMOST_EQUAL(segment.start.z, segment.end.z));
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
const double new_segment_start_x = vis_center_x - cos(target_dir) * visibility_depth / 2;
const double new_segment_start_y = vis_center_y - sin(target_dir) * visibility_depth / 2;
return Segment3d(Waypoint3d(new_segment_start_x, new_segment_start_y, segment.start.z, target_dir),
segment.length);
}
/** Builds a new segment of the given length and direction,
* such that (x_coords, y_coords) is at the center of the visibility area. */
Segment observation_segment(double x_coords, double y_coords, double dir, double length) const {
const double visibility_depth = length + _view_depth;
const double segment_start_x = x_coords - cos(dir) * visibility_depth / 2;
const double segment_start_y = y_coords - sin(dir) * visibility_depth / 2;
return Segment(Waypoint(segment_start_x, segment_start_y, dir), length);
}
/** Builds a new segment of the given length and direction,
* such that (x_coords, y_coords) is at the center of the visibility area. */
Segment3d
observation_segment(double x_coords, double y_coords, double z_coords, double dir, double length) const {
const double visibility_depth = length + _view_depth;
const double segment_start_x = x_coords - cos(dir) * visibility_depth / 2;
const double segment_start_y = y_coords - sin(dir) * visibility_depth / 2;
return Segment3d(Waypoint3d(segment_start_x, segment_start_y, z_coords, dir), length);
}
Waypoint visibility_center(const Segment& segment) const {
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
return Waypoint(vis_center_x, vis_center_y, segment.start.dir);
}
Waypoint3d visibility_center(const Segment3d& segment) const {
ASSERT(ALMOST_EQUAL(segment.start.z, segment.end.z));
const double visibility_depth = segment.length + _view_depth;
const double vis_center_x = segment.start.x + cos(segment.start.dir) * visibility_depth / 2;
const double vis_center_y = segment.start.y + sin(segment.start.dir) * visibility_depth / 2;
return Waypoint3d(vis_center_x, vis_center_y, segment.start.z, segment.start.dir);
}
private:
double _max_angular_velocity;
double _max_air_speed;
double _min_turn_radius;
double _max_pitch_angle; /* aka gamma_max */
double _view_width = 100;
double _view_depth = 70;
DubinsPath dubins_path(const Waypoint& origin, const Waypoint& target) const {
DubinsPath path;
double orig[3] = {origin.x, origin.y, origin.dir};
double dest[3] = {target.x, target.y, target.dir};
// ugly hack to be compatible with dubins implementation that expects a double[3] in place of each Waypoint
int ret = dubins_init(orig, dest, _min_turn_radius, &path);
ASSERT(ret == 0);
return path;
}
};
}
#endif //PLANNING_CPP_UAV_H
<|endoftext|> |
<commit_before>#include <cstdio>
#define NOMINMAX
#include <wine/debug.h>
#include "test.h"
WINE_DEFAULT_DEBUG_CHANNEL(steambridget);
static Test t;
extern "C"
{
void *get_real_object()
{
return (void *)(&t);
}
}
Test::Test()
{
WINE_TRACE("(this=%p)\n", this);
}
int Test::function_one(int param_one, bool param_two, const char *param_three)
{
WINE_TRACE("(this=%p,%i,%i,\"%s\")\n", this, param_one, param_two, param_three);
return 42;
}
bool Test::function_two(double param_one, void *param_two, float param_three)
{
WINE_TRACE("(this=%p,%f,%p,%f)\n", this, param_one, param_two, param_three);
return true;
}
<commit_msg>Added better TRACE debugging to the Winelib DLL.<commit_after>#include <cstdio>
#define NOMINMAX
#include <wine/debug.h>
#include "test.h"
WINE_DEFAULT_DEBUG_CHANNEL(steambridget);
static Test t;
extern "C"
{
void *get_real_object()
{
return (void *)(&t);
}
}
Test::Test()
{
WINE_TRACE("(this=%p,vtable=%p,function_one=%p)\n", this, *((void **)(this)), &Test::function_one);
}
int Test::function_one(int param_one, bool param_two, const char *param_three)
{
WINE_TRACE("(this=%p,%i,%i,\"%s\")\n", this, param_one, param_two, param_three);
return 42;
}
bool Test::function_two(double param_one, void *param_two, float param_three)
{
WINE_TRACE("(this=%p,%f|%i&%i,%p,%f)\n", this, param_one, param_one, param_two, param_three);
return true;
}
<|endoftext|> |
<commit_before>#include "line_optimizer.h"
#include <limits>
#include <algorithm>
#include "sparse_vector.h"
#include "scorer.h"
using namespace std;
typedef ErrorSurface::const_iterator ErrorIter;
// sort by increasing x-ints
struct IntervalComp {
bool operator() (const ErrorIter& a, const ErrorIter& b) const {
return a->x < b->x;
}
};
double LineOptimizer::LineOptimize(
const vector<ErrorSurface>& surfaces,
const LineOptimizer::ScoreType type,
float* best_score,
const double epsilon) {
// cerr << "MIN=" << MINIMIZE_SCORE << " MAX=" << MAXIMIZE_SCORE << " MINE=" << type << endl;
vector<ErrorIter> all_ints;
for (vector<ErrorSurface>::const_iterator i = surfaces.begin();
i != surfaces.end(); ++i) {
const ErrorSurface& surface = *i;
for (ErrorIter j = surface.begin(); j != surface.end(); ++j)
all_ints.push_back(j);
}
sort(all_ints.begin(), all_ints.end(), IntervalComp());
double last_boundary = all_ints.front()->x;
ScoreP accp = all_ints.front()->delta->GetZero();
Score *acc=accp.get();
float& cur_best_score = *best_score;
cur_best_score = (type == MAXIMIZE_SCORE ?
-numeric_limits<float>::max() : numeric_limits<float>::max());
bool left_edge = true;
double pos = numeric_limits<double>::quiet_NaN();
for (vector<ErrorIter>::iterator i = all_ints.begin();
i != all_ints.end(); ++i) {
const ErrorSegment& seg = **i;
assert(seg.delta);
if (seg.x - last_boundary > epsilon) {
float sco = acc->ComputeScore();
if ((type == MAXIMIZE_SCORE && sco > cur_best_score) ||
(type == MINIMIZE_SCORE && sco < cur_best_score) ) {
cur_best_score = sco;
if (left_edge) {
pos = seg.x - 0.1;
left_edge = false;
} else {
pos = last_boundary + (seg.x - last_boundary) / 2;
}
// cerr << "NEW BEST: " << pos << " (score=" << cur_best_score << ")\n";
}
// string xx; acc->ScoreDetails(&xx); cerr << "---- " << xx;
// cerr << "---- s=" << sco << "\n";
last_boundary = seg.x;
}
// cerr << "x-boundary=" << seg.x << "\n";
acc->PlusEquals(*seg.delta);
}
float sco = acc->ComputeScore();
if ((type == MAXIMIZE_SCORE && sco > cur_best_score) ||
(type == MINIMIZE_SCORE && sco < cur_best_score) ) {
cur_best_score = sco;
if (left_edge) {
pos = 0;
} else {
pos = last_boundary + 1000.0;
}
}
return pos;
}
void LineOptimizer::RandomUnitVector(const vector<int>& features_to_optimize,
SparseVector<double>* axis,
RandomNumberGenerator<boost::mt19937>* rng) {
axis->clear();
for (int i = 0; i < features_to_optimize.size(); ++i)
axis->set_value(features_to_optimize[i], rng->next() - 0.5);
(*axis) /= axis->l2norm();
}
void LineOptimizer::CreateOptimizationDirections(
const vector<int>& features_to_optimize,
int additional_random_directions,
RandomNumberGenerator<boost::mt19937>* rng,
vector<SparseVector<double> >* dirs
, bool include_orthogonal
) {
dirs->clear();
typedef SparseVector<double> Dir;
vector<Dir> &out=*dirs;
int i=0;
if (include_orthogonal)
for (;i<features_to_optimize.size();++i) {
Dir d;
d.set_value(features_to_optimize[i],1.);
out.push_back(d);
}
out.resize(i+additional_random_directions);
for (;i<out.size();++i)
RandomUnitVector(features_to_optimize, &out[i], rng);
cerr << "Generated " << out.size() << " total axes to optimize along.\n";
}
<commit_msg>proper sampling from unit sphere<commit_after>#include "line_optimizer.h"
#include <limits>
#include <algorithm>
#include "sparse_vector.h"
#include "scorer.h"
using namespace std;
typedef ErrorSurface::const_iterator ErrorIter;
// sort by increasing x-ints
struct IntervalComp {
bool operator() (const ErrorIter& a, const ErrorIter& b) const {
return a->x < b->x;
}
};
double LineOptimizer::LineOptimize(
const vector<ErrorSurface>& surfaces,
const LineOptimizer::ScoreType type,
float* best_score,
const double epsilon) {
// cerr << "MIN=" << MINIMIZE_SCORE << " MAX=" << MAXIMIZE_SCORE << " MINE=" << type << endl;
vector<ErrorIter> all_ints;
for (vector<ErrorSurface>::const_iterator i = surfaces.begin();
i != surfaces.end(); ++i) {
const ErrorSurface& surface = *i;
for (ErrorIter j = surface.begin(); j != surface.end(); ++j)
all_ints.push_back(j);
}
sort(all_ints.begin(), all_ints.end(), IntervalComp());
double last_boundary = all_ints.front()->x;
ScoreP accp = all_ints.front()->delta->GetZero();
Score *acc=accp.get();
float& cur_best_score = *best_score;
cur_best_score = (type == MAXIMIZE_SCORE ?
-numeric_limits<float>::max() : numeric_limits<float>::max());
bool left_edge = true;
double pos = numeric_limits<double>::quiet_NaN();
for (vector<ErrorIter>::iterator i = all_ints.begin();
i != all_ints.end(); ++i) {
const ErrorSegment& seg = **i;
assert(seg.delta);
if (seg.x - last_boundary > epsilon) {
float sco = acc->ComputeScore();
if ((type == MAXIMIZE_SCORE && sco > cur_best_score) ||
(type == MINIMIZE_SCORE && sco < cur_best_score) ) {
cur_best_score = sco;
if (left_edge) {
pos = seg.x - 0.1;
left_edge = false;
} else {
pos = last_boundary + (seg.x - last_boundary) / 2;
}
// cerr << "NEW BEST: " << pos << " (score=" << cur_best_score << ")\n";
}
// string xx; acc->ScoreDetails(&xx); cerr << "---- " << xx;
// cerr << "---- s=" << sco << "\n";
last_boundary = seg.x;
}
// cerr << "x-boundary=" << seg.x << "\n";
acc->PlusEquals(*seg.delta);
}
float sco = acc->ComputeScore();
if ((type == MAXIMIZE_SCORE && sco > cur_best_score) ||
(type == MINIMIZE_SCORE && sco < cur_best_score) ) {
cur_best_score = sco;
if (left_edge) {
pos = 0;
} else {
pos = last_boundary + 1000.0;
}
}
return pos;
}
void LineOptimizer::RandomUnitVector(const vector<int>& features_to_optimize,
SparseVector<double>* axis,
RandomNumberGenerator<boost::mt19937>* rng) {
axis->clear();
for (int i = 0; i < features_to_optimize.size(); ++i)
axis->set_value(features_to_optimize[i], rng->NextNormal(0.0,1.0));
(*axis) /= axis->l2norm();
}
void LineOptimizer::CreateOptimizationDirections(
const vector<int>& features_to_optimize,
int additional_random_directions,
RandomNumberGenerator<boost::mt19937>* rng,
vector<SparseVector<double> >* dirs
, bool include_orthogonal
) {
dirs->clear();
typedef SparseVector<double> Dir;
vector<Dir> &out=*dirs;
int i=0;
if (include_orthogonal)
for (;i<features_to_optimize.size();++i) {
Dir d;
d.set_value(features_to_optimize[i],1.);
out.push_back(d);
}
out.resize(i+additional_random_directions);
for (;i<out.size();++i)
RandomUnitVector(features_to_optimize, &out[i], rng);
cerr << "Generated " << out.size() << " total axes to optimize along.\n";
}
<|endoftext|> |
<commit_before>#include "swift/AST/CASTBridging.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeRepr.h"
using namespace swift;
template <typename T>
inline llvm::ArrayRef<T> getArrayRef(BridgedArrayRef bridged) {
return {static_cast<const T *>(bridged.data), size_t(bridged.numElements)};
}
BridgedIdentifier
SwiftASTContext_getIdentifier(void *ctx, const uint8_t *_Nullable str, long len) {
return const_cast<void *>(
static_cast<ASTContext *>(ctx)
->getIdentifier(
StringRef{reinterpret_cast<const char *>(str), size_t(len)})
.getAsOpaquePointer());
}
void *SwiftImportDecl_create(void *ctx, void *dc, void *importLoc, char kind,
void *kindLoc, BridgedArrayRef path,
BridgedArrayRef pathLocs) {
assert(path.numElements == pathLocs.numElements);
ASTContext &Context = *static_cast<ASTContext *>(ctx);
ImportPath::Builder importPath;
for (auto p : llvm::zip(getArrayRef<Identifier>(path),
getArrayRef<SourceLoc>(pathLocs))) {
Identifier ident;
SourceLoc loc;
std::tie(ident, loc) = p;
importPath.push_back(ident, loc);
}
return ImportDecl::create(
Context, static_cast<DeclContext *>(dc), *(SourceLoc *)&importLoc,
static_cast<ImportKind>(kind), *(SourceLoc *)&kindLoc,
std::move(importPath).get());
}
void *BridgedSourceLoc_advanced(void *loc, long len) {
SourceLoc l = ((SourceLoc *)&loc)->getAdvancedLoc(len);
return &l; // TODO: what?
}
void *SwiftTopLevelCodeDecl_createStmt(void *ctx, void *DC, void *startLoc,
void *element, void *endLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *S = static_cast<Stmt *>(element);
auto Brace =
BraceStmt::create(Context, *(SourceLoc *)&startLoc,
{S}, *(SourceLoc *)&endLoc,
/*Implicit=*/true);
auto *TLCD =
new (Context) TopLevelCodeDecl(static_cast<DeclContext *>(DC), Brace);
return (Decl *)TLCD;
}
void *SwiftTopLevelCodeDecl_createExpr(void *ctx, void *DC, void *startLoc,
void *element, void *endLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *E = static_cast<Expr *>(element);
auto Brace =
BraceStmt::create(Context, *(SourceLoc *)&startLoc,
{E}, *(SourceLoc *)&endLoc,
/*Implicit=*/true);
auto *TLCD =
new (Context) TopLevelCodeDecl(static_cast<DeclContext *>(DC), Brace);
return (Decl *)TLCD;
}
void *SwiftSequenceExpr_create(void *ctx, BridgedArrayRef exprs) {
return SequenceExpr::create(*static_cast<ASTContext *>(ctx),
getArrayRef<Expr *>(exprs));
}
void *SwiftTupleExpr_create(void *ctx, void *lparen, BridgedArrayRef subs,
void *rparen) {
return TupleExpr::create(
*static_cast<ASTContext *>(ctx), *(SourceLoc *)&lparen,
getArrayRef<Expr *>(subs), {}, {}, *(SourceLoc *)&rparen,
/*Implicit*/ false);
}
void *SwiftFunctionCallExpr_create(void *ctx, void *fn, void *args) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
TupleExpr *TE = static_cast<TupleExpr *>(args);
SmallVector<Argument, 8> arguments;
for (unsigned i = 0; i < TE->getNumElements(); ++i) {
arguments.emplace_back(TE->getElementNameLoc(i), TE->getElementName(i),
TE->getElement(i));
}
auto *argList = ArgumentList::create(Context, TE->getLParenLoc(), arguments,
TE->getRParenLoc(), None,
/*isImplicit*/ false);
return CallExpr::create(Context, static_cast<Expr *>(fn), argList,
/*implicit*/ false);
}
void *SwiftIdentifierExpr_create(void *ctx, BridgedIdentifier base, void *loc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto name = DeclNameRef{
swift::Identifier::getFromOpaquePointer(base)};
Expr *E = new (Context) UnresolvedDeclRefExpr(
name, DeclRefKind::Ordinary, DeclNameLoc{*(SourceLoc *)&loc});
return E;
}
void *SwiftStringLiteralExpr_create(
void *ctx, const uint8_t *_Nullable string,
long len, void *TokenLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) StringLiteralExpr(
StringRef{reinterpret_cast<const char *>(string), size_t(len)},
*(SourceLoc *)&TokenLoc);
}
void *SwiftIntegerLiteralExpr_create(
void *ctx, const uint8_t *_Nullable string, long len, void *TokenLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) IntegerLiteralExpr(
StringRef{reinterpret_cast<const char *>(string), size_t(len)},
*(SourceLoc *)&TokenLoc);
}
void *SwiftBooleanLiteralExpr_create(void *ctx, bool value, void *TokenLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) BooleanLiteralExpr(value, *(SourceLoc *)&TokenLoc);
}
void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable nameId,
void *loc, bool isStatic, bool isLet, void *dc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) VarDecl(isStatic,
isLet ? VarDecl::Introducer::Let : VarDecl::Introducer::Var,
*(SourceLoc *)&loc, Identifier::getFromOpaquePointer(nameId),
reinterpret_cast<DeclContext *>(dc));
}
void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then, void *_Nullable elseLoc,
void *_Nullable elseStmt) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) IfStmt(*(SourceLoc *)&ifLoc, (Expr *)cond, (Stmt *)then, *(SourceLoc *)&elseLoc,
(Stmt *)elseStmt, None, Context);
}
void *BraceStmt_createExpr(void *ctx, void *lbloc, BridgedArrayRef elements, void *rbloc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return BraceStmt::create(Context, *(SourceLoc *)&lbloc,
getArrayRef<ASTNode>(elements),
*(SourceLoc *)&rbloc);
}
void *BraceStmt_createStmt(void *ctx, void *lbloc, BridgedArrayRef elements, void *rbloc) {
llvm::SmallVector<ASTNode, 6> nodes;
for (auto stmt : getArrayRef<Stmt *>(elements)) {
nodes.push_back(stmt);
}
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return BraceStmt::create(Context, *(SourceLoc *)&lbloc,
Context.AllocateCopy(nodes),
*(SourceLoc *)&rbloc);
}
void *ParamDecl_create(
void *ctx, void *loc,
void *_Nullable argLoc, BridgedIdentifier _Nullable argName,
void *_Nullable paramLoc, BridgedIdentifier _Nullable paramName,
void *declContext) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) ParamDecl(*(SourceLoc *)&loc, *(SourceLoc *)&argLoc,
Identifier::getFromOpaquePointer(argName),
*(SourceLoc *)¶mLoc,
Identifier::getFromOpaquePointer(paramName),
(DeclContext *)declContext);
}
void *FuncDecl_create(void *ctx, void *staticLoc, bool isStatic, void *funcLoc,
BridgedIdentifier name, void *nameLoc,
bool isAsync, void *_Nullable asyncLoc,
bool throws, void *_Nullable throwsLoc,
void *paramLLoc, BridgedArrayRef params, void *paramRLoc,
void *_Nullable body, void *_Nullable returnType,
void *declContext) {
auto *paramList = ParameterList::create(
*static_cast<ASTContext *>(ctx), *(SourceLoc *)¶mLLoc,
getArrayRef<ParamDecl *>(params), *(SourceLoc *)¶mRLoc);
auto declName =
DeclName(*static_cast<ASTContext *>(ctx),
Identifier::getFromOpaquePointer(name), paramList);
auto *out = FuncDecl::create(
*static_cast<ASTContext *>(ctx), *(SourceLoc *)&staticLoc,
isStatic ? StaticSpellingKind::KeywordStatic : StaticSpellingKind::None,
*(SourceLoc *)&funcLoc, declName, *(SourceLoc *)&nameLoc, isAsync,
*(SourceLoc *)&asyncLoc, throws, *(SourceLoc *)&throwsLoc, nullptr,
paramList, (TypeRepr *)returnType, (DeclContext *)declContext);
out->setBody((BraceStmt *)body, FuncDecl::BodyKind::Parsed);
return static_cast<Decl *>(out);
}
void *SimpleIdentTypeRepr_create(void *ctx, void *loc, BridgedIdentifier id) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) SimpleIdentTypeRepr(DeclNameLoc(*(SourceLoc *)&loc),
DeclNameRef(Identifier::getFromOpaquePointer(id)));
}
void *UnresolvedDotExpr_create(
void *ctx, void *base, void *dotLoc, BridgedIdentifier name,
void *nameLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) UnresolvedDotExpr((Expr *)base, *(SourceLoc *)&dotLoc,
DeclNameRef(Identifier::getFromOpaquePointer(name)),
DeclNameLoc(*(SourceLoc *)&nameLoc), false);
}
void *ClosureExpr_create(void *ctx, void *body, void *dc) {
DeclAttributes attributes;
SourceRange bracketRange;
SourceLoc asyncLoc;
SourceLoc throwsLoc;
SourceLoc arrowLoc;
SourceLoc inLoc;
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *out = new (Context) ClosureExpr(attributes, bracketRange, nullptr,
nullptr, asyncLoc, throwsLoc, arrowLoc,
inLoc, nullptr, 0, (DeclContext *)dc);
out->setBody((BraceStmt *)body, true);
return (Expr *)out;
}
void NominalTypeDecl_setMembers(void *decl, BridgedArrayRef members) {
auto declMembers = getArrayRef<Decl *>(members);
for (auto m : declMembers)
((NominalTypeDecl *)decl)->addMember(m);
}
DeclContextAndDecl StructDecl_create(
void *ctx, void *loc, BridgedIdentifier name, void *nameLoc, void *dc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *out = new (Context) StructDecl(SourceLoc(), // *(SourceLoc *)&loc,
Identifier::getFromOpaquePointer(name),
SourceLoc(), // *(SourceLoc *)&nameLoc,
{}, nullptr,
(DeclContext *)dc);
out->setImplicit(); // TODO: remove this.
return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out};
}
DeclContextAndDecl ClassDecl_create(
void *ctx, void *loc, BridgedIdentifier name, void *nameLoc, void *dc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *out = new (Context) ClassDecl(SourceLoc(), // *(SourceLoc *)&loc,
Identifier::getFromOpaquePointer(name),
SourceLoc(), // *(SourceLoc *)&nameLoc,
{}, nullptr,
(DeclContext *)dc, false);
out->setImplicit(); // TODO: remove this.
return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out};
}
void TopLevelCodeDecl_dump(void *decl) { ((TopLevelCodeDecl *)decl)->dump(); }
void Expr_dump(void *expr) { ((Expr *)expr)->dump(); }
void Decl_dump(void *expr) { ((Decl *)expr)->dump(); }
void Stmt_dump(void *expr) { ((Stmt *)expr)->dump(); }
<commit_msg>[ASTGen] Clean up casting with source locations<commit_after>#include "swift/AST/CASTBridging.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeRepr.h"
using namespace swift;
template <typename T>
inline llvm::ArrayRef<T> getArrayRef(BridgedArrayRef bridged) {
return {static_cast<const T *>(bridged.data), size_t(bridged.numElements)};
}
static SourceLoc getSourceLocFromPointer(void *loc) {
auto smLoc = llvm::SMLoc::getFromPointer((const char *)loc);
return SourceLoc(smLoc);
}
BridgedIdentifier
SwiftASTContext_getIdentifier(void *ctx, const uint8_t *_Nullable str, long len) {
return const_cast<void *>(
static_cast<ASTContext *>(ctx)
->getIdentifier(
StringRef{reinterpret_cast<const char *>(str), size_t(len)})
.getAsOpaquePointer());
}
void *SwiftImportDecl_create(void *ctx, void *dc, void *importLoc, char kind,
void *kindLoc, BridgedArrayRef path,
BridgedArrayRef pathLocs) {
assert(path.numElements == pathLocs.numElements);
ASTContext &Context = *static_cast<ASTContext *>(ctx);
ImportPath::Builder importPath;
for (auto p : llvm::zip(getArrayRef<Identifier>(path),
getArrayRef<SourceLoc>(pathLocs))) {
Identifier ident;
SourceLoc loc;
std::tie(ident, loc) = p;
importPath.push_back(ident, loc);
}
return ImportDecl::create(
Context, static_cast<DeclContext *>(dc),
getSourceLocFromPointer(importLoc),
static_cast<ImportKind>(kind), getSourceLocFromPointer(kindLoc),
std::move(importPath).get());
}
void *BridgedSourceLoc_advanced(void *loc, long len) {
SourceLoc l = getSourceLocFromPointer(loc).getAdvancedLoc(len);
return const_cast<void *>(l.getOpaquePointerValue());
}
void *SwiftTopLevelCodeDecl_createStmt(void *ctx, void *DC, void *startLoc,
void *element, void *endLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *S = static_cast<Stmt *>(element);
auto Brace =
BraceStmt::create(Context, getSourceLocFromPointer(startLoc),
{S}, getSourceLocFromPointer(endLoc),
/*Implicit=*/true);
auto *TLCD =
new (Context) TopLevelCodeDecl(static_cast<DeclContext *>(DC), Brace);
return (Decl *)TLCD;
}
void *SwiftTopLevelCodeDecl_createExpr(void *ctx, void *DC, void *startLoc,
void *element, void *endLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *E = static_cast<Expr *>(element);
auto Brace =
BraceStmt::create(Context, getSourceLocFromPointer(startLoc),
{E}, getSourceLocFromPointer(endLoc),
/*Implicit=*/true);
auto *TLCD =
new (Context) TopLevelCodeDecl(static_cast<DeclContext *>(DC), Brace);
return (Decl *)TLCD;
}
void *SwiftSequenceExpr_create(void *ctx, BridgedArrayRef exprs) {
return SequenceExpr::create(*static_cast<ASTContext *>(ctx),
getArrayRef<Expr *>(exprs));
}
void *SwiftTupleExpr_create(void *ctx, void *lparen, BridgedArrayRef subs,
void *rparen) {
return TupleExpr::create(
*static_cast<ASTContext *>(ctx), getSourceLocFromPointer(lparen),
getArrayRef<Expr *>(subs), {}, {}, getSourceLocFromPointer(rparen),
/*Implicit*/ false);
}
void *SwiftFunctionCallExpr_create(void *ctx, void *fn, void *args) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
TupleExpr *TE = static_cast<TupleExpr *>(args);
SmallVector<Argument, 8> arguments;
for (unsigned i = 0; i < TE->getNumElements(); ++i) {
arguments.emplace_back(TE->getElementNameLoc(i), TE->getElementName(i),
TE->getElement(i));
}
auto *argList = ArgumentList::create(Context, TE->getLParenLoc(), arguments,
TE->getRParenLoc(), None,
/*isImplicit*/ false);
return CallExpr::create(Context, static_cast<Expr *>(fn), argList,
/*implicit*/ false);
}
void *SwiftIdentifierExpr_create(void *ctx, BridgedIdentifier base, void *loc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto name = DeclNameRef{
swift::Identifier::getFromOpaquePointer(base)};
Expr *E = new (Context) UnresolvedDeclRefExpr(
name, DeclRefKind::Ordinary, DeclNameLoc{getSourceLocFromPointer(loc)});
return E;
}
void *SwiftStringLiteralExpr_create(
void *ctx, const uint8_t *_Nullable string,
long len, void *TokenLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) StringLiteralExpr(
StringRef{reinterpret_cast<const char *>(string), size_t(len)},
getSourceLocFromPointer(TokenLoc));
}
void *SwiftIntegerLiteralExpr_create(
void *ctx, const uint8_t *_Nullable string, long len, void *TokenLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) IntegerLiteralExpr(
StringRef{reinterpret_cast<const char *>(string), size_t(len)},
getSourceLocFromPointer(TokenLoc));
}
void *SwiftBooleanLiteralExpr_create(void *ctx, bool value, void *TokenLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) BooleanLiteralExpr(
value, getSourceLocFromPointer(TokenLoc));
}
void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable nameId,
void *loc, bool isStatic, bool isLet, void *dc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) VarDecl(isStatic,
isLet ? VarDecl::Introducer::Let : VarDecl::Introducer::Var,
getSourceLocFromPointer(loc),
Identifier::getFromOpaquePointer(nameId),
reinterpret_cast<DeclContext *>(dc));
}
void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then, void *_Nullable elseLoc,
void *_Nullable elseStmt) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) IfStmt(
getSourceLocFromPointer(ifLoc), (Expr *)cond, (Stmt *)then,
getSourceLocFromPointer(elseLoc), (Stmt *)elseStmt, None, Context);
}
void *BraceStmt_createExpr(void *ctx, void *lbloc, BridgedArrayRef elements, void *rbloc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return BraceStmt::create(Context, getSourceLocFromPointer(lbloc),
getArrayRef<ASTNode>(elements),
getSourceLocFromPointer(rbloc));
}
void *BraceStmt_createStmt(void *ctx, void *lbloc, BridgedArrayRef elements, void *rbloc) {
llvm::SmallVector<ASTNode, 6> nodes;
for (auto stmt : getArrayRef<Stmt *>(elements)) {
nodes.push_back(stmt);
}
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return BraceStmt::create(Context, getSourceLocFromPointer(lbloc),
Context.AllocateCopy(nodes),
getSourceLocFromPointer(rbloc));
}
void *ParamDecl_create(
void *ctx, void *loc,
void *_Nullable argLoc, BridgedIdentifier _Nullable argName,
void *_Nullable paramLoc, BridgedIdentifier _Nullable paramName,
void *declContext) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) ParamDecl(getSourceLocFromPointer(loc),
getSourceLocFromPointer(argLoc),
Identifier::getFromOpaquePointer(argName),
getSourceLocFromPointer(paramLoc),
Identifier::getFromOpaquePointer(paramName),
(DeclContext *)declContext);
}
void *FuncDecl_create(void *ctx, void *staticLoc, bool isStatic, void *funcLoc,
BridgedIdentifier name, void *nameLoc,
bool isAsync, void *_Nullable asyncLoc,
bool throws, void *_Nullable throwsLoc,
void *paramLLoc, BridgedArrayRef params, void *paramRLoc,
void *_Nullable body, void *_Nullable returnType,
void *declContext) {
auto *paramList = ParameterList::create(
*static_cast<ASTContext *>(ctx), getSourceLocFromPointer(paramLLoc),
getArrayRef<ParamDecl *>(params), getSourceLocFromPointer(paramRLoc));
auto declName =
DeclName(*static_cast<ASTContext *>(ctx),
Identifier::getFromOpaquePointer(name), paramList);
auto *out = FuncDecl::create(
*static_cast<ASTContext *>(ctx), getSourceLocFromPointer(staticLoc),
isStatic ? StaticSpellingKind::KeywordStatic : StaticSpellingKind::None,
getSourceLocFromPointer(funcLoc), declName,
getSourceLocFromPointer(nameLoc), isAsync,
getSourceLocFromPointer(asyncLoc), throws,
getSourceLocFromPointer(throwsLoc), nullptr,
paramList, (TypeRepr *)returnType, (DeclContext *)declContext);
out->setBody((BraceStmt *)body, FuncDecl::BodyKind::Parsed);
return static_cast<Decl *>(out);
}
void *SimpleIdentTypeRepr_create(void *ctx, void *loc, BridgedIdentifier id) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) SimpleIdentTypeRepr(
DeclNameLoc(getSourceLocFromPointer(loc)),
DeclNameRef(Identifier::getFromOpaquePointer(id)));
}
void *UnresolvedDotExpr_create(
void *ctx, void *base, void *dotLoc, BridgedIdentifier name,
void *nameLoc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
return new (Context) UnresolvedDotExpr(
(Expr *)base, getSourceLocFromPointer(dotLoc),
DeclNameRef(Identifier::getFromOpaquePointer(name)),
DeclNameLoc(getSourceLocFromPointer(nameLoc)), false);
}
void *ClosureExpr_create(void *ctx, void *body, void *dc) {
DeclAttributes attributes;
SourceRange bracketRange;
SourceLoc asyncLoc;
SourceLoc throwsLoc;
SourceLoc arrowLoc;
SourceLoc inLoc;
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *out = new (Context) ClosureExpr(attributes, bracketRange, nullptr,
nullptr, asyncLoc, throwsLoc, arrowLoc,
inLoc, nullptr, 0, (DeclContext *)dc);
out->setBody((BraceStmt *)body, true);
return (Expr *)out;
}
void NominalTypeDecl_setMembers(void *decl, BridgedArrayRef members) {
auto declMembers = getArrayRef<Decl *>(members);
for (auto m : declMembers)
((NominalTypeDecl *)decl)->addMember(m);
}
DeclContextAndDecl StructDecl_create(
void *ctx, void *loc, BridgedIdentifier name, void *nameLoc, void *dc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *out = new (Context) StructDecl(getSourceLocFromPointer(loc),
Identifier::getFromOpaquePointer(name),
getSourceLocFromPointer(nameLoc),
{}, nullptr,
(DeclContext *)dc);
out->setImplicit(); // TODO: remove this.
return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out};
}
DeclContextAndDecl ClassDecl_create(
void *ctx, void *loc, BridgedIdentifier name, void *nameLoc, void *dc) {
ASTContext &Context = *static_cast<ASTContext *>(ctx);
auto *out = new (Context) ClassDecl(getSourceLocFromPointer(loc),
Identifier::getFromOpaquePointer(name),
getSourceLocFromPointer(nameLoc),
{}, nullptr,
(DeclContext *)dc, false);
out->setImplicit(); // TODO: remove this.
return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out};
}
void TopLevelCodeDecl_dump(void *decl) { ((TopLevelCodeDecl *)decl)->dump(llvm::errs()); }
void Expr_dump(void *expr) { ((Expr *)expr)->dump(llvm::errs()); }
void Decl_dump(void *expr) { ((Decl *)expr)->dump(llvm::errs()); }
void Stmt_dump(void *expr) { ((Stmt *)expr)->dump(llvm::errs()); }
<|endoftext|> |
<commit_before>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>
namespace mtp
{
Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
{
NameToObjectIdMap list;
auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
list.reserve(folders.ObjectHandles.size());
for(auto id : folders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
list.insert(std::make_pair(name, id));
}
return list;
}
Library::Library(const mtp::SessionPtr & session): _session(session)
{
auto storages = _session->GetStorageIDs();
if (storages.StorageIDs.empty())
throw std::runtime_error("no storages found");
_storage = storages.StorageIDs[0]; //picking up first storage.
//zune fails to create artist/album without storage id
{
msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
for (auto id : rootFolders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == "Artists")
_artistsFolder = id;
else if (name == "Albums")
_albumsFolder = id;
else if (name == "Music")
_musicFolder = id;
}
}
if (_artistsFolder == ObjectId())
_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
if (_albumsFolder == ObjectId())
_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
if (_musicFolder == ObjectId())
_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;
debug("artists folder: ", _artistsFolder.Id);
debug("albums folder: ", _albumsFolder.Id);
debug("music folder: ", _musicFolder.Id);
auto musicFolders = ListAssociations(_musicFolder);
using namespace mtp;
{
auto artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);
for (auto id : artists.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
debug("artist: ", name, "\t", id.Id);
auto artist = std::make_shared<Artist>();
artist->Id = id;
artist->Name = name;
auto it = musicFolders.find(name);
if (it != musicFolders.end())
artist->MusicFolderId = it->second;
else
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
_artists.insert(std::make_pair(name, artist));
}
}
std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
{
auto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
for (auto id : albums.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
auto albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);
auto artist = GetArtist(artistName);
if (!artist)
error("invalid artist name in album ", name);
debug("album: ", name, "\t", id.Id, "\t", albumDate);
auto album = std::make_shared<Album>();
album->Name = name;
album->Artist = artist;
album->Id = id;
album->Year = ConvertDateTime(albumDate);
if (albumFolders.find(artist) == albumFolders.end()) {
albumFolders[artist] = ListAssociations(artist->MusicFolderId);
}
auto it = albumFolders.find(artist);
if (it == albumFolders.end())
throw std::runtime_error("no iterator after insert, internal error");
const auto & albums = it->second;
auto alit = albums.find(name);
if (alit != albums.end())
album->MusicFolderId = alit->second;
else
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
}
}
}
Library::~Library()
{ }
Library::ArtistPtr Library::CreateArtist(const std::string & name)
{
if (name.empty())
return nullptr;
ByteArray propList;
OutputStream os(propList);
os.Write32(2); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name + ".art");
auto artist = std::make_shared<Artist>();
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
artist->Name = name;
auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
artist->Id = response.ObjectId;
_artists.insert(std::make_pair(name, artist));
return artist;
}
Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, const std::string & name, int year)
{
if (name.empty() || !artist)
return nullptr;
ByteArray propList;
OutputStream os(propList);
os.Write32(year? 4: 3); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name + "--" + name + ".alb");
if (year)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(ConvertYear(year));
}
auto album = std::make_shared<Album>();
album->Artist = artist;
album->Name = name;
album->Year = year;
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
album->Id = response.ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
return album;
}
ObjectId Library::CreateTrack(ArtistPtr artist, AlbumPtr album, ObjectFormat type, const std::string &name, const std::string &filename, size_t size)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(3); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(filename);
auto response = _session->SendObjectPropList(Session::AnyStorage, Session::Device, type, size, propList);
return response.ObjectId;
}
}
<commit_msg>create track on given storage with given music/artist/album as parent<commit_after>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>
namespace mtp
{
Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
{
NameToObjectIdMap list;
auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
list.reserve(folders.ObjectHandles.size());
for(auto id : folders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
list.insert(std::make_pair(name, id));
}
return list;
}
Library::Library(const mtp::SessionPtr & session): _session(session)
{
auto storages = _session->GetStorageIDs();
if (storages.StorageIDs.empty())
throw std::runtime_error("no storages found");
_storage = storages.StorageIDs[0]; //picking up first storage.
//zune fails to create artist/album without storage id
{
msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
for (auto id : rootFolders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == "Artists")
_artistsFolder = id;
else if (name == "Albums")
_albumsFolder = id;
else if (name == "Music")
_musicFolder = id;
}
}
if (_artistsFolder == ObjectId())
_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
if (_albumsFolder == ObjectId())
_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
if (_musicFolder == ObjectId())
_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;
debug("artists folder: ", _artistsFolder.Id);
debug("albums folder: ", _albumsFolder.Id);
debug("music folder: ", _musicFolder.Id);
auto musicFolders = ListAssociations(_musicFolder);
using namespace mtp;
{
auto artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);
for (auto id : artists.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
debug("artist: ", name, "\t", id.Id);
auto artist = std::make_shared<Artist>();
artist->Id = id;
artist->Name = name;
auto it = musicFolders.find(name);
if (it != musicFolders.end())
artist->MusicFolderId = it->second;
else
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
_artists.insert(std::make_pair(name, artist));
}
}
std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
{
auto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
for (auto id : albums.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
auto albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);
auto artist = GetArtist(artistName);
if (!artist)
error("invalid artist name in album ", name);
debug("album: ", name, "\t", id.Id, "\t", albumDate);
auto album = std::make_shared<Album>();
album->Name = name;
album->Artist = artist;
album->Id = id;
album->Year = ConvertDateTime(albumDate);
if (albumFolders.find(artist) == albumFolders.end()) {
albumFolders[artist] = ListAssociations(artist->MusicFolderId);
}
auto it = albumFolders.find(artist);
if (it == albumFolders.end())
throw std::runtime_error("no iterator after insert, internal error");
const auto & albums = it->second;
auto alit = albums.find(name);
if (alit != albums.end())
album->MusicFolderId = alit->second;
else
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
}
}
}
Library::~Library()
{ }
Library::ArtistPtr Library::CreateArtist(const std::string & name)
{
if (name.empty())
return nullptr;
ByteArray propList;
OutputStream os(propList);
os.Write32(2); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name + ".art");
auto artist = std::make_shared<Artist>();
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
artist->Name = name;
auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
artist->Id = response.ObjectId;
_artists.insert(std::make_pair(name, artist));
return artist;
}
Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, const std::string & name, int year)
{
if (name.empty() || !artist)
return nullptr;
ByteArray propList;
OutputStream os(propList);
os.Write32(year? 4: 3); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name + "--" + name + ".alb");
if (year)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(ConvertYear(year));
}
auto album = std::make_shared<Album>();
album->Artist = artist;
album->Name = name;
album->Year = year;
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
album->Id = response.ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
return album;
}
ObjectId Library::CreateTrack(ArtistPtr artist, AlbumPtr album, ObjectFormat type, const std::string &name, const std::string &filename, size_t size)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(3); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(filename);
auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
return response.ObjectId;
}
}
<|endoftext|> |
<commit_before>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
namespace rstudio {
namespace core {
namespace {
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str().substr(2);
}
std::string proxyLockFileName()
{
return std::string()
+ ".rstudio-lock"
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), ".rstudio-lock") &&
isLockFileStale(filePath))
{
Error error = filePath.remove();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
if (proxyPath.exists())
{
Error error = proxyPath.remove();
if (error)
LOG_ERROR(error);
}
// write something to the file (to ensure it's created)
Error error = core::writeStringToFile(proxyPath, pidString());
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
return fileExistsError(ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
return error;
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<commit_msg>protect lockfiles with a guid<commit_after>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockGuid = "22341c29-6541-44eb-88da-e097378a46d4";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str().substr(2);
}
std::string proxyLockFileName()
{
return std::string()
+ ".rstudio-lock"
+ "-" + kFileLockGuid
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), ".rstudio-lock") &&
isLockFileStale(filePath))
{
Error error = filePath.remove();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
if (proxyPath.exists())
{
Error error = proxyPath.remove();
if (error)
LOG_ERROR(error);
}
// write something to the file (to ensure it's created)
Error error = core::writeStringToFile(proxyPath, pidString());
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
return fileExistsError(ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
return error;
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/types.hpp>
#include <eosio/chain/symbol.hpp>
namespace eosio { namespace chain {
/**
asset includes amount and currency symbol
asset::from_string takes a string of the form "10.0000 CUR" and constructs an asset
with amount = 10 and symbol(4,"CUR")
*/
struct asset
{
static constexpr int64_t max_amount = (1LL << 62) - 1;
explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {
EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
}
share_type amount;
symbol sym;
bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }
bool is_valid()const { return is_amount_within_range() && sym.valid(); }
double to_real()const { return static_cast<double>(amount) / precision(); }
uint8_t decimals()const;
string symbol_name()const;
int64_t precision()const;
const symbol& get_symbol() const { return sym; }
static asset from_string(const string& from);
string to_string()const;
asset& operator += (const asset& o)
{
FC_ASSERT(get_symbol() == o.get_symbol());
amount += o.amount;
return *this;
}
asset& operator -= (const asset& o)
{
FC_ASSERT(get_symbol() == o.get_symbol());
amount -= o.amount;
return *this;
}
asset operator -()const { return asset(-amount, get_symbol()); }
friend bool operator == (const asset& a, const asset& b)
{
return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);
}
friend bool operator < (const asset& a, const asset& b)
{
FC_ASSERT(a.get_symbol() == b.get_symbol());
return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());
}
friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }
friend bool operator != (const asset& a, const asset& b) { return !(a == b); }
friend bool operator > (const asset& a, const asset& b) { return !(a <= b); }
friend bool operator >= (const asset& a, const asset& b) { return !(a < b); }
friend asset operator - (const asset& a, const asset& b) {
FC_ASSERT(a.get_symbol() == b.get_symbol());
return asset(a.amount - b.amount, a.get_symbol());
}
friend asset operator + (const asset& a, const asset& b) {
FC_ASSERT(a.get_symbol() == b.get_symbol());
return asset(a.amount + b.amount, a.get_symbol());
}
friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }
};
struct extended_asset {
extended_asset(){}
extended_asset( asset a, name n ):quantity(a),contract(n){}
asset quantity;
name contract;
};
bool operator < (const asset& a, const asset& b);
bool operator <= (const asset& a, const asset& b);
}} // namespace eosio::chain
namespace fc {
inline void to_variant(const eosio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }
inline void from_variant(const fc::variant& var, eosio::chain::asset& vo) {
vo = eosio::chain::asset::from_string(var.get_string());
}
}
FC_REFLECT(eosio::chain::asset, (amount)(sym))
FC_REFLECT(eosio::chain::extended_asset, (quantity)(contract) )
<commit_msg>Add reflector_verify for FC_REFLECT serialization verification<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/types.hpp>
#include <eosio/chain/symbol.hpp>
namespace eosio { namespace chain {
/**
asset includes amount and currency symbol
asset::from_string takes a string of the form "10.0000 CUR" and constructs an asset
with amount = 10 and symbol(4,"CUR")
*/
struct asset
{
static constexpr int64_t max_amount = (1LL << 62) - 1;
explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {
EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
}
bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }
bool is_valid()const { return is_amount_within_range() && sym.valid(); }
double to_real()const { return static_cast<double>(amount) / precision(); }
uint8_t decimals()const;
string symbol_name()const;
int64_t precision()const;
const symbol& get_symbol() const { return sym; }
static asset from_string(const string& from);
string to_string()const;
asset& operator += (const asset& o)
{
FC_ASSERT(get_symbol() == o.get_symbol());
amount += o.amount;
return *this;
}
asset& operator -= (const asset& o)
{
FC_ASSERT(get_symbol() == o.get_symbol());
amount -= o.amount;
return *this;
}
asset operator -()const { return asset(-amount, get_symbol()); }
friend bool operator == (const asset& a, const asset& b)
{
return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);
}
friend bool operator < (const asset& a, const asset& b)
{
FC_ASSERT(a.get_symbol() == b.get_symbol());
return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());
}
friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }
friend bool operator != (const asset& a, const asset& b) { return !(a == b); }
friend bool operator > (const asset& a, const asset& b) { return !(a <= b); }
friend bool operator >= (const asset& a, const asset& b) { return !(a < b); }
friend asset operator - (const asset& a, const asset& b) {
FC_ASSERT(a.get_symbol() == b.get_symbol());
return asset(a.amount - b.amount, a.get_symbol());
}
friend asset operator + (const asset& a, const asset& b) {
FC_ASSERT(a.get_symbol() == b.get_symbol());
return asset(a.amount + b.amount, a.get_symbol());
}
friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }
friend struct fc::reflector<asset>;
void reflector_verify()const {
EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
}
private:
share_type amount;
symbol sym;
};
struct extended_asset {
extended_asset(){}
extended_asset( asset a, name n ):quantity(a),contract(n){}
asset quantity;
name contract;
};
bool operator < (const asset& a, const asset& b);
bool operator <= (const asset& a, const asset& b);
}} // namespace eosio::chain
namespace fc {
inline void to_variant(const eosio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }
inline void from_variant(const fc::variant& var, eosio::chain::asset& vo) {
vo = eosio::chain::asset::from_string(var.get_string());
}
}
FC_REFLECT(eosio::chain::asset, (amount)(sym))
FC_REFLECT(eosio::chain::extended_asset, (quantity)(contract) )
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Mohammed Nafees <[email protected]>
// Copyright 2012 Dennis Nienhüser <[email protected]>
// Copyright 2012 Illya Kovalevskyy <[email protected]>
//
#include "MapInfoDialog.h"
#include "MarbleWidget.h"
#include "PopupItem.h"
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtGui/QAction>
namespace Marble
{
MapInfoDialog::MapInfoDialog(QObject *parent) :
QObject( parent ),
m_popupItem( new PopupItem )
{
connect( m_popupItem, SIGNAL(dirty()), this, SIGNAL(repaintNeeded()) );
connect( m_popupItem, SIGNAL(hide()), this, SLOT(hidePopupItem()) );
}
MapInfoDialog::~MapInfoDialog()
{
}
QStringList MapInfoDialog::renderPosition() const
{
return QStringList( "ALWAYS_ON_TOP" );
}
QString MapInfoDialog::renderPolicy() const
{
return "ALWAYS";
}
bool MapInfoDialog::render( GeoPainter *painter, ViewportParams *viewport,
const QString&, GeoSceneLayer* )
{
if ( visible() ) {
m_popupItem->paintEvent( painter, viewport );
}
return true;
}
bool MapInfoDialog::eventFilter( QObject *object, QEvent *e )
{
return m_popupItem && visible() && m_popupItem->eventFilter( object, e );
}
qreal MapInfoDialog::zValue() const
{
return 4711.23;
}
bool MapInfoDialog::visible() const
{
return m_popupItem->visible();
}
void MapInfoDialog::setVisible( bool visible )
{
m_popupItem->setVisible( visible );
}
void MapInfoDialog::setCoordinates(const GeoDataCoordinates &coordinates , Qt::Alignment alignment)
{
if ( m_popupItem ) {
m_popupItem->setCoordinate( coordinates );
m_popupItem->setAlignment( alignment );
}
}
void MapInfoDialog::setUrl( const QUrl &url )
{
if ( m_popupItem ) {
m_popupItem->setUrl( url );
}
}
void MapInfoDialog::setContent( const QString &html )
{
if ( m_popupItem ) {
m_popupItem->setContent( html );
}
}
void MapInfoDialog::setBackgroundColor(const QColor &color)
{
if(color.isValid()) {
m_popupItem->setBackgroundColor(color);
}
}
void MapInfoDialog::setTextColor(const QColor &color)
{
if(color.isValid()) {
m_popupItem->setTextColor(color);
}
}
void MapInfoDialog::setSize( const QSizeF &size )
{
if ( m_popupItem ) {
m_popupItem->setSize( size );
}
}
void MapInfoDialog::setPosition( const QPointF &position )
{
/** @todo Implement */
Q_UNUSED( position );
}
void MapInfoDialog::hidePopupItem()
{
setVisible( false );
}
}
#include "MapInfoDialog.moc"
<commit_msg>Repaint when content changes.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Mohammed Nafees <[email protected]>
// Copyright 2012 Dennis Nienhüser <[email protected]>
// Copyright 2012 Illya Kovalevskyy <[email protected]>
//
#include "MapInfoDialog.h"
#include "MarbleWidget.h"
#include "PopupItem.h"
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtGui/QAction>
namespace Marble
{
MapInfoDialog::MapInfoDialog(QObject *parent) :
QObject( parent ),
m_popupItem( new PopupItem )
{
connect( m_popupItem, SIGNAL(dirty()), this, SIGNAL(repaintNeeded()) );
connect( m_popupItem, SIGNAL(hide()), this, SLOT(hidePopupItem()) );
}
MapInfoDialog::~MapInfoDialog()
{
}
QStringList MapInfoDialog::renderPosition() const
{
return QStringList( "ALWAYS_ON_TOP" );
}
QString MapInfoDialog::renderPolicy() const
{
return "ALWAYS";
}
bool MapInfoDialog::render( GeoPainter *painter, ViewportParams *viewport,
const QString&, GeoSceneLayer* )
{
if ( visible() ) {
m_popupItem->paintEvent( painter, viewport );
}
return true;
}
bool MapInfoDialog::eventFilter( QObject *object, QEvent *e )
{
return m_popupItem && visible() && m_popupItem->eventFilter( object, e );
}
qreal MapInfoDialog::zValue() const
{
return 4711.23;
}
bool MapInfoDialog::visible() const
{
return m_popupItem->visible();
}
void MapInfoDialog::setVisible( bool visible )
{
m_popupItem->setVisible( visible );
}
void MapInfoDialog::setCoordinates(const GeoDataCoordinates &coordinates , Qt::Alignment alignment)
{
if ( m_popupItem ) {
m_popupItem->setCoordinate( coordinates );
m_popupItem->setAlignment( alignment );
}
}
void MapInfoDialog::setUrl( const QUrl &url )
{
if ( m_popupItem ) {
m_popupItem->setUrl( url );
}
}
void MapInfoDialog::setContent( const QString &html )
{
if ( m_popupItem ) {
m_popupItem->setContent( html );
emit repaintNeeded();
}
}
void MapInfoDialog::setBackgroundColor(const QColor &color)
{
if(color.isValid()) {
m_popupItem->setBackgroundColor(color);
}
}
void MapInfoDialog::setTextColor(const QColor &color)
{
if(color.isValid()) {
m_popupItem->setTextColor(color);
}
}
void MapInfoDialog::setSize( const QSizeF &size )
{
if ( m_popupItem ) {
m_popupItem->setSize( size );
}
}
void MapInfoDialog::setPosition( const QPointF &position )
{
/** @todo Implement */
Q_UNUSED( position );
}
void MapInfoDialog::hidePopupItem()
{
setVisible( false );
}
}
#include "MapInfoDialog.moc"
<|endoftext|> |
<commit_before>#include <rusql/rusql.hpp>
#include <boost/thread.hpp>
#include "test.hpp"
#include "database_test.hpp"
int main(int argc, char *argv[]) {
auto db = get_database(argc, argv);
test_init(6);
db->execute("CREATE TABLE rusqltest (`value` INT(2) NOT NULL)");
db->execute("INSERT INTO rusqltest VALUES (20)");
auto statement = db->prepare("SELECT value FROM rusqltest");
statement.execute();
boost::thread thread([&db]() {
auto thread_handle = db->get_thread_handle();
db->execute("UPDATE rusqltest SET value=30");
});
thread.join();
uint64_t value = 10;
statement.bind_results(value);
test(statement.fetch(), "one result");
test(value == 20, "value was correct (" + std::to_string(value) + ")");
test(!statement.fetch(), "exactly one result");
statement.execute();
statement.bind_results(value);
test(statement.fetch(), "one result");
test(value == 30, "value was correct (" + std::to_string(value) + ")");
test(!statement.fetch(), "exactly one result");
db->execute("DROP TABLE rusqltest");
}
<commit_msg>Add level of indentation<commit_after>#include <rusql/rusql.hpp>
#include <boost/thread.hpp>
#include "test.hpp"
#include "database_test.hpp"
int main(int argc, char *argv[]) {
auto db = get_database(argc, argv);
test_init(6);
db->execute("CREATE TABLE rusqltest (`value` INT(2) NOT NULL)");
db->execute("INSERT INTO rusqltest VALUES (20)");
{
auto statement = db->prepare("SELECT value FROM rusqltest");
statement.execute();
boost::thread thread([&db]() {
auto thread_handle = db->get_thread_handle();
db->execute("UPDATE rusqltest SET value=30");
});
thread.join();
uint64_t value = 10;
statement.bind_results(value);
test(statement.fetch(), "one result");
test(value == 20, "value was correct (" + std::to_string(value) + ")");
test(!statement.fetch(), "exactly one result");
statement.execute();
statement.bind_results(value);
test(statement.fetch(), "one result");
test(value == 30, "value was correct (" + std::to_string(value) + ")");
test(!statement.fetch(), "exactly one result");
}
db->execute("DROP TABLE rusqltest");
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/network/hosts.hpp>
#include <metaverse/macros_define.hpp>
#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
#include <metaverse/bitcoin.hpp>
#include <metaverse/bitcoin/utility/path.hpp>
#include <metaverse/bitcoin/math/limits.hpp>
#include <metaverse/network/settings.hpp>
#include <metaverse/network/channel.hpp>
namespace libbitcoin {
namespace network {
uint32_t timer_interval = 60 * 5; // 5 minutes
hosts::hosts(threadpool& pool, const settings& settings)
: seed_count(settings.seeds.size())
, host_pool_capacity_(std::max(settings.host_pool_capacity, 1u))
, buffer_(host_pool_capacity_)
, backup_(host_pool_capacity_)
, inactive_(host_pool_capacity_ * 2)
, seeds_()
, stopped_(true)
, file_path_(default_data_path() / settings.hosts_file)
, disabled_(settings.host_pool_capacity == 0)
, pool_(pool)
, self_(settings.self)
{
}
// private
hosts::iterator hosts::find(const address& host)
{
return find(buffer_, host);
}
hosts::iterator hosts::find(list& buffer, const address& host)
{
const auto found = [&host](const address & entry)
{
return entry.port == host.port && entry.ip == host.ip;
};
return std::find_if(buffer.begin(), buffer.end(), found);
}
size_t hosts::count() const
{
///////////////////////////////////////////////////////////////////////////
// Critical Section
shared_lock lock(mutex_);
return buffer_.size();
///////////////////////////////////////////////////////////////////////////
}
code hosts::fetch_seed(address& out, const config::authority::list& excluded_list)
{
return fetch(seeds_, out, excluded_list);
}
code hosts::fetch(address& out, const config::authority::list& excluded_list)
{
return fetch(buffer_, out, excluded_list);
}
template <typename T>
code hosts::fetch(T& buffer, address& out, const config::authority::list& excluded_list)
{
if (disabled_) {
return error::not_found;
}
// Critical Section
shared_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
if (buffer.empty()) {
return error::not_found;
}
auto match = [&excluded_list](address& addr) {
auto auth = config::authority(addr);
return std::find(excluded_list.begin(), excluded_list.end(), auth) == excluded_list.end();
};
std::vector<address> vec;
std::copy_if(buffer.begin(), buffer.end(), std::back_inserter(vec), match);
if (vec.empty()) {
return error::not_found;
}
const auto index = pseudo_random(0, vec.size() - 1);
out = vec[static_cast<size_t>(index)];
return error::success;
}
hosts::address::list hosts::copy_seeds()
{
if (disabled_)
return address::list();
shared_lock lock{mutex_};
return seeds_;
}
hosts::address::list hosts::copy()
{
if (disabled_)
return address::list();
shared_lock lock{mutex_};
if (stopped_ || buffer_.empty())
return address::list();
// not copy all, but just 10% ~ 20% , at least one
const auto out_count = std::max<size_t>(1,
std::min<size_t>(1000, buffer_.size()) / pseudo_random(5, 10));
const auto limit = buffer_.size();
auto index = pseudo_random(0, limit - 1);
address::list copy(out_count);
for (size_t count = 0; count < out_count; ++count)
copy.push_back(buffer_[index++ % limit]);
pseudo_random::shuffle(copy);
return copy;
}
bool hosts::store_cache(bool succeed_clear_buffer)
{
if (!buffer_.empty()) {
bc::ofstream file(file_path_.string());
const auto file_error = file.bad();
if (file_error) {
log::error(LOG_NETWORK) << "hosts file (" << file_path_.string() << ") open failed" ;
return false;
}
log::debug(LOG_NETWORK)
<< "sync hosts to file(" << file_path_.string()
<< "), inactive size is " << inactive_.size()
<< ", buffer size is " << buffer_.size();
for (const auto& entry : buffer_) {
// TODO: create full space-delimited network_address serialization.
// Use to/from string format as opposed to wire serialization.
if (!(channel::blacklisted(entry) || channel::manualbanned(entry))) {
file << config::authority(entry) << std::endl;
}
}
if (succeed_clear_buffer) {
buffer_.clear();
}
}
else {
if (boost::filesystem::exists(file_path_.string())) {
boost::filesystem::remove_all(file_path_.string());
}
}
return true;
}
void hosts::handle_timer(const code& ec)
{
if (disabled_) {
return;
}
if (ec.value() != error::success) {
return;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return;
}
upgrade_to_unique_lock unq_lock(lock);
if (!store_cache()) {
return;
}
snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));
}
// load
code hosts::start()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (!stopped_) {
return error::operation_failed;
}
upgrade_to_unique_lock unq_lock(lock);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
snap_timer_ = std::make_shared<deadline>(pool_, asio::seconds(timer_interval));
snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));
stopped_ = false;
bc::ifstream file(file_path_.string());
const auto file_error = file.bad();
if (!file_error) {
std::string line;
while (std::getline(file, line)) {
config::authority host(line);
if (host.port() != 0) {
auto network_address = host.to_network_address();
if (network_address.is_routable()) {
buffer_.push_back(network_address);
if (buffer_.full()) {
break;
}
}
else {
log::debug(LOG_NETWORK) << "host start is not routable,"
<< config::authority{network_address};
}
}
}
}
if (file_error) {
log::debug(LOG_NETWORK)
<< "Failed to save hosts file.";
return error::file_system;
}
return error::success;
}
// load
code hosts::stop()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::success;
}
upgrade_to_unique_lock unq_lock(lock);
// stop timer
snap_timer_->stop();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
stopped_ = true;
if (!store_cache(true)) {
return error::file_system;
}
return error::success;
}
code hosts::clear()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
if (!buffer_.empty()) {
std::swap(backup_, buffer_);
buffer_.clear();
}
return error::success;
}
code hosts::after_reseeding()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
//re-seeding failed and recover the buffer with backup one
if (buffer_.size() <= seed_count) {
log::debug(LOG_NETWORK)
<< "Reseeding finished, buffer size: " << buffer_.size()
<< ", less than seed count: " << seed_count
<< ", roll back the hosts cache.";
if (!buffer_.full()) {
for (auto& host : backup_) {
if (find(host) == buffer_.end()) {
buffer_.push_back(host);
if (buffer_.full()) {
break;
}
}
}
}
}
else {
// filter inactive hosts
for (auto &host : inactive_) {
auto iter = find(host);
if (iter != buffer_.end()) {
buffer_.erase(iter);
}
}
}
// clear the backup
backup_.clear();
log::debug(LOG_NETWORK)
<< "Reseeding finished, buffer size: " << buffer_.size();
return error::success;
}
code hosts::remove(const address& host)
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
auto it = find(host);
if (it != buffer_.end()) {
buffer_.erase(it);
}
if (find(inactive_, host) == inactive_.end()) {
inactive_.push_back(host);
}
return error::success;
}
code hosts::store_seed(const address& host)
{
// don't store blacklist and banned address
if (channel::blacklisted(host) || channel::manualbanned(host)) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
auto iter = std::find_if(seeds_.begin(), seeds_.end(),
[&host](const address& item){
return host.ip == item.ip && host.port == item.port;
});
if (iter == seeds_.end()) {
constexpr size_t max_seeds = 8;
constexpr size_t half_pos = max_seeds >> 1;
upgrade_to_unique_lock unq_lock(lock);
if (seeds_.size() == max_seeds) { // full
std::copy(seeds_.begin()+half_pos+1, seeds_.end(), seeds_.begin()+half_pos);
seeds_.back() = host;
}
else {
seeds_.push_back(host);
}
#ifdef PRIVATE_CHAIN
log::info(LOG_NETWORK) << "store seed " << config::authority(host).to_string();
#endif
}
return error::success;
}
code hosts::remove_seed(const address& host)
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
auto iter = std::find_if(seeds_.begin(), seeds_.end(),
[&host](const address& item){
return host.ip == item.ip && host.port == item.port;
});
if (iter != seeds_.end()) {
upgrade_to_unique_lock unq_lock(lock);
seeds_.erase(iter);
#ifdef PRIVATE_CHAIN
log::info(LOG_NETWORK) << "remove seed " << config::authority(host).to_string();
#endif
}
return error::success;
}
code hosts::store(const address& host)
{
if (disabled_) {
return error::success;
}
if (!host.is_routable()) {
// We don't treat invalid address as an error, just log it.
return error::success;
}
// don't store self address
auto authority = config::authority{host};
if (authority == self_ || authority.port() == 0) {
return error::success;
}
// don't store blacklist and banned address
if (channel::blacklisted(host) || channel::manualbanned(host)) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
if (find(host) == buffer_.end()) {
buffer_.push_back(host);
}
auto iter = find(inactive_, host);
if (iter != inactive_.end()) {
inactive_.erase(iter);
}
return error::success;
}
// The handler is invoked once all calls to do_store are completed.
// We disperse here to allow other addresses messages to interleave hosts.
void hosts::store(const address::list& hosts, result_handler handler)
{
if (disabled_ || hosts.empty()) {
handler(error::success);
return;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
handler(error::service_stopped);
return;
}
// Accept between 1 and all of this peer's addresses up to capacity.
const auto capacity = host_pool_capacity_;
size_t host_size = hosts.size();
const size_t usable = std::min(host_size, capacity);
const size_t random = static_cast<size_t>(pseudo_random(1, usable));
// But always accept at least the amount we are short if available.
const size_t gap = capacity - buffer_.size();
const size_t accept = std::max(gap, random);
// Convert minimum desired to step for iteration, no less than 1.
const auto step = std::max(usable / accept, size_t(1));
size_t accepted = 0;
upgrade_to_unique_lock unq_lock(lock);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
for (size_t index = 0; index < usable; index = ceiling_add(index, step)) {
const auto& host = hosts[index];
// Do not treat invalid address as an error, just log it.
if (!host.is_valid()) {
log::debug(LOG_NETWORK)
<< "Invalid host address from peer.";
continue;
}
if (channel::blacklisted(host) || channel::manualbanned(host)) {
continue;
}
// Do not allow duplicates in the host cache.
if (find(host) == buffer_.end()
&& find(inactive_, host) == inactive_.end()) {
++accepted;
buffer_.push_back(host);
}
}
log::debug(LOG_NETWORK)
<< "Accepted (" << accepted << " of " << hosts.size()
<< ") host addresses from peer."
<< " inactive size is " << inactive_.size()
<< ", buffer size is " << buffer_.size();
handler(error::success);
}
} // namespace network
} // namespace libbitcoin
<commit_msg>fix mutex lock.<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/network/hosts.hpp>
#include <metaverse/macros_define.hpp>
#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
#include <metaverse/bitcoin.hpp>
#include <metaverse/bitcoin/utility/path.hpp>
#include <metaverse/bitcoin/math/limits.hpp>
#include <metaverse/network/settings.hpp>
#include <metaverse/network/channel.hpp>
namespace libbitcoin {
namespace network {
uint32_t timer_interval = 60 * 5; // 5 minutes
hosts::hosts(threadpool& pool, const settings& settings)
: seed_count(settings.seeds.size())
, host_pool_capacity_(std::max(settings.host_pool_capacity, 1u))
, buffer_(host_pool_capacity_)
, backup_(host_pool_capacity_)
, inactive_(host_pool_capacity_ * 2)
, seeds_()
, stopped_(true)
, file_path_(default_data_path() / settings.hosts_file)
, disabled_(settings.host_pool_capacity == 0)
, pool_(pool)
, self_(settings.self)
{
}
// private
hosts::iterator hosts::find(const address& host)
{
return find(buffer_, host);
}
hosts::iterator hosts::find(list& buffer, const address& host)
{
const auto found = [&host](const address & entry)
{
return entry.port == host.port && entry.ip == host.ip;
};
return std::find_if(buffer.begin(), buffer.end(), found);
}
size_t hosts::count() const
{
///////////////////////////////////////////////////////////////////////////
// Critical Section
shared_lock lock(mutex_);
return buffer_.size();
///////////////////////////////////////////////////////////////////////////
}
code hosts::fetch_seed(address& out, const config::authority::list& excluded_list)
{
return fetch(seeds_, out, excluded_list);
}
code hosts::fetch(address& out, const config::authority::list& excluded_list)
{
return fetch(buffer_, out, excluded_list);
}
template <typename T>
code hosts::fetch(T& buffer, address& out, const config::authority::list& excluded_list)
{
if (disabled_) {
return error::not_found;
}
// Critical Section
shared_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
if (buffer.empty()) {
return error::not_found;
}
auto match = [&excluded_list](address& addr) {
auto auth = config::authority(addr);
return std::find(excluded_list.begin(), excluded_list.end(), auth) == excluded_list.end();
};
std::vector<address> vec;
std::copy_if(buffer.begin(), buffer.end(), std::back_inserter(vec), match);
if (vec.empty()) {
return error::not_found;
}
const auto index = pseudo_random(0, vec.size() - 1);
out = vec[static_cast<size_t>(index)];
return error::success;
}
hosts::address::list hosts::copy_seeds()
{
if (disabled_)
return address::list();
shared_lock lock{mutex_};
return seeds_;
}
hosts::address::list hosts::copy()
{
if (disabled_)
return address::list();
shared_lock lock{mutex_};
if (stopped_ || buffer_.empty())
return address::list();
// not copy all, but just 10% ~ 20% , at least one
const auto out_count = std::max<size_t>(1,
std::min<size_t>(1000, buffer_.size()) / pseudo_random(5, 10));
const auto limit = buffer_.size();
auto index = pseudo_random(0, limit - 1);
address::list copy(out_count);
for (size_t count = 0; count < out_count; ++count)
copy.push_back(buffer_[index++ % limit]);
pseudo_random::shuffle(copy);
return copy;
}
bool hosts::store_cache(bool succeed_clear_buffer)
{
if (!buffer_.empty()) {
bc::ofstream file(file_path_.string());
const auto file_error = file.bad();
if (file_error) {
log::error(LOG_NETWORK) << "hosts file (" << file_path_.string() << ") open failed" ;
return false;
}
log::debug(LOG_NETWORK)
<< "sync hosts to file(" << file_path_.string()
<< "), inactive size is " << inactive_.size()
<< ", buffer size is " << buffer_.size();
for (const auto& entry : buffer_) {
// TODO: create full space-delimited network_address serialization.
// Use to/from string format as opposed to wire serialization.
if (!(channel::blacklisted(entry) || channel::manualbanned(entry))) {
file << config::authority(entry) << std::endl;
}
}
if (succeed_clear_buffer) {
buffer_.clear();
}
}
else {
if (boost::filesystem::exists(file_path_.string())) {
boost::filesystem::remove_all(file_path_.string());
}
}
return true;
}
void hosts::handle_timer(const code& ec)
{
if (disabled_) {
return;
}
if (ec.value() != error::success) {
return;
}
{
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return;
}
upgrade_to_unique_lock unq_lock(lock);
if (!store_cache()) {
return;
}
}
snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));
}
// load
code hosts::start()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (!stopped_) {
return error::operation_failed;
}
upgrade_to_unique_lock unq_lock(lock);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
snap_timer_ = std::make_shared<deadline>(pool_, asio::seconds(timer_interval));
snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));
stopped_ = false;
bc::ifstream file(file_path_.string());
const auto file_error = file.bad();
if (!file_error) {
std::string line;
while (std::getline(file, line)) {
config::authority host(line);
if (host.port() != 0) {
auto network_address = host.to_network_address();
if (network_address.is_routable()) {
buffer_.push_back(network_address);
if (buffer_.full()) {
break;
}
}
else {
log::debug(LOG_NETWORK) << "host start is not routable,"
<< config::authority{network_address};
}
}
}
}
if (file_error) {
log::debug(LOG_NETWORK)
<< "Failed to save hosts file.";
return error::file_system;
}
return error::success;
}
// load
code hosts::stop()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::success;
}
upgrade_to_unique_lock unq_lock(lock);
// stop timer
snap_timer_->stop();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
stopped_ = true;
if (!store_cache(true)) {
return error::file_system;
}
return error::success;
}
code hosts::clear()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
if (!buffer_.empty()) {
std::swap(backup_, buffer_);
buffer_.clear();
}
return error::success;
}
code hosts::after_reseeding()
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
//re-seeding failed and recover the buffer with backup one
if (buffer_.size() <= seed_count) {
log::debug(LOG_NETWORK)
<< "Reseeding finished, buffer size: " << buffer_.size()
<< ", less than seed count: " << seed_count
<< ", roll back the hosts cache.";
if (!buffer_.full()) {
for (auto& host : backup_) {
if (find(host) == buffer_.end()) {
buffer_.push_back(host);
if (buffer_.full()) {
break;
}
}
}
}
}
else {
// filter inactive hosts
for (auto &host : inactive_) {
auto iter = find(host);
if (iter != buffer_.end()) {
buffer_.erase(iter);
}
}
}
// clear the backup
backup_.clear();
log::debug(LOG_NETWORK)
<< "Reseeding finished, buffer size: " << buffer_.size();
return error::success;
}
code hosts::remove(const address& host)
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
auto it = find(host);
if (it != buffer_.end()) {
buffer_.erase(it);
}
if (find(inactive_, host) == inactive_.end()) {
inactive_.push_back(host);
}
return error::success;
}
code hosts::store_seed(const address& host)
{
// don't store blacklist and banned address
if (channel::blacklisted(host) || channel::manualbanned(host)) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
auto iter = std::find_if(seeds_.begin(), seeds_.end(),
[&host](const address& item){
return host.ip == item.ip && host.port == item.port;
});
if (iter == seeds_.end()) {
constexpr size_t max_seeds = 8;
constexpr size_t half_pos = max_seeds >> 1;
upgrade_to_unique_lock unq_lock(lock);
if (seeds_.size() == max_seeds) { // full
std::copy(seeds_.begin()+half_pos+1, seeds_.end(), seeds_.begin()+half_pos);
seeds_.back() = host;
}
else {
seeds_.push_back(host);
}
#ifdef PRIVATE_CHAIN
log::info(LOG_NETWORK) << "store seed " << config::authority(host).to_string();
#endif
}
return error::success;
}
code hosts::remove_seed(const address& host)
{
if (disabled_) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
auto iter = std::find_if(seeds_.begin(), seeds_.end(),
[&host](const address& item){
return host.ip == item.ip && host.port == item.port;
});
if (iter != seeds_.end()) {
upgrade_to_unique_lock unq_lock(lock);
seeds_.erase(iter);
#ifdef PRIVATE_CHAIN
log::info(LOG_NETWORK) << "remove seed " << config::authority(host).to_string();
#endif
}
return error::success;
}
code hosts::store(const address& host)
{
if (disabled_) {
return error::success;
}
if (!host.is_routable()) {
// We don't treat invalid address as an error, just log it.
return error::success;
}
// don't store self address
auto authority = config::authority{host};
if (authority == self_ || authority.port() == 0) {
return error::success;
}
// don't store blacklist and banned address
if (channel::blacklisted(host) || channel::manualbanned(host)) {
return error::success;
}
// Critical Section
upgrade_lock lock(mutex_);
if (stopped_) {
return error::service_stopped;
}
upgrade_to_unique_lock unq_lock(lock);
if (find(host) == buffer_.end()) {
buffer_.push_back(host);
}
auto iter = find(inactive_, host);
if (iter != inactive_.end()) {
inactive_.erase(iter);
}
return error::success;
}
// The handler is invoked once all calls to do_store are completed.
// We disperse here to allow other addresses messages to interleave hosts.
void hosts::store(const address::list& hosts, result_handler handler)
{
if (disabled_ || hosts.empty()) {
handler(error::success);
return;
}
// Critical Section
mutex_.lock_upgrade();
if (stopped_) {
mutex_.unlock_upgrade();
handler(error::service_stopped);
return;
}
// Accept between 1 and all of this peer's addresses up to capacity.
const auto capacity = host_pool_capacity_;
size_t host_size = hosts.size();
const size_t usable = std::min(host_size, capacity);
const size_t random = static_cast<size_t>(pseudo_random(1, usable));
// But always accept at least the amount we are short if available.
const size_t gap = capacity - buffer_.size();
const size_t accept = std::max(gap, random);
// Convert minimum desired to step for iteration, no less than 1.
const auto step = std::max(usable / accept, size_t(1));
size_t accepted = 0;
mutex_.unlock_upgrade_and_lock();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
for (size_t index = 0; index < usable; index = ceiling_add(index, step)) {
const auto& host = hosts[index];
// Do not treat invalid address as an error, just log it.
if (!host.is_valid()) {
log::debug(LOG_NETWORK)
<< "Invalid host address from peer.";
continue;
}
if (channel::blacklisted(host) || channel::manualbanned(host)) {
continue;
}
// Do not allow duplicates in the host cache.
if (find(host) == buffer_.end()
&& find(inactive_, host) == inactive_.end()) {
++accepted;
buffer_.push_back(host);
}
}
log::debug(LOG_NETWORK)
<< "Accepted (" << accepted << " of " << hosts.size()
<< ") host addresses from peer."
<< " inactive size is " << inactive_.size()
<< ", buffer size is " << buffer_.size();
mutex_.unlock();
handler(error::success);
}
} // namespace network
} // namespace libbitcoin
<|endoftext|> |
<commit_before>#include <iostream> //cout
#include <string>
#include "qmc.h"
#include <gmc.h> //LaGenMatComplex
#include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
#include <random> //random_device, mt19937
#include <cstdlib> //rand, srand
#include <math.h>
using namespace std;
/* ---- WORKING ---- */
/* Randomisation */
int random_spin(){
random_device rd;
mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, 1);
return dist(gen)*2 - 1;
}
float random_probability(){
random_device rd;
mt19937 gen(rd());
std::uniform_real_distribution<> dist(0, 1);
return dist(gen);
}
/* Testing */
void test_spin_generation(){
for(int i = 0; i < 5; i++){
cout.width(10);
cout << random_spin();
}
cout << endl;
}
void test_probability_generation(){
for(int i = 0; i < 5; i++){
cout.width(5);
cout << random_probability();
}
cout << endl;
}
/* ---- TESTING ----*/
/* Output */
void print_sites(const int array[], const int array_size){
for(int i = 0; i < array_size; i++){
cout.width(7);
cout << array[i];
}
cout << endl;
}
/* Randomisation */
/* Generation */
void generate_lattice_array(const int array_size, int array[]){
for(int i = 0; i < array_size; i++){
array[i] = random_spin();
}
}
/* Testing */
void test_generate_lattice_array(){
int array_size = 5, array[5];
generate_lattice_array(array_size, array);
print_sites(array, array_size);
}
void test_sweep(){
/* Plan */
/* [ ] Input */
// [ ] lattice_size - int
// [ ] time_slices - int
// [ ] iterations - int
// [ ] lattice - LaGenMatComplex
// [ ] U - float
/* [ ] Processing */
// [ ] generate a lattice of spins
// [ ] sweep the lattice
/* [ ] Output */
// [ ] average spins
// [ ] acceptance probabilities
// int lattice_size = 5, time_slices = 4;
// int matrix_size = lattice_size * time_slices;
}
void test_increasing_U(){
/* Plan */
/* [ ] Input */
// [ ] matrix_size - int
// [ ] iterations - int
// [ ] lattice - LaGenMatComplex
// [ ] U - float
/* [ ] Processing */
// [ ] for n increasing values of U
// [ ] generate a lattice of spins
// [ ] sweep the lattice
/* [ ] Output */
// [ ] acceptance probabilities
}
/* --- Main QMC Program --- */
int main(){
test_generate_lattice_array();
}
<commit_msg>generate_lattice_array - testing<commit_after>#include <iostream> //cout
#include <string>
#include "qmc.h"
#include <gmc.h> //LaGenMatComplex
#include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
#include <random> //random_device, mt19937
#include <cstdlib> //rand, srand
#include <math.h>
using namespace std;
/* ---- WORKING ---- */
/* Randomisation */
int random_spin(){
random_device rd;
mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, 1);
return dist(gen)*2 - 1;
}
float random_probability(){
random_device rd;
mt19937 gen(rd());
std::uniform_real_distribution<> dist(0, 1);
return dist(gen);
}
/* Testing */
void test_spin_generation(){
for(int i = 0; i < 5; i++){
cout.width(10);
cout << random_spin();
}
cout << endl;
}
void test_probability_generation(){
for(int i = 0; i < 5; i++){
cout.width(5);
cout << random_probability();
}
cout << endl;
}
/* ---- TESTING ----*/
/* Output */
void print_sites(const int array[], const int array_size){
for(int i = 0; i < array_size; i++){
cout.width(7);
cout << array[i];
}
cout << endl;
}
/* Randomisation */
/* Generation */
void generate_lattice_array(const int array_size, int array[]){
for(int i = 0; i < array_size; i++){
array[i] = random_spin();
}
}
/* Testing */
void test_generate_lattice_array(){
int array_size = 10, array[array_size];
generate_lattice_array(array_size, array);
print_sites(array, array_size);
}
void test_sweep(){
/* Plan */
/* [ ] Input */
// [ ] lattice_size - int
// [ ] time_slices - int
// [ ] iterations - int
// [ ] lattice - LaGenMatComplex
// [ ] U - float
/* [ ] Processing */
// [ ] generate a lattice of spins
// [ ] sweep the lattice
/* [ ] Output */
// [ ] average spins
// [ ] acceptance probabilities
// int lattice_size = 5, time_slices = 4;
// int matrix_size = lattice_size * time_slices;
}
void test_increasing_U(){
/* Plan */
/* [ ] Input */
// [ ] matrix_size - int
// [ ] iterations - int
// [ ] lattice - LaGenMatComplex
// [ ] U - float
/* [ ] Processing */
// [ ] for n increasing values of U
// [ ] generate a lattice of spins
// [ ] sweep the lattice
/* [ ] Output */
// [ ] acceptance probabilities
}
/* --- Main QMC Program --- */
int main(){
test_generate_lattice_array();
}
<|endoftext|> |
<commit_before>//===-- Valgrind.cpp - Implement Valgrind communication ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Defines Valgrind communication methods, if HAVE_VALGRIND_VALGRIND_H is
// defined. If we have valgrind.h but valgrind isn't running, its macros are
// no-ops.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Valgrind.h"
#include "llvm/Config/config.h"
#if HAVE_VALGRIND_VALGRIND_H
#include <valgrind/valgrind.h>
static bool InitNotUnderValgrind() {
return !RUNNING_ON_VALGRIND;
}
// This bool is negated from what we'd expect because code may run before it
// gets initialized. If that happens, it will appear to be 0 (false), and we
// want that to cause the rest of the code in this file to run the
// Valgrind-provided macros.
static const bool NotUnderValgrind = InitNotUnderValgrind();
bool llvm::sys::RunningOnValgrind() {
if (NotUnderValgrind)
return false;
return RUNNING_ON_VALGRIND;
}
void llvm::sys::ValgrindDiscardTranslations(const void *Addr, size_t Len) {
if (NotUnderValgrind)
return;
VALGRIND_DISCARD_TRANSLATIONS(Addr, Len);
}
#else // !HAVE_VALGRIND_VALGRIND_H
bool llvm::sys::RunningOnValgrind() {
return false;
}
void llvm::sys::ValgrindDiscardTranslations(const void *Addr, size_t Len) {
}
#endif // !HAVE_VALGRIND_VALGRIND_H
<commit_msg>Add a missing include of cstddef needed for size_t.<commit_after>//===-- Valgrind.cpp - Implement Valgrind communication ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Defines Valgrind communication methods, if HAVE_VALGRIND_VALGRIND_H is
// defined. If we have valgrind.h but valgrind isn't running, its macros are
// no-ops.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Valgrind.h"
#include "llvm/Config/config.h"
#include <cstddef>
#if HAVE_VALGRIND_VALGRIND_H
#include <valgrind/valgrind.h>
static bool InitNotUnderValgrind() {
return !RUNNING_ON_VALGRIND;
}
// This bool is negated from what we'd expect because code may run before it
// gets initialized. If that happens, it will appear to be 0 (false), and we
// want that to cause the rest of the code in this file to run the
// Valgrind-provided macros.
static const bool NotUnderValgrind = InitNotUnderValgrind();
bool llvm::sys::RunningOnValgrind() {
if (NotUnderValgrind)
return false;
return RUNNING_ON_VALGRIND;
}
void llvm::sys::ValgrindDiscardTranslations(const void *Addr, size_t Len) {
if (NotUnderValgrind)
return;
VALGRIND_DISCARD_TRANSLATIONS(Addr, Len);
}
#else // !HAVE_VALGRIND_VALGRIND_H
bool llvm::sys::RunningOnValgrind() {
return false;
}
void llvm::sys::ValgrindDiscardTranslations(const void *Addr, size_t Len) {
}
#endif // !HAVE_VALGRIND_VALGRIND_H
<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
}<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
}<|endoftext|> |
<commit_before>#include "table.hpp"
#include <iomanip>
namespace opossum {
table::table(const size_t chunk_size) : _chunk_size(chunk_size) {
_chunks.push_back(chunk());
}
void table::add_column(std::string &&name, std::string type) {
_column_names.push_back(name);
_column_types.push_back(type);
for(auto &chunk : _chunks) {
chunk.add_column(type);
}
// TODO default values for existing rows?
}
void table::append(std::initializer_list<all_type_variant> values) {
if(_chunk_size > 0 && _chunks.back().size() == _chunk_size) {
_chunks.emplace_back();
// TODO add columns to new chunk - only once we know how to deal with different types (HANA?)
}
_chunks.back().append(values);
}
size_t table::col_count() const {
return _column_types.size();
}
std::vector<int> table::column_string_widths(int max) const {
std::vector<int> widths(col_count());
for(size_t col = 0; col < col_count(); ++col) {
widths[col] = to_string(_column_names[col]).size();
}
for(auto &&chunk : _chunks) {
auto widths2 = chunk.column_string_widths(max);
for(size_t col = 0; col < col_count(); ++col) {
widths[col] = std::max(widths[col], widths2[col]);
}
}
return widths;
}
void table::print(std::ostream &out) const {
auto widths = column_string_widths(20);
for(size_t col = 0; col < col_count(); ++col) {
out << "|" << std::setw(widths[col]) << _column_names[col] << std::setw(0) << "|";
}
out << std::endl;
size_t chunk_id = 0;
for(auto &&chunk : _chunks) {
out << "=== chunk " << chunk_id << " === " << std::endl;
chunk_id++;
chunk.print(out, widths);
}
}
}<commit_msg>Added row_count() to opossum::table<commit_after>#include "table.hpp"
#include <iomanip>
namespace opossum {
table::table(const size_t chunk_size) : _chunk_size(chunk_size) {
_chunks.push_back(chunk());
}
void table::add_column(std::string &&name, std::string type) {
_column_names.push_back(name);
_column_types.push_back(type);
for(auto &chunk : _chunks) {
chunk.add_column(type);
}
// TODO default values for existing rows?
}
void table::append(std::initializer_list<all_type_variant> values) {
if(_chunk_size > 0 && _chunks.back().size() == _chunk_size) {
_chunks.emplace_back();
// TODO add columns to new chunk - only once we know how to deal with different types (HANA?)
}
_chunks.back().append(values);
}
size_t table::col_count() const {
return _column_types.size();
}
size_t table::row_count() const {
size_t ret = 0;
for (auto &&chunk : _chunks) {
ret += chunk.size();
}
return ret;
}
std::vector<int> table::column_string_widths(int max) const {
std::vector<int> widths(col_count());
for(size_t col = 0; col < col_count(); ++col) {
widths[col] = to_string(_column_names[col]).size();
}
for(auto &&chunk : _chunks) {
auto widths2 = chunk.column_string_widths(max);
for(size_t col = 0; col < col_count(); ++col) {
widths[col] = std::max(widths[col], widths2[col]);
}
}
return widths;
}
void table::print(std::ostream &out) const {
auto widths = column_string_widths(20);
for(size_t col = 0; col < col_count(); ++col) {
out << "|" << std::setw(widths[col]) << _column_names[col] << std::setw(0);
}
out << "|" << std::endl;
size_t chunk_id = 0;
for(auto &&chunk : _chunks) {
out << "=== chunk " << chunk_id << " === " << std::endl;
chunk_id++;
chunk.print(out, widths);
}
}
}<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _WIN32
#pragma warning( 4:4786)
#endif
// interface header
#include "commands.h"
// implementation-specific system headers
#include <string>
#include <cstdio>
#include <cstring>
// implementation-specific bzflag headers
#include "global.h"
#include "Address.h"
// implementation-specific bzfs-specific headers
#include "VotingArbiter.h"
#include "Permissions.h"
#include "CmdLineOptions.h"
#include "PlayerInfo.h"
// FIXME -- need to pull communication out of bzfs.cxx...
extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message, bool fullBuffer);
extern bool hasPerm(int playerIndex, PlayerAccessInfo::AccessPerm right);
extern PlayerInfo *player;
extern CmdLineOptions *clOptions;
extern uint16_t curMaxPlayers;
extern int NotConnected;
void handlePollCmd(int t, const char *message)
{
char reply[MessageLen];
/* make sure player has permission to request a poll */
if (!hasPerm(t, PlayerAccessInfo::poll)) {
sprintf(reply,"%s, you are presently not authorized to run /poll", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure that there is a poll arbiter */
if (BZDB->isEmpty("poll")) {
sprintf(reply, "ERROR: the poll arbiter has disappeared (this should never happen)");
sendMessage(ServerPlayer, t, reply, true);
return;
}
// only need to do this once
static VotingArbiter *arbiter = (VotingArbiter *)BZDB->getPointer("poll");
/* make sure that there is not a poll active already */
if (arbiter->knowsPoll()) {
sprintf(reply,"A poll to %s %s is presently in progress", arbiter->getPollAction().c_str(), arbiter->getPollPlayer().c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Unable to start a new poll until the current one is over");
sendMessage(ServerPlayer, t, reply, true);
return;
}
// get available voter count
unsigned short int available = 0;
for (int i=0; i < curMaxPlayers; i++) {
// anyone on the server (even observers) are eligible to vote
if (player[i].fd != NotConnected) {
available++;
}
}
// make sure there are enough players to even make a poll (don't count the pollee)
if (available - 1 < clOptions->votesRequired) {
sprintf(reply,"Unable to initiate a new poll. There are not enough players.");
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"There needs to be at least %d other %s and only %d %s available.",
clOptions->votesRequired,
clOptions->votesRequired - 1 == 1 ? "player" : "players",
available - 1,
available - 1 == 1 ? "is" : "are");
sendMessage(ServerPlayer, t, reply, true);
return;
}
std::string pollCmd = &message[5];
std::string cmd;
std::string nick;
unsigned int endPos;
unsigned int startPos = pollCmd.find_first_not_of(" \t");
if (startPos != std::string::npos) {
endPos = pollCmd.find_first_of(" \t", startPos);
if (endPos == std::string::npos)
endPos = pollCmd.length();
cmd = pollCmd.substr(startPos,endPos-startPos);
pollCmd = pollCmd.substr(endPos);
}
else {
sprintf(reply,"Invalid poll syntax: /poll (kick|ban|vote|veto) playername");
sendMessage(ServerPlayer, t, reply, true);
return;
}
if ((cmd == "ban") || (cmd == "kick")) {
startPos = pollCmd.find_first_not_of(" \t");
if (startPos != std::string::npos) {
std::string votePlayer = pollCmd.substr(startPos);
if (votePlayer.length() == 0) {
sprintf(reply,"%s, no player was specified for the %s vote", player[t].callSign, cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /poll %s [playername]", cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure the requested player is actually here */
bool foundPlayer=false;
std::string playerIP = "";
for (int v = 0; v < curMaxPlayers; v++) {
if (votePlayer == player[v].callSign) {
playerIP = player[v].peer.getDotNotation().c_str();
foundPlayer=true;
break;
}
}
if (!foundPlayer) {
/* wrong name? */
sprintf(reply, "The player specified for a %s vote is not here", cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /poll %s [playername]", cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* create and announce the new poll */
if (cmd == "ban") {
if (arbiter->pollToBan(votePlayer.c_str(), player[t].callSign, playerIP) == false) {
sprintf(reply,"You are not able to request a ban poll right now, %s", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else {
sprintf(reply,"A poll to temporarily ban %s has been requested by %s", votePlayer.c_str(), player[t].callSign);
sendMessage(ServerPlayer, AllPlayers, reply, true);
}
} else {
if (arbiter->pollToKick(votePlayer.c_str(), player[t].callSign) == false) {
sprintf(reply,"You are not able to request a kick poll right now, %s", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else {
sprintf(reply,"A poll to %s %s has been requested by %s", cmd.c_str(), votePlayer.c_str(), player[t].callSign);
sendMessage(ServerPlayer, AllPlayers, reply, true);
}
}
// set the number of available voters
arbiter->setAvailableVoters(available);
// keep track of who is allowed to vote
for (int j=0; j < curMaxPlayers; j++) {
// anyone on the server (even observers) are eligible to vote
if (player[j].fd != NotConnected) {
arbiter->grantSuffrage(player[j].callSign);
}
}
// automatically place a vote for the player requesting the poll
arbiter->voteYes(player[t].callSign);
}
else {
sprintf(reply,"Invalid poll syntax: /poll %s playername", cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
} else if (cmd == "vote") {
if (!hasPerm(t, PlayerAccessInfo::vote)) {
sprintf(reply,"%s, you do not presently have permission to vote (must /identify first)", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* !!! needs to be handled by the /vote command */
sprintf(reply,"%s, your vote has been recorded -- unimplemented", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else if (cmd == "veto") {
if (!hasPerm(t, PlayerAccessInfo::veto)) {
sprintf(reply,"%s, you do not have permission to veto the poll", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
}
/* !!! needs to be handled by the /veto command */
sprintf(reply,"%s, you have aborted the poll -- unimplemented", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else {
sprintf(reply,"Invalid option to the poll command");
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /poll ban|kick [playername]");
sendMessage(ServerPlayer, t, reply, true);
} /* end handling of poll subcommands */
return;
}
void handleVoteCmd(int t, const char *message)
{
char reply[MessageLen];
if (!hasPerm(t, PlayerAccessInfo::vote)) {
/* permission denied for /vote */
sprintf(reply,"%s, you are presently not authorized to run /vote", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure that there is a poll arbiter */
if (BZDB->isEmpty("poll")) {
sprintf(reply, "ERROR: the poll arbiter has disappeared (this should never happen)");
sendMessage(ServerPlayer, t, reply, true);
return;
}
// only need to get this once
static VotingArbiter *arbiter = (VotingArbiter *)BZDB->getPointer("poll");
/* make sure that there is a poll to vote upon */
if ((arbiter != NULL) && !arbiter->knowsPoll()) {
sprintf(reply,"A poll is not presently in progress. There is nothing to vote on");
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* find the start of the vote answer */
std::string answer;
std::string voteCmd = &message[5];
unsigned int startPos = voteCmd.find_first_not_of(" \t");
if (startPos != std::string::npos) {
unsigned int endPos = voteCmd.find_first_of(" \t", startPos);
if (endPos == std::string::npos)
endPos = voteCmd.length();
answer = voteCmd.substr(startPos, endPos-startPos);
}
/* XXX answer arrays should be static const but it'll do for now */
static const unsigned int yesCount = 8;
char yesAnswers[8][5];
sprintf(yesAnswers[0], "y");
sprintf(yesAnswers[1], "1");
sprintf(yesAnswers[2], "yes");
sprintf(yesAnswers[3], "yea");
sprintf(yesAnswers[4], "si");
sprintf(yesAnswers[5], "ja");
sprintf(yesAnswers[6], "oui");
sprintf(yesAnswers[7], "sim");
static const unsigned int noCount = 7;
char noAnswers[7][5];
sprintf(noAnswers[0], "n");
sprintf(noAnswers[1], "0");
sprintf(noAnswers[2], "no");
sprintf(noAnswers[3], "nay");
sprintf(noAnswers[4], "nein");
sprintf(noAnswers[5], "non");
sprintf(noAnswers[6], "nao");
// see if the vote response is a valid yes or no answer
int vote=-1;
for (unsigned int v = 0; v < (noCount > yesCount ? noCount : yesCount); v++) {
if (v < yesCount) {
if (answer == yesAnswers[v]) {
vote = 1;
break;
}
}
if (v < noCount) {
if (answer == noAnswers[v]) {
vote = 0;
break;
}
}
}
// cast the vote or complain
bool cast = false;
if (vote == 0) {
if ((cast = arbiter->voteNo(player[t].callSign)) == true) {
/* player voted no */
sprintf(reply,"%s, your vote in opposition of the %s has been recorded", player[t].callSign, arbiter->getPollAction().c_str());
sendMessage(ServerPlayer, t, reply, true);
}
} else if (vote == 1) {
if ((cast = arbiter->voteYes(player[t].callSign)) == true) {
/* player voted yes */
sprintf(reply,"%s, your vote in favor of the %s has been recorded", player[t].callSign, arbiter->getPollAction().c_str());
sendMessage(ServerPlayer, t, reply, true);
}
} else {
if (answer.length() == 0) {
sprintf(reply,"%s, you did not provide a vote answer", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /vote yes|no|y|n|1|0|yea|nay|si|ja|nein|oui|non|sim|nao");
sendMessage(ServerPlayer, t, reply, true);
} else {
sprintf(reply,"%s, you did not vote in favor or in opposition", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /vote yes|no|y|n|1|0|yea|nay|si|ja|nein|oui|non|sim|nao");
sendMessage(ServerPlayer, t, reply, true);
}
return;
}
if (!cast) {
/* player was unable to cast their vote; probably already voted */
sprintf(reply,"%s, you have already voted on the poll to %s %s", player[t].callSign, arbiter->getPollAction().c_str(), arbiter->getPollPlayer().c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
return;
}
void handleVetoCmd(int t, const char * /*message*/)
{
char reply[MessageLen];
if (!hasPerm(t, PlayerAccessInfo::veto)) {
/* permission denied for /veto */
sprintf(reply,"%s, you are presently not authorized to run /veto", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure that there is a poll arbiter */
if (BZDB->isEmpty("poll")) {
sprintf(reply, "ERROR: the poll arbiter has disappeared (this should never happen)");
sendMessage(ServerPlayer, t, reply, true);
return;
}
// only need to do this once
static VotingArbiter *arbiter = (VotingArbiter *)BZDB->getPointer("poll");
/* make sure there is an unexpired poll */
if ((arbiter != NULL) && !arbiter->knowsPoll()) {
sprintf(reply, "%s, there is presently no active poll to veto", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* poof */
arbiter->forgetPoll();
sprintf(reply,"%s, you have cancelled the poll to %s %s", player[t].callSign, arbiter->getPollAction().c_str(), arbiter->getPollPlayer().c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"The poll was cancelled by %s", player[t].callSign);
sendMessage(ServerPlayer, AllPlayers, reply, true);
return;
}
// ex: shiftwidth=2 tabstop=8
<commit_msg>readded optional quoting, better whitespace checking, and stdified the vote strings<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _WIN32
#pragma warning( 4:4786)
#endif
// interface header
#include "commands.h"
// implementation-specific system headers
#include <string>
#include <cstdio>
#include <cstring>
// implementation-specific bzflag headers
#include "global.h"
#include "Address.h"
// implementation-specific bzfs-specific headers
#include "VotingArbiter.h"
#include "Permissions.h"
#include "CmdLineOptions.h"
#include "PlayerInfo.h"
// FIXME -- need to pull communication out of bzfs.cxx...
extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message, bool fullBuffer);
extern bool hasPerm(int playerIndex, PlayerAccessInfo::AccessPerm right);
extern PlayerInfo player[MaxPlayers];
extern CmdLineOptions *clOptions;
extern uint16_t curMaxPlayers;
extern int NotConnected;
void handlePollCmd(int t, const char *message)
{
char reply[MessageLen] = {0};
DEBUG2("Entered poll command handler (MessageLen is %d)\n", MessageLen);
/* make sure player has permission to request a poll */
if (!hasPerm(t, PlayerAccessInfo::poll)) {
sprintf(reply,"%s, you are presently not authorized to run /poll", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
DEBUG2("Player has permission\n");
/* make sure that there is a poll arbiter */
if (BZDB->isEmpty("poll")) {
sprintf(reply, "ERROR: the poll arbiter has disappeared (this should never happen)");
sendMessage(ServerPlayer, t, reply, true);
return;
}
DEBUG2("BZDB poll value is not empty\n");
// only need to do this once
static VotingArbiter *arbiter = (VotingArbiter *)BZDB->getPointer("poll");
DEBUG2("Arbiter was acquired with address 0x%x\n", (unsigned int)arbiter);
/* make sure that there is not a poll active already */
if (arbiter->knowsPoll()) {
sprintf(reply,"A poll to %s %s is presently in progress", arbiter->getPollAction().c_str(), arbiter->getPollPlayer().c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Unable to start a new poll until the current one is over");
sendMessage(ServerPlayer, t, reply, true);
return;
}
DEBUG2("The arbiter says there is not another poll active\n");
// get available voter count
unsigned short int available = 0;
for (int i=0; i < curMaxPlayers; i++) {
// anyone on the server (even observers) are eligible to vote
if (player[i].fd != NotConnected) {
available++;
}
}
DEBUG2("There are %d available players for %d votes required\n", available, clOptions->votesRequired);
/* make sure there are enough players to even make a poll that has a chance
* of succeeding (not counting the person being acted upon)
*/
if (available - 1 < clOptions->votesRequired) {
sprintf(reply,"Unable to initiate a new poll. There are not enough players.");
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"There needs to be at least %d other %s and only %d %s available.",
clOptions->votesRequired,
clOptions->votesRequired - 1 == 1 ? "player" : "players",
available - 1,
available - 1 == 1 ? "is" : "are");
sendMessage(ServerPlayer, t, reply, true);
return;
}
std::string arguments = &message[5];
std::string cmd = "";
DEBUG2("The arguments string is [%s]\n", arguments.c_str());
/* find the start of the command */
size_t startPosition = 0;
while ((startPosition < arguments.size()) &&
(isWhitespace(arguments[startPosition]))) {
startPosition++;
}
DEBUG2("Start position is %d\n", (int)startPosition);
/* find the end of the command */
size_t endPosition = startPosition + 1;
while ((endPosition < arguments.size()) &&
(!isWhitespace(arguments[endPosition]))) {
endPosition++;
}
DEBUG2("End position is %d\n", (int)endPosition);
/* stash the command ('kick', etc) in lowercase to simplify comparison */
if ((startPosition != arguments.size()) &&
(endPosition > startPosition)) {
for (size_t i = startPosition; i < endPosition; i++) {
cmd += tolower(arguments[i]);
}
}
DEBUG2("Command is %s\n", cmd.c_str());
/* handle subcommands */
if ((cmd == "ban") || (cmd == "kick")) {
std::string nick;
arguments = arguments.substr(endPosition);
DEBUG2("Command arguments rguments is [%s]\n", arguments.c_str());
/* find the start of the player name */
startPosition = 0;
while ((startPosition < arguments.size()) &&
(isWhitespace(arguments[startPosition]))) {
startPosition++;
}
// do not include a starting quote, if given
if ( arguments[startPosition] == '"' ) {
startPosition++;
}
DEBUG2("Start position for player name is %d\n", (int)startPosition);
/* find the end of the player name */
endPosition = arguments.size() - 1;
while ((endPosition > 0) &&
(isWhitespace(arguments[endPosition]))) {
endPosition--;
}
// do not include a trailing quote, if given
if ( arguments[endPosition] == '"' ) {
endPosition--;
}
DEBUG2("End position for player name is %d\n", (int)endPosition);
nick = arguments.substr(startPosition, endPosition - startPosition + 1);
DEBUG2("Player specified to vote upon is [%s]\n", nick.c_str());
if (nick.length() == 0) {
sprintf(reply,"%s, no player was specified for the [%s] vote", player[t].callSign, cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /poll %s playername", cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure the requested player is actually here */
bool foundPlayer=false;
std::string playerIP = "";
for (int v = 0; v < curMaxPlayers; v++) {
if (strncasecmp(nick.c_str(), player[v].callSign, 256) == 0) {
playerIP = player[v].peer.getDotNotation().c_str();
foundPlayer=true;
break;
}
}
if (!foundPlayer) {
/* wrong name? */
sprintf(reply, "The player specified for a %s vote is not here", cmd.c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* create and announce the new poll */
if (cmd == "ban") {
if (arbiter->pollToBan(nick.c_str(), player[t].callSign, playerIP) == false) {
sprintf(reply,"You are not able to request a ban poll right now, %s", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
} else {
sprintf(reply,"A poll to temporarily ban %s has been requested by %s", nick.c_str(), player[t].callSign);
sendMessage(ServerPlayer, AllPlayers, reply, true);
}
} else {
if (arbiter->pollToKick(nick.c_str(), player[t].callSign) == false) {
sprintf(reply,"You are not able to request a kick poll right now, %s", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
} else {
sprintf(reply,"A poll to %s %s has been requested by %s", cmd.c_str(), nick.c_str(), player[t].callSign);
sendMessage(ServerPlayer, AllPlayers, reply, true);
}
}
// set the number of available voters
arbiter->setAvailableVoters(available);
// keep track of who is allowed to vote
for (int j=0; j < curMaxPlayers; j++) {
// anyone on the server (even observers) are eligible to vote
if (player[j].fd != NotConnected) {
arbiter->grantSuffrage(player[j].callSign);
}
}
// automatically place a vote for the player requesting the poll
arbiter->voteYes(player[t].callSign);
} else if (cmd == "vote") {
if (!hasPerm(t, PlayerAccessInfo::vote)) {
sprintf(reply,"%s, you do not presently have permission to vote (must /identify first)", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* !!! needs to be handled by the /vote command */
sprintf(reply,"%s, your vote has been recorded -- unimplemented", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else if (cmd == "veto") {
if (!hasPerm(t, PlayerAccessInfo::veto)) {
sprintf(reply,"%s, you do not have permission to veto the poll", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
}
/* !!! needs to be handled by the /veto command */
sprintf(reply,"%s, you have aborted the poll -- unimplemented", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else {
sprintf(reply,"Invalid option to the poll command");
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"Usage: /poll ban|kick playername");
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply," or /poll vote yes|no");
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply," or /poll veto");
sendMessage(ServerPlayer, t, reply, true);
} /* end handling of poll subcommands */
return;
}
void handleVoteCmd(int t, const char *message)
{
char reply[MessageLen] = {0};
if (!hasPerm(t, PlayerAccessInfo::vote)) {
/* permission denied for /vote */
sprintf(reply,"%s, you are presently not authorized to run /vote", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure that there is a poll arbiter */
if (BZDB->isEmpty("poll")) {
sprintf(reply, "ERROR: the poll arbiter has disappeared (this should never happen)");
sendMessage(ServerPlayer, t, reply, true);
return;
}
// only need to get this once
static VotingArbiter *arbiter = (VotingArbiter *)BZDB->getPointer("poll");
/* make sure that there is a poll to vote upon */
if ((arbiter != NULL) && !arbiter->knowsPoll()) {
sprintf(reply,"A poll is not presently in progress. There is nothing to vote on");
sendMessage(ServerPlayer, t, reply, true);
return;
}
std::string voteCmd = &message[5];
std::string answer;
/* find the start of the vote answer */
size_t startPosition = 0;
while ((startPosition < voteCmd.size()) &&
(isWhitespace(voteCmd[startPosition]))) {
startPosition++;
}
/* stash the answer ('yes', 'no', etc) in lowercase to simplify comparison */
for (size_t i = startPosition; i < voteCmd.size() && !isWhitespace(voteCmd[i]); i++) {
answer += tolower(voteCmd[i]);
}
std::vector<std::string> yesAnswers;
yesAnswers.push_back("y");
yesAnswers.push_back("1");
yesAnswers.push_back("yes");
yesAnswers.push_back("yea");
yesAnswers.push_back("si");
yesAnswers.push_back("ja");
yesAnswers.push_back("oui");
yesAnswers.push_back("sim");
std::vector<std::string> noAnswers;
noAnswers.push_back("n");
noAnswers.push_back("0");
noAnswers.push_back("no");
noAnswers.push_back("nay");
noAnswers.push_back("nein");
noAnswers.push_back("non");
noAnswers.push_back("nao");
// see if the vote response is a valid yes or no answer
int vote=-1;
unsigned int maxAnswerCount = noAnswers.size() > yesAnswers.size() ? noAnswers.size() : yesAnswers.size();
for (unsigned int v = 0; v < maxAnswerCount; v++) {
if (v < yesAnswers.size()) {
if (answer == yesAnswers[v]) {
vote = 1;
break;
}
}
if (v < noAnswers.size()) {
if (answer == noAnswers[v]) {
vote = 0;
break;
}
}
}
// cast the vote or complain
bool cast = false;
if (vote == 0) {
if ((cast = arbiter->voteNo(player[t].callSign)) == true) {
/* player voted no */
sprintf(reply,"%s, your vote in opposition of the %s has been recorded", player[t].callSign, arbiter->getPollAction().c_str());
sendMessage(ServerPlayer, t, reply, true);
}
} else if (vote == 1) {
if ((cast = arbiter->voteYes(player[t].callSign)) == true) {
/* player voted yes */
sprintf(reply,"%s, your vote in favor of the %s has been recorded", player[t].callSign, arbiter->getPollAction().c_str());
sendMessage(ServerPlayer, t, reply, true);
}
} else {
if (answer.length() == 0) {
sprintf(reply,"%s, you did not provide a vote answer", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
} else {
sprintf(reply,"%s, you did not vote in favor or in opposition", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
}
sprintf(reply,"Usage: /vote yes|no|y|n|1|0|yea|nay|si|ja|nein|oui|non|sim|nao");
sendMessage(ServerPlayer, t, reply, true);
return;
}
if (!cast) {
/* player was unable to cast their vote; probably already voted */
sprintf(reply,"%s, you have already voted on the poll to %s %s", player[t].callSign, arbiter->getPollAction().c_str(), arbiter->getPollPlayer().c_str());
sendMessage(ServerPlayer, t, reply, true);
return;
}
return;
}
void handleVetoCmd(int t, const char * /*message*/)
{
char reply[MessageLen] = {0};
if (!hasPerm(t, PlayerAccessInfo::veto)) {
/* permission denied for /veto */
sprintf(reply,"%s, you are presently not authorized to run /veto", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* make sure that there is a poll arbiter */
if (BZDB->isEmpty("poll")) {
sprintf(reply, "ERROR: the poll arbiter has disappeared (this should never happen)");
sendMessage(ServerPlayer, t, reply, true);
return;
}
// only need to do this once
static VotingArbiter *arbiter = (VotingArbiter *)BZDB->getPointer("poll");
/* make sure there is an unexpired poll */
if ((arbiter != NULL) && !arbiter->knowsPoll()) {
sprintf(reply, "%s, there is presently no active poll to veto", player[t].callSign);
sendMessage(ServerPlayer, t, reply, true);
return;
}
/* poof */
arbiter->forgetPoll();
sprintf(reply,"%s, you have cancelled the poll to %s %s", player[t].callSign, arbiter->getPollAction().c_str(), arbiter->getPollPlayer().c_str());
sendMessage(ServerPlayer, t, reply, true);
sprintf(reply,"The poll was cancelled by %s", player[t].callSign);
sendMessage(ServerPlayer, AllPlayers, reply, true);
return;
}
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
// handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
// velocity
if (m_pStates[STATE_RUN]) impulse *= m_fMaxVelocity;
else impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
// clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
if (GetCollision())
{
// get collision
vec3 tangent, binormal;
const Vec3 *caps = m_pShape->GetCaps();
for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++)
{
m_pDummy->SetTransform(Get_Body_Transform());
m_pShape->GetCollision(m_vecContacts, 0.0f);
if (m_vecContacts.Size() == 0) break;
float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size());
for (int j = 0; j < m_vecContacts.Size(); j++)
{
const CShape::Contact &c = m_vecContacts[j];
vec3 normalCollision = c.normal;
if (is_frozen && c.depth < penetration_2)
{
m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision)));
}
else
{
m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts));
is_frozen = 0;
}
float normal_velocity = Dot(normalCollision, m_vVelocity);
if (normal_velocity < 0.0f)
{
m_vVelocity -= normalCollision * normal_velocity;
}
if (friction > EPSILON)
{
OrthoBasis(c.normal, tangent, binormal);
float tangent_velocity = Dot(tangent, m_vVelocity);
float binormal_velocity = Dot(binormal, m_vVelocity);
if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON)
{
}
}
}
}
}
}
}<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
// handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
// velocity
if (m_pStates[STATE_RUN]) impulse *= m_fMaxVelocity;
else impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
// clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
if (GetCollision())
{
// get collision
vec3 tangent, binormal;
const Vec3 *caps = m_pShape->GetCaps();
for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++)
{
m_pDummy->SetTransform(Get_Body_Transform());
m_pShape->GetCollision(m_vecContacts, 0.0f);
if (m_vecContacts.Size() == 0) break;
float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size());
for (int j = 0; j < m_vecContacts.Size(); j++)
{
const CShape::Contact &c = m_vecContacts[j];
vec3 normalCollision = c.normal;
if (is_frozen && c.depth < penetration_2)
{
m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision)));
}
else
{
m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts));
is_frozen = 0;
}
float normal_velocity = Dot(normalCollision, m_vVelocity);
if (normal_velocity < 0.0f)
{
m_vVelocity -= normalCollision * normal_velocity;
}
if (friction > EPSILON)
{
OrthoBasis(c.normal, tangent, binormal);
float tangent_velocity = Dot(tangent, m_vVelocity);
float binormal_velocity = Dot(binormal, m_vVelocity);
if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON)
{
float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f);
m_vVelocity -= tangent * tangent_velocity * friction_velocity;
m_vVelocity -= binormal * binormal_velocity * friction_velocity;
}
}
}
}
}
}
}<|endoftext|> |
<commit_before>#pragma once
#include "TimingTags.hpp"
#include "timing_graph_fwd.hpp"
#include "tatum_linear_map.hpp"
namespace tatum { namespace detail {
/** \class CommonAnalysisOps
*
* The operations for CommonAnalysisVisitor to perform setup analysis.
* The setup analysis operations define that maximum edge delays are used, and that the
* maixmum arrival time (and minimum required times) are propagated through the timing graph.
*
* \see HoldAnalysisOps
* \see CommonAnalysisVisitor
*/
class CommonAnalysisOps {
public:
CommonAnalysisOps(size_t num_tags)
: data_tags_(num_tags, NUM_DATA_TAGS_RESERVE)
, clock_launch_tags_(num_tags, NUM_CLK_TAGS_RESERVE)
, clock_capture_tags_(num_tags, NUM_CLK_TAGS_RESERVE) {}
TimingTags& get_data_tags(const NodeId node_id) { return data_tags_[node_id]; }
TimingTags& get_launch_clock_tags(const NodeId node_id) { return clock_launch_tags_[node_id]; }
TimingTags& get_capture_clock_tags(const NodeId node_id) { return clock_capture_tags_[node_id]; }
const TimingTags& get_data_tags(const NodeId node_id) const { return data_tags_[node_id]; }
const TimingTags& get_launch_clock_tags(const NodeId node_id) const { return clock_launch_tags_[node_id]; }
const TimingTags& get_capture_clock_tags(const NodeId node_id) const { return clock_capture_tags_[node_id]; }
void reset() {
data_tags_.clear();
clock_launch_tags_.clear();
clock_capture_tags_.clear();
}
private:
constexpr static size_t NUM_DATA_TAGS_RESERVE = 1;
constexpr static size_t NUM_CLK_TAGS_RESERVE = 0;
tatum::util::linear_map<NodeId,TimingTags> data_tags_;
tatum::util::linear_map<NodeId,TimingTags> clock_launch_tags_;
tatum::util::linear_map<NodeId,TimingTags> clock_capture_tags_;
};
}} //namespace
<commit_msg>Fix reseting bug<commit_after>#pragma once
#include "TimingTags.hpp"
#include "timing_graph_fwd.hpp"
#include "tatum_linear_map.hpp"
namespace tatum { namespace detail {
/** \class CommonAnalysisOps
*
* The operations for CommonAnalysisVisitor to perform setup analysis.
* The setup analysis operations define that maximum edge delays are used, and that the
* maixmum arrival time (and minimum required times) are propagated through the timing graph.
*
* \see HoldAnalysisOps
* \see CommonAnalysisVisitor
*/
class CommonAnalysisOps {
public:
CommonAnalysisOps(size_t num_tags)
: data_tags_(num_tags, NUM_DATA_TAGS_RESERVE)
, clock_launch_tags_(num_tags, NUM_CLOCK_TAGS_RESERVE)
, clock_capture_tags_(num_tags, NUM_CLOCK_TAGS_RESERVE) {}
TimingTags& get_data_tags(const NodeId node_id) { return data_tags_[node_id]; }
TimingTags& get_launch_clock_tags(const NodeId node_id) { return clock_launch_tags_[node_id]; }
TimingTags& get_capture_clock_tags(const NodeId node_id) { return clock_capture_tags_[node_id]; }
const TimingTags& get_data_tags(const NodeId node_id) const { return data_tags_[node_id]; }
const TimingTags& get_launch_clock_tags(const NodeId node_id) const { return clock_launch_tags_[node_id]; }
const TimingTags& get_capture_clock_tags(const NodeId node_id) const { return clock_capture_tags_[node_id]; }
void reset() {
data_tags_ = tatum::util::linear_map<NodeId,TimingTags>(data_tags_.size(), NUM_DATA_TAGS_RESERVE);
clock_launch_tags_ = tatum::util::linear_map<NodeId,TimingTags>(clock_launch_tags_.size(), NUM_CLOCK_TAGS_RESERVE);
clock_capture_tags_ = tatum::util::linear_map<NodeId,TimingTags>(clock_capture_tags_.size(), NUM_CLOCK_TAGS_RESERVE);
}
private:
constexpr static size_t NUM_DATA_TAGS_RESERVE = 1;
constexpr static size_t NUM_CLOCK_TAGS_RESERVE = 0;
tatum::util::linear_map<NodeId,TimingTags> data_tags_;
tatum::util::linear_map<NodeId,TimingTags> clock_launch_tags_;
tatum::util::linear_map<NodeId,TimingTags> clock_capture_tags_;
};
}} //namespace
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm> // for std::fill
#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
#include <cmath> // for sqrt
// Local Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/error_vector.h"
#include "libmesh/fe_base.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/elem.h"
#include "libmesh/system.h"
#include "libmesh/dense_vector.h"
#include "libmesh/tensor_tools.h"
namespace libMesh
{
void
KellyErrorEstimator::initialize(const System& system,
ErrorVector&,
bool)
{
// Hang onto the system - we may need it for variable names later.
my_system = &system;
// We'll need gradients and normal vectors for flux jump computation
fe_fine->get_dphi();
fe_fine->get_normals();
fe_coarse->get_dphi();
}
void
KellyErrorEstimator::internal_side_integration ()
{
Real error = 1.e-30;
unsigned int n_qp = fe_fine->n_quadrature_points();
unsigned int n_fine_dofs = Ufine.size();
unsigned int n_coarse_dofs = Ucoarse.size();
std::vector<std::vector<RealGradient> > dphi_coarse = fe_coarse->get_dphi();
std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
std::vector<Point> face_normals = fe_fine->get_normals();
std::vector<Real> JxW_face = fe_fine->get_JxW();
for (unsigned int qp=0; qp != n_qp; ++qp)
{
// Calculate solution gradients on fine and coarse elements
// at this quadrature point
Gradient grad_fine, grad_coarse;
for (unsigned int i=0; i != n_coarse_dofs; ++i)
grad_coarse.add_scaled (dphi_coarse[i][qp], Ucoarse(i));
for (unsigned int i=0; i != n_fine_dofs; ++i)
grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));
// Find the jump in the normal derivative
// at this quadrature point
const Number jump = (grad_fine - grad_coarse)*face_normals[qp];
const Real jump2 = TensorTools::norm_sq(jump);
// Accumulate the jump integral
error += JxW_face[qp] * jump2;
}
// Add the h-weighted jump integral to each error term
fine_error =
error * fine_elem->hmax() * error_norm.weight(var);
coarse_error =
error * coarse_elem->hmax() * error_norm.weight(var);
}
bool
KellyErrorEstimator::boundary_side_integration ()
{
const std::string &var_name = my_system->variable_name(var);
std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
std::vector<Point> face_normals = fe_fine->get_normals();
std::vector<Real> JxW_face = fe_fine->get_JxW();
std::vector<Point> qface_point = fe_fine->get_xyz();
// The reinitialization also recomputes the locations of
// the quadrature points on the side. By checking if the
// first quadrature point on the side is on a flux boundary
// for a particular variable, we will determine if the whole
// element is on a flux boundary (assuming quadrature points
// are strictly contained in the side).
if (this->_bc_function(*my_system, qface_point[0], var_name).first)
{
const Real h = fine_elem->hmax();
// The number of quadrature points
const unsigned int n_qp = fe_fine->n_quadrature_points();
// The error contribution from this face
Real error = 1.e-30;
// loop over the integration points on the face.
for (unsigned int qp=0; qp<n_qp; qp++)
{
// Value of the imposed flux BC at this quadrature point.
const std::pair<bool,Real> flux_bc =
this->_bc_function(*my_system, qface_point[qp], var_name);
// Be sure the BC function still thinks we're on the
// flux boundary.
libmesh_assert_equal_to (flux_bc.first, true);
// The solution gradient from each element
Gradient grad_fine;
// Compute the solution gradient on element e
for (unsigned int i=0; i != Ufine.size(); i++)
grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));
// The difference between the desired BC and the approximate solution.
const Number jump = flux_bc.second - grad_fine*face_normals[qp];
// The flux jump squared. If using complex numbers,
// TensorTools::norm_sq(z) returns |z|^2, where |z| is the modulus of z.
const Real jump2 = TensorTools::norm_sq(jump);
// Integrate the error on the face. The error is
// scaled by an additional power of h, where h is
// the maximum side length for the element. This
// arises in the definition of the indicator.
error += JxW_face[qp]*jump2;
} // End quadrature point loop
fine_error = error*h*error_norm.weight(var);
return true;
} // end if side on flux boundary
return false;
}
void
KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System& system,
const Point& p,
const std::string& var_name))
{
_bc_function = fptr;
// We may be turning boundary side integration on or off
if (fptr)
integrate_boundary_sides = true;
else
integrate_boundary_sides = false;
}
} // namespace libMesh
<commit_msg>Trivial change to save intel-12.0 from itself.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm> // for std::fill
#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
#include <cmath> // for sqrt
// Local Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/error_vector.h"
#include "libmesh/fe_base.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/elem.h"
#include "libmesh/system.h"
#include "libmesh/dense_vector.h"
#include "libmesh/tensor_tools.h"
namespace libMesh
{
void
KellyErrorEstimator::initialize(const System& system,
ErrorVector&,
bool)
{
// Hang onto the system - we may need it for variable names later.
my_system = &system;
// We'll need gradients and normal vectors for flux jump computation
fe_fine->get_dphi();
fe_fine->get_normals();
fe_coarse->get_dphi();
}
void
KellyErrorEstimator::internal_side_integration ()
{
Real error = 1.e-30;
unsigned int n_qp = fe_fine->n_quadrature_points();
unsigned int n_fine_dofs = Ufine.size();
unsigned int n_coarse_dofs = Ucoarse.size();
std::vector<std::vector<RealGradient> > dphi_coarse = fe_coarse->get_dphi();
std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
std::vector<Point> face_normals = fe_fine->get_normals();
std::vector<Real> JxW_face = fe_fine->get_JxW();
for (unsigned int qp=0; qp != n_qp; ++qp)
{
// Calculate solution gradients on fine and coarse elements
// at this quadrature point
Gradient grad_fine, grad_coarse;
for (unsigned int i=0; i != n_coarse_dofs; ++i)
grad_coarse.add_scaled (dphi_coarse[i][qp], Ucoarse(i));
for (unsigned int i=0; i != n_fine_dofs; ++i)
grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));
// Find the jump in the normal derivative
// at this quadrature point
const Number jump = (grad_fine - grad_coarse)*face_normals[qp];
const Real jump2 = TensorTools::norm_sq(jump);
// Accumulate the jump integral
error += JxW_face[qp] * jump2;
}
// Add the h-weighted jump integral to each error term
fine_error =
error * fine_elem->hmax() * error_norm.weight(var);
coarse_error =
error * coarse_elem->hmax() * error_norm.weight(var);
}
bool
KellyErrorEstimator::boundary_side_integration ()
{
const std::string &var_name = my_system->variable_name(var);
const unsigned int n_fine_dofs = Ufine.size();
std::vector<std::vector<RealGradient> > dphi_fine = fe_fine->get_dphi();
std::vector<Point> face_normals = fe_fine->get_normals();
std::vector<Real> JxW_face = fe_fine->get_JxW();
std::vector<Point> qface_point = fe_fine->get_xyz();
// The reinitialization also recomputes the locations of
// the quadrature points on the side. By checking if the
// first quadrature point on the side is on a flux boundary
// for a particular variable, we will determine if the whole
// element is on a flux boundary (assuming quadrature points
// are strictly contained in the side).
if (this->_bc_function(*my_system, qface_point[0], var_name).first)
{
const Real h = fine_elem->hmax();
// The number of quadrature points
const unsigned int n_qp = fe_fine->n_quadrature_points();
// The error contribution from this face
Real error = 1.e-30;
// loop over the integration points on the face.
for (unsigned int qp=0; qp<n_qp; qp++)
{
// Value of the imposed flux BC at this quadrature point.
const std::pair<bool,Real> flux_bc =
this->_bc_function(*my_system, qface_point[qp], var_name);
// Be sure the BC function still thinks we're on the
// flux boundary.
libmesh_assert_equal_to (flux_bc.first, true);
// The solution gradient from each element
Gradient grad_fine;
// Compute the solution gradient on element e
for (unsigned int i=0; i != n_fine_dofs; i++)
grad_fine.add_scaled (dphi_fine[i][qp], Ufine(i));
// The difference between the desired BC and the approximate solution.
const Number jump = flux_bc.second - grad_fine*face_normals[qp];
// The flux jump squared. If using complex numbers,
// TensorTools::norm_sq(z) returns |z|^2, where |z| is the modulus of z.
const Real jump2 = TensorTools::norm_sq(jump);
// Integrate the error on the face. The error is
// scaled by an additional power of h, where h is
// the maximum side length for the element. This
// arises in the definition of the indicator.
error += JxW_face[qp]*jump2;
} // End quadrature point loop
fine_error = error*h*error_norm.weight(var);
return true;
} // end if side on flux boundary
return false;
}
void
KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System& system,
const Point& p,
const std::string& var_name))
{
_bc_function = fptr;
// We may be turning boundary side integration on or off
if (fptr)
integrate_boundary_sides = true;
else
integrate_boundary_sides = false;
}
} // namespace libMesh
<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
}<|endoftext|> |
<commit_before>//===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
//
// This library implements the functionality defined in llvm/Assembly/Writer.h
//
// This library uses the Analysis library to figure out offsets for
// variables in the method tables...
//
// TODO: print out the type name instead of the full type if a particular type
// is in the symbol table...
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/SlotCalculator.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/iOther.h"
#include "llvm/iMemory.h"
class AssemblyWriter : public ModuleAnalyzer {
ostream &Out;
SlotCalculator &Table;
public:
inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
}
inline void write(const Module *M) { processModule(M); }
inline void write(const Method *M) { processMethod(M); }
inline void write(const BasicBlock *BB) { processBasicBlock(BB); }
inline void write(const Instruction *I) { processInstruction(I); }
inline void write(const ConstPoolVal *CPV) { processConstant(CPV); }
protected:
virtual bool visitMethod(const Method *M);
virtual bool processConstPool(const ConstantPool &CP, bool isMethod);
virtual bool processConstant(const ConstPoolVal *CPV);
virtual bool processMethod(const Method *M);
virtual bool processMethodArgument(const MethodArgument *MA);
virtual bool processBasicBlock(const BasicBlock *BB);
virtual bool processInstruction(const Instruction *I);
private :
void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
};
// visitMethod - This member is called after the above two steps, visting each
// method, because they are effectively values that go into the constant pool.
//
bool AssemblyWriter::visitMethod(const Method *M) {
return false;
}
bool AssemblyWriter::processConstPool(const ConstantPool &CP, bool isMethod) {
// Done printing arguments...
if (isMethod) Out << ")\n";
ModuleAnalyzer::processConstPool(CP, isMethod);
if (isMethod)
Out << "begin";
else
Out << "implementation\n";
return false;
}
// processConstant - Print out a constant pool entry...
//
bool AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
Out << "\t";
// Print out name if it exists...
if (CPV->hasName())
Out << "%" << CPV->getName() << " = ";
// Print out the opcode...
Out << CPV->getType();
// Write the value out now...
writeOperand(CPV, false, false);
if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
Out << "\t\t; <" << CPV->getType() << ">:";
if (Slot >= 0) Out << Slot;
else Out << "<badref>";
}
Out << endl;
return false;
}
// processMethod - Process all aspects of a method.
//
bool AssemblyWriter::processMethod(const Method *M) {
// Print out the return type and name...
Out << "\n" << M->getReturnType() << " \"" << M->getName() << "\"(";
Table.incorporateMethod(M);
ModuleAnalyzer::processMethod(M);
Table.purgeMethod();
Out << "end\n";
return false;
}
// processMethodArgument - This member is called for every argument that
// is passed into the method. Simply print it out
//
bool AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
// Insert commas as we go... the first arg doesn't get a comma
if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
// Output type...
Out << Arg->getType();
// Output name, if available...
if (Arg->hasName())
Out << " %" << Arg->getName();
else if (Table.getValSlot(Arg) < 0)
Out << "<badref>";
return false;
}
// processBasicBlock - This member is called for each basic block in a methd.
//
bool AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n" << BB->getName() << ":";
} else {
int Slot = Table.getValSlot(BB);
Out << "\n; <label>:";
if (Slot >= 0)
Out << Slot; // Extra newline seperates out label's
else
Out << "<badref>";
}
Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
ModuleAnalyzer::processBasicBlock(BB);
return false;
}
// processInstruction - This member is called for each Instruction in a methd.
//
bool AssemblyWriter::processInstruction(const Instruction *I) {
Out << "\t";
// Print out name if it exists...
if (I && I->hasName())
Out << "%" << I->getName() << " = ";
// Print out the opcode...
Out << I->getOpcode();
// Print out the type of the operands...
const Value *Operand = I->getOperand(0);
// Special case conditional branches to swizzle the condition out to the front
if (I->getInstType() == Instruction::Br && I->getOperand(1)) {
writeOperand(I->getOperand(2), true);
Out << ",";
writeOperand(Operand, true);
Out << ",";
writeOperand(I->getOperand(1), true);
} else if (I->getInstType() == Instruction::Switch) {
// Special case switch statement to get formatting nice and correct...
writeOperand(Operand , true); Out << ",";
writeOperand(I->getOperand(1), true); Out << " [";
for (unsigned op = 2; (Operand = I->getOperand(op)); op += 2) {
Out << "\n\t\t";
writeOperand(Operand, true); Out << ",";
writeOperand(I->getOperand(op+1), true);
}
Out << "\n\t]";
} else if (I->getInstType() == Instruction::PHINode) {
Out << " " << Operand->getType();
Out << " ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(1), false); Out << "]";
for (unsigned op = 2; (Operand = I->getOperand(op)); op += 2) {
Out << ", ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(op+1), false); Out << "]";
}
} else if (I->getInstType() == Instruction::Ret && !Operand) {
Out << " void";
} else if (I->getInstType() == Instruction::Call) {
writeOperand(Operand, true);
Out << "(";
Operand = I->getOperand(1);
if (Operand) writeOperand(Operand, true);
for (unsigned op = 2; (Operand = I->getOperand(op)); ++op) {
Out << ",";
writeOperand(Operand, true);
}
Out << " )";
} else if (I->getInstType() == Instruction::Malloc ||
I->getInstType() == Instruction::Alloca) {
Out << " " << ((const PointerType*)((ConstPoolType*)Operand)
->getValue())->getValueType();
if ((Operand = I->getOperand(1))) {
Out << ","; writeOperand(Operand, true);
}
} else if (Operand) { // Print the normal way...
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
const Type *TheType = Operand->getType();
unsigned i;
for (i = 1; (Operand = I->getOperand(i)); i++) {
if (Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
if (!PrintAllTypes)
Out << " " << I->getOperand(0)->getType();
for (unsigned i = 0; (Operand = I->getOperand(i)); i++) {
if (i) Out << ",";
writeOperand(Operand, PrintAllTypes);
}
}
// Print a little comment after the instruction indicating which slot it
// occupies.
//
if (I->getType() != Type::VoidTy) {
Out << "\t\t; <" << I->getType() << ">";
if (!I->hasName()) {
int Slot = Table.getValSlot(I); // Print out the def slot taken...
if (Slot >= 0) Out << ":" << Slot;
else Out << ":<badref>";
}
Out << "\t[#uses=" << I->use_size() << "]"; // Output # uses
}
Out << endl;
return false;
}
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
bool PrintName) {
if (PrintType)
Out << " " << Operand->getType();
if (Operand->hasName() && PrintName) {
Out << " %" << Operand->getName();
} else {
int Slot = Table.getValSlot(Operand);
if (Operand->getValueType() == Value::ConstantVal) {
Out << " " << ((ConstPoolVal*)Operand)->getStrValue();
} else {
if (Slot >= 0) Out << " %" << Slot;
else if (PrintName)
Out << "<badref>"; // Not embeded into a location?
}
}
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void WriteToAssembly(const Module *M, ostream &o) {
if (M == 0) { o << "<null> module\n"; return; }
SlotCalculator SlotTable(M, true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const Method *M, ostream &o) {
if (M == 0) { o << "<null> method\n"; return; }
SlotCalculator SlotTable(M->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const BasicBlock *BB, ostream &o) {
if (BB == 0) { o << "<null> basic block\n"; return; }
SlotCalculator SlotTable(BB->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(BB);
}
void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
if (CPV == 0) { o << "<null> constant pool value\n"; return; }
SlotCalculator *SlotTable;
// A Constant pool value may have a parent that is either a method or a
// module. Untangle this now...
//
if (CPV->getParent() == 0 ||
CPV->getParent()->getValueType() == Value::MethodVal) {
SlotTable = new SlotCalculator((Method*)CPV->getParent(), true);
} else {
assert(CPV->getParent()->getValueType() == Value::ModuleVal);
SlotTable = new SlotCalculator((Module*)CPV->getParent(), true);
}
AssemblyWriter W(o, *SlotTable);
W.write(CPV);
delete SlotTable;
}
void WriteToAssembly(const Instruction *I, ostream &o) {
if (I == 0) { o << "<null> instruction\n"; return; }
SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0,
true);
AssemblyWriter W(o, SlotTable);
W.write(I);
}
<commit_msg>Add a space to the PHI node output code to make it look nicer<commit_after>//===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
//
// This library implements the functionality defined in llvm/Assembly/Writer.h
//
// This library uses the Analysis library to figure out offsets for
// variables in the method tables...
//
// TODO: print out the type name instead of the full type if a particular type
// is in the symbol table...
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/SlotCalculator.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/iOther.h"
#include "llvm/iMemory.h"
class AssemblyWriter : public ModuleAnalyzer {
ostream &Out;
SlotCalculator &Table;
public:
inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
}
inline void write(const Module *M) { processModule(M); }
inline void write(const Method *M) { processMethod(M); }
inline void write(const BasicBlock *BB) { processBasicBlock(BB); }
inline void write(const Instruction *I) { processInstruction(I); }
inline void write(const ConstPoolVal *CPV) { processConstant(CPV); }
protected:
virtual bool visitMethod(const Method *M);
virtual bool processConstPool(const ConstantPool &CP, bool isMethod);
virtual bool processConstant(const ConstPoolVal *CPV);
virtual bool processMethod(const Method *M);
virtual bool processMethodArgument(const MethodArgument *MA);
virtual bool processBasicBlock(const BasicBlock *BB);
virtual bool processInstruction(const Instruction *I);
private :
void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
};
// visitMethod - This member is called after the above two steps, visting each
// method, because they are effectively values that go into the constant pool.
//
bool AssemblyWriter::visitMethod(const Method *M) {
return false;
}
bool AssemblyWriter::processConstPool(const ConstantPool &CP, bool isMethod) {
// Done printing arguments...
if (isMethod) Out << ")\n";
ModuleAnalyzer::processConstPool(CP, isMethod);
if (isMethod)
Out << "begin";
else
Out << "implementation\n";
return false;
}
// processConstant - Print out a constant pool entry...
//
bool AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
Out << "\t";
// Print out name if it exists...
if (CPV->hasName())
Out << "%" << CPV->getName() << " = ";
// Print out the opcode...
Out << CPV->getType();
// Write the value out now...
writeOperand(CPV, false, false);
if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
Out << "\t\t; <" << CPV->getType() << ">:";
if (Slot >= 0) Out << Slot;
else Out << "<badref>";
}
Out << endl;
return false;
}
// processMethod - Process all aspects of a method.
//
bool AssemblyWriter::processMethod(const Method *M) {
// Print out the return type and name...
Out << "\n" << M->getReturnType() << " \"" << M->getName() << "\"(";
Table.incorporateMethod(M);
ModuleAnalyzer::processMethod(M);
Table.purgeMethod();
Out << "end\n";
return false;
}
// processMethodArgument - This member is called for every argument that
// is passed into the method. Simply print it out
//
bool AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
// Insert commas as we go... the first arg doesn't get a comma
if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
// Output type...
Out << Arg->getType();
// Output name, if available...
if (Arg->hasName())
Out << " %" << Arg->getName();
else if (Table.getValSlot(Arg) < 0)
Out << "<badref>";
return false;
}
// processBasicBlock - This member is called for each basic block in a methd.
//
bool AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n" << BB->getName() << ":";
} else {
int Slot = Table.getValSlot(BB);
Out << "\n; <label>:";
if (Slot >= 0)
Out << Slot; // Extra newline seperates out label's
else
Out << "<badref>";
}
Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
ModuleAnalyzer::processBasicBlock(BB);
return false;
}
// processInstruction - This member is called for each Instruction in a methd.
//
bool AssemblyWriter::processInstruction(const Instruction *I) {
Out << "\t";
// Print out name if it exists...
if (I && I->hasName())
Out << "%" << I->getName() << " = ";
// Print out the opcode...
Out << I->getOpcode();
// Print out the type of the operands...
const Value *Operand = I->getOperand(0);
// Special case conditional branches to swizzle the condition out to the front
if (I->getInstType() == Instruction::Br && I->getOperand(1)) {
writeOperand(I->getOperand(2), true);
Out << ",";
writeOperand(Operand, true);
Out << ",";
writeOperand(I->getOperand(1), true);
} else if (I->getInstType() == Instruction::Switch) {
// Special case switch statement to get formatting nice and correct...
writeOperand(Operand , true); Out << ",";
writeOperand(I->getOperand(1), true); Out << " [";
for (unsigned op = 2; (Operand = I->getOperand(op)); op += 2) {
Out << "\n\t\t";
writeOperand(Operand, true); Out << ",";
writeOperand(I->getOperand(op+1), true);
}
Out << "\n\t]";
} else if (I->getInstType() == Instruction::PHINode) {
Out << " " << Operand->getType();
Out << " ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(1), false); Out << " ]";
for (unsigned op = 2; (Operand = I->getOperand(op)); op += 2) {
Out << ", ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(op+1), false); Out << " ]";
}
} else if (I->getInstType() == Instruction::Ret && !Operand) {
Out << " void";
} else if (I->getInstType() == Instruction::Call) {
writeOperand(Operand, true);
Out << "(";
Operand = I->getOperand(1);
if (Operand) writeOperand(Operand, true);
for (unsigned op = 2; (Operand = I->getOperand(op)); ++op) {
Out << ",";
writeOperand(Operand, true);
}
Out << " )";
} else if (I->getInstType() == Instruction::Malloc ||
I->getInstType() == Instruction::Alloca) {
Out << " " << ((const PointerType*)((ConstPoolType*)Operand)
->getValue())->getValueType();
if ((Operand = I->getOperand(1))) {
Out << ","; writeOperand(Operand, true);
}
} else if (Operand) { // Print the normal way...
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
const Type *TheType = Operand->getType();
unsigned i;
for (i = 1; (Operand = I->getOperand(i)); i++) {
if (Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
if (!PrintAllTypes)
Out << " " << I->getOperand(0)->getType();
for (unsigned i = 0; (Operand = I->getOperand(i)); i++) {
if (i) Out << ",";
writeOperand(Operand, PrintAllTypes);
}
}
// Print a little comment after the instruction indicating which slot it
// occupies.
//
if (I->getType() != Type::VoidTy) {
Out << "\t\t; <" << I->getType() << ">";
if (!I->hasName()) {
int Slot = Table.getValSlot(I); // Print out the def slot taken...
if (Slot >= 0) Out << ":" << Slot;
else Out << ":<badref>";
}
Out << "\t[#uses=" << I->use_size() << "]"; // Output # uses
}
Out << endl;
return false;
}
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
bool PrintName) {
if (PrintType)
Out << " " << Operand->getType();
if (Operand->hasName() && PrintName) {
Out << " %" << Operand->getName();
} else {
int Slot = Table.getValSlot(Operand);
if (Operand->getValueType() == Value::ConstantVal) {
Out << " " << ((ConstPoolVal*)Operand)->getStrValue();
} else {
if (Slot >= 0) Out << " %" << Slot;
else if (PrintName)
Out << "<badref>"; // Not embeded into a location?
}
}
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void WriteToAssembly(const Module *M, ostream &o) {
if (M == 0) { o << "<null> module\n"; return; }
SlotCalculator SlotTable(M, true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const Method *M, ostream &o) {
if (M == 0) { o << "<null> method\n"; return; }
SlotCalculator SlotTable(M->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const BasicBlock *BB, ostream &o) {
if (BB == 0) { o << "<null> basic block\n"; return; }
SlotCalculator SlotTable(BB->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(BB);
}
void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
if (CPV == 0) { o << "<null> constant pool value\n"; return; }
SlotCalculator *SlotTable;
// A Constant pool value may have a parent that is either a method or a
// module. Untangle this now...
//
if (CPV->getParent() == 0 ||
CPV->getParent()->getValueType() == Value::MethodVal) {
SlotTable = new SlotCalculator((Method*)CPV->getParent(), true);
} else {
assert(CPV->getParent()->getValueType() == Value::ModuleVal);
SlotTable = new SlotCalculator((Module*)CPV->getParent(), true);
}
AssemblyWriter W(o, *SlotTable);
W.write(CPV);
delete SlotTable;
}
void WriteToAssembly(const Instruction *I, ostream &o) {
if (I == 0) { o << "<null> instruction\n"; return; }
SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0,
true);
AssemblyWriter W(o, SlotTable);
W.write(I);
}
<|endoftext|> |
<commit_before>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 a Platform module header.
#include <platform/Platform.h>
// Open a root engine namespace
DC_USE_DREEMCHEST
// Open a platform namespace to use shorter types.
using namespace platform;
// This class is a key for handling events raised by Window.
// Yes, this is a window delegate class, and it works in the
// same way as an application delegate.
class WindowHandler : public WindowDelegate {
// This method is called when mouse/touch is pressed.
virtual void handleMouseDown( Window* window, u32 x, u32 y, int touchId ) {
platform::log::msg( "handleMouseDown : %d %d\n", x, y );
}
// This method is called when mouse/touch is released.
virtual void handleMouseUp( Window* window, u32 x, u32 y, int touchId ) {
platform::log::msg( "handleMouseUp : %d %d\n", x, y );
}
// This method is called when mouse/touch is moved.
virtual void handleMouseMove( Window* window, u32 sx, u32 sy, u32 ex, u32 ey, int touchId ) {
platform::log::msg( "handleMouseMove : %d %d\n", ex, ey );
}
// This method is called when key is pressed.
virtual void handleKeyDown( Window* window, Key key ) {
platform::log::msg( "handleKeyDown : %d\n", key );
}
// This method is called when key is released.
virtual void handleKeyUp( Window* window, Key key ) {
platform::log::msg( "handleKeyUp : %d\n", key );
}
// This method is called each frame
virtual void handleUpdate( Window* window ) {
}
};
// Application delegate is used to handle an events raised by application instance.
class WindowEvents : public ApplicationDelegate {
// This method will be called once an application is launched.
virtual void handleLaunched( Application* application ) {
platform::log::setStandardHandler();
// Create a 800x600 window like we did in previous example.
Window* window = Window::create( 800, 600 );
// Now set a window delegate.
window->setDelegate( new WindowHandler );
}
};
// Now declare an application entry point with WindowEvents application delegate.
dcDeclareApplication( new WindowEvents )<commit_msg>Fixed compilation issue<commit_after>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 a Platform module header.
#include <platform/Platform.h>
// Open a root engine namespace
DC_USE_DREEMCHEST
// Open a platform namespace to use shorter types.
using namespace platform;
// This class is a key for handling events raised by Window.
// Yes, this is a window delegate class, and it works in the
// same way as an application delegate.
class WindowHandler : public WindowDelegate {
// This method is called when mouse/touch is pressed.
virtual void handleMouseDown( Window* window, u32 x, u32 y, int touchId ) {
platform::log::msg( "handleMouseDown : %d %d\n", x, y );
}
// This method is called when mouse/touch is released.
virtual void handleMouseUp( Window* window, u32 x, u32 y, int touchId ) {
platform::log::msg( "handleMouseUp : %d %d\n", x, y );
}
// This method is called when mouse/touch is moved.
virtual void handleMouseMove( Window* window, u32 sx, u32 sy, u32 ex, u32 ey, int touchId ) {
platform::log::msg( "handleMouseMove : %d %d\n", ex, ey );
}
// This method is called when key is pressed.
virtual void handleKeyDown( Window* window, Key key ) {
platform::log::msg( "handleKeyDown : %d\n", (int)key );
}
// This method is called when key is released.
virtual void handleKeyUp( Window* window, Key key ) {
platform::log::msg( "handleKeyUp : %d\n", (int)key );
}
// This method is called each frame
virtual void handleUpdate( Window* window ) {
}
};
// Application delegate is used to handle an events raised by application instance.
class WindowEvents : public ApplicationDelegate {
// This method will be called once an application is launched.
virtual void handleLaunched( Application* application ) {
platform::log::setStandardHandler();
// Create a 800x600 window like we did in previous example.
Window* window = Window::create( 800, 600 );
// Now set a window delegate.
window->setDelegate( new WindowHandler );
}
};
// Now declare an application entry point with WindowEvents application delegate.
dcDeclareApplication( new WindowEvents )<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
}<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 "amr_includes.H"
#include "fc2d_clawpack46.H"
#include "swirl_user.H"
#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif
void swirl_link_solvers(fclaw2d_domain_t *domain)
{
fclaw2d_solver_functions_t* sf = get_solver_functions(domain);
sf->use_single_step_update = fclaw_true;
sf->use_mol_update = fclaw_false;
sf->f_patch_setup = &swirl_patch_setup;
sf->f_patch_initialize = &swirl_patch_initialize;
sf->f_patch_physical_bc = &swirl_patch_physical_bc;
sf->f_patch_single_step_update = &swirl_patch_single_step_update;
fclaw2d_output_functions_t* of = get_output_functions(domain);
of->f_patch_write_header = &swirl_parallel_write_header;
of->f_patch_write_output = &swirl_parallel_write_output;
fc2d_clawpack46_link_to_clawpatch();
}
void swirl_problem_setup(fclaw2d_domain_t* domain)
{
fc2d_clawpack46_setprob(domain);
}
void swirl_patch_setup(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx)
{
fc2d_clawpack46_setaux(domain,this_patch,this_block_idx,this_patch_idx);
}
void swirl_patch_initialize(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx)
{
fc2d_clawpack46_qinit(domain,this_patch,this_block_idx,this_patch_idx);
}
void swirl_patch_physical_bc(fclaw2d_domain *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt,
fclaw_bool intersects_bc[],
fclaw_bool time_interp)
{
fc2d_clawpack46_bc2(domain,this_patch,this_block_idx,this_patch_idx,
t,dt,intersects_bc,time_interp);
}
double swirl_patch_single_step_update(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt)
{
fc2d_clawpack46_b4step2(domain,this_patch,this_block_idx,this_patch_idx,t,dt);
double maxcfl = fc2d_clawpack46_step2(domain,this_patch,this_block_idx,
this_patch_idx,t,dt);
return maxcfl;
}
/* -----------------------------------------------------------------
Default routine for tagging patches for refinement and coarsening
----------------------------------------------------------------- */
fclaw_bool swirl_patch_tag4refinement(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int initflag)
{
/* ----------------------------------------------------------- */
// Global parameters
const amr_options_t *gparms = get_domain_parms(domain);
int mx = gparms->mx;
int my = gparms->my;
int mbc = gparms->mbc;
int meqn = gparms->meqn;
/* ----------------------------------------------------------- */
// Patch specific parameters
ClawPatch *cp = get_clawpatch(this_patch);
double xlower = cp->xlower();
double ylower = cp->ylower();
double dx = cp->dx();
double dy = cp->dy();
/* ------------------------------------------------------------ */
// Pointers needed to pass to Fortran
double* q = cp->q();
int tag_patch = 0;
swirl_tag4refinement_(mx,my,mbc,meqn,xlower,ylower,dx,dy,q,initflag,tag_patch);
return tag_patch == 1;
}
fclaw_bool swirl_patch_tag4coarsening(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int blockno,
int patchno)
{
/* ----------------------------------------------------------- */
// Global parameters
const amr_options_t *gparms = get_domain_parms(domain);
int mx = gparms->mx;
int my = gparms->my;
int mbc = gparms->mbc;
int meqn = gparms->meqn;
/* ----------------------------------------------------------- */
// Patch specific parameters
ClawPatch *cp = get_clawpatch(this_patch);
double xlower = cp->xlower();
double ylower = cp->ylower();
double dx = cp->dx();
double dy = cp->dy();
/* ------------------------------------------------------------ */
// Pointers needed to pass to Fortran
double* qcoarse = cp->q();
int tag_patch = 1; // == 0 or 1
swirl_tag4coarsening_(mx,my,mbc,meqn,xlower,ylower,dx,dy,qcoarse,tag_patch);
return tag_patch == 0;
}
void swirl_parallel_write_header(fclaw2d_domain_t* domain, int iframe, int ngrids)
{
const amr_options_t *gparms = get_domain_parms(domain);
double time = get_domain_time(domain);
printf("Matlab output Frame %d at time %16.8e\n\n",iframe,time);
// Write out header file containing global information for 'iframe'
int mfields = gparms->meqn;
int maux = 0;
swirl_write_tfile_(iframe,time,mfields,ngrids,maux);
// This opens file 'fort.qXXXX' for replace (where XXXX = <zero padding><iframe>, e.g. 0001,
// 0010, 0114), and closes the file.
new_qfile_(iframe);
}
void swirl_parallel_write_output(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int iframe,int num,int level)
{
/* ----------------------------------------------------------- */
// Global parameters
const amr_options_t *gparms = get_domain_parms(domain);
int mx = gparms->mx;
int my = gparms->my;
int mbc = gparms->mbc;
int meqn = gparms->meqn;
/* ----------------------------------------------------------- */
// Patch specific parameters
ClawPatch *cp = get_clawpatch(this_patch);
double xlower = cp->xlower();
double ylower = cp->ylower();
double dx = cp->dx();
double dy = cp->dy();
/* ------------------------------------------------------------ */
// Pointers needed to pass to Fortran
double* q = cp->q();
/* ------------------------------------------------------------- */
// This opens a file for append. Now, the style is in the 'clawout' style.
int matlab_level = level;
int mpirank = domain->mpirank;
swirl_write_qfile_(meqn,mbc,mx,my,xlower,ylower,dx,dy,q,
iframe,num,matlab_level,this_block_idx,
mpirank);
}
#ifdef __cplusplus
#if 0
{
#endif
}
#endif
<commit_msg>(swirl) Add clawpack vtable<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 "amr_includes.H"
#include "fc2d_clawpack46.H"
#include "swirl_user.H"
#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif
static const fc2d_clawpack46_vtable_t classic_user =
{
setprob_,
NULL, /* bc2 */
qinit_,
setaux_,
b4step2_,
NULL /* src2 */
};
void swirl_link_solvers(fclaw2d_domain_t *domain)
{
fclaw2d_solver_functions_t* sf = get_solver_functions(domain);
sf->use_single_step_update = fclaw_true;
sf->use_mol_update = fclaw_false;
sf->f_patch_setup = &swirl_patch_setup;
sf->f_patch_initialize = &swirl_patch_initialize;
sf->f_patch_physical_bc = &swirl_patch_physical_bc;
sf->f_patch_single_step_update = &swirl_patch_single_step_update;
fclaw2d_output_functions_t* of = get_output_functions(domain);
of->f_patch_write_header = &swirl_parallel_write_header;
of->f_patch_write_output = &swirl_parallel_write_output;
fc2d_clawpack46_set_vtable(&classic_user);
fc2d_clawpack46_link_to_clawpatch();
}
void swirl_problem_setup(fclaw2d_domain_t* domain)
{
fc2d_clawpack46_setprob();
}
void swirl_patch_setup(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx)
{
fc2d_clawpack46_setaux(domain,this_patch,this_block_idx,this_patch_idx);
}
void swirl_patch_initialize(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx)
{
fc2d_clawpack46_qinit(domain,this_patch,this_block_idx,this_patch_idx);
}
void swirl_patch_physical_bc(fclaw2d_domain *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt,
fclaw_bool intersects_bc[],
fclaw_bool time_interp)
{
fc2d_clawpack46_bc2(domain,this_patch,this_block_idx,this_patch_idx,
t,dt,intersects_bc,time_interp);
}
double swirl_patch_single_step_update(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt)
{
fc2d_clawpack46_b4step2(domain,this_patch,this_block_idx,this_patch_idx,t,dt);
double maxcfl = fc2d_clawpack46_step2(domain,this_patch,this_block_idx,
this_patch_idx,t,dt);
return maxcfl;
}
/* -----------------------------------------------------------------
Default routine for tagging patches for refinement and coarsening
----------------------------------------------------------------- */
fclaw_bool swirl_patch_tag4refinement(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int initflag)
{
/* ----------------------------------------------------------- */
// Global parameters
const amr_options_t *gparms = get_domain_parms(domain);
int mx = gparms->mx;
int my = gparms->my;
int mbc = gparms->mbc;
int meqn = gparms->meqn;
/* ----------------------------------------------------------- */
// Patch specific parameters
ClawPatch *cp = get_clawpatch(this_patch);
double xlower = cp->xlower();
double ylower = cp->ylower();
double dx = cp->dx();
double dy = cp->dy();
/* ------------------------------------------------------------ */
// Pointers needed to pass to Fortran
double* q = cp->q();
int tag_patch = 0;
swirl_tag4refinement_(mx,my,mbc,meqn,xlower,ylower,dx,dy,q,initflag,tag_patch);
return tag_patch == 1;
}
fclaw_bool swirl_patch_tag4coarsening(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int blockno,
int patchno)
{
/* ----------------------------------------------------------- */
// Global parameters
const amr_options_t *gparms = get_domain_parms(domain);
int mx = gparms->mx;
int my = gparms->my;
int mbc = gparms->mbc;
int meqn = gparms->meqn;
/* ----------------------------------------------------------- */
// Patch specific parameters
ClawPatch *cp = get_clawpatch(this_patch);
double xlower = cp->xlower();
double ylower = cp->ylower();
double dx = cp->dx();
double dy = cp->dy();
/* ------------------------------------------------------------ */
// Pointers needed to pass to Fortran
double* qcoarse = cp->q();
int tag_patch = 1; // == 0 or 1
swirl_tag4coarsening_(mx,my,mbc,meqn,xlower,ylower,dx,dy,qcoarse,tag_patch);
return tag_patch == 0;
}
void swirl_parallel_write_header(fclaw2d_domain_t* domain, int iframe, int ngrids)
{
const amr_options_t *gparms = get_domain_parms(domain);
double time = get_domain_time(domain);
printf("Matlab output Frame %d at time %16.8e\n\n",iframe,time);
// Write out header file containing global information for 'iframe'
int mfields = gparms->meqn;
int maux = 0;
swirl_write_tfile_(iframe,time,mfields,ngrids,maux);
// This opens file 'fort.qXXXX' for replace (where XXXX = <zero padding><iframe>, e.g. 0001,
// 0010, 0114), and closes the file.
new_qfile_(iframe);
}
void swirl_parallel_write_output(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int iframe,int num,int level)
{
/* ----------------------------------------------------------- */
// Global parameters
const amr_options_t *gparms = get_domain_parms(domain);
int mx = gparms->mx;
int my = gparms->my;
int mbc = gparms->mbc;
int meqn = gparms->meqn;
/* ----------------------------------------------------------- */
// Patch specific parameters
ClawPatch *cp = get_clawpatch(this_patch);
double xlower = cp->xlower();
double ylower = cp->ylower();
double dx = cp->dx();
double dy = cp->dy();
/* ------------------------------------------------------------ */
// Pointers needed to pass to Fortran
double* q = cp->q();
/* ------------------------------------------------------------- */
// This opens a file for append. Now, the style is in the 'clawout' style.
int matlab_level = level;
int mpirank = domain->mpirank;
swirl_write_qfile_(meqn,mbc,mx,my,xlower,ylower,dx,dy,q,
iframe,num,matlab_level,this_block_idx,
mpirank);
}
#ifdef __cplusplus
#if 0
{
#endif
}
#endif
<|endoftext|> |
<commit_before>#ifndef CAN_EMULATOR
#include "usbutil.h"
#include "canread.h"
#include "serialutil.h"
#include "signals.h"
#include "log.h"
#include "cJSON.h"
#include "listener.h"
#include <stdint.h>
extern SerialDevice SERIAL_DEVICE;
extern UsbDevice USB_DEVICE;
extern Listener listener;
/* Forward declarations */
void receiveCan(CanBus*);
void initializeAllCan();
bool receiveWriteRequest(uint8_t*);
bool receiveCANWriteRequest(uint8_t*);
void setup() {
initializeLogging();
initializeSerial(&SERIAL_DEVICE);
initializeUsb(&USB_DEVICE);
initializeAllCan();
}
void loop() {
for(int i = 0; i < getCanBusCount(); i++) {
receiveCan(&getCanBuses()[i]);
}
processListenerQueues(&listener);
#ifdef TRANSMITTER
readFromHost(&USB_DEVICE, &receiveCANWriteRequest);
readFromSerial(&SERIAL_DEVICE, &receiveCANWriteRequest);
#else
readFromHost(&USB_DEVICE, &receiveWriteRequest);
readFromSerial(&SERIAL_DEVICE, &receiveWriteRequest);
for(int i = 0; i < getCanBusCount(); i++) {
processCanWriteQueue(&getCanBuses()[i]);
}
#endif
}
void initializeAllCan() {
for(int i = 0; i < getCanBusCount(); i++) {
initializeCan(&(getCanBuses()[i]));
}
}
#ifdef TRANSMITTER
bool receiveCANWriteRequest(uint8_t* message) {
int index=0;
int packetLength = 15;
while(true) {
if(message[index] == '!') {
return true;
}
if (index + packetLength >= 64) {
debug("!");
}
if(message[index] != '{' || message[index+5] != '|'
|| message[index+14] != '}') {
debug("Received a corrupted CAN message.\r\n");
for(int i = 0; i < 16; i++) {
debug("%02x ", message[index+i] );
}
debug("\r\n");
return false;
}
CanMessage outGoing = {0, 0};
memcpy((uint8_t*)&outGoing.id, &message[index+1], 4);
for(int i = 0; i < 8; i++) {
((uint8_t*)&(outGoing.data))[i] = message[index+i+6];
}
// debug("Sending CAN message id = 0x%02x, data = 0x", outGoing.id);
//for(int i = 0; i < 8; i++) {
// debug("%02x ", ((uint8_t*)&(outGoing.data))[i] );
//}
//debug("\r\n");
sendCanMessage(&(getCanBuses()[0]), outGoing);
index += packetLength;
}
return true;
}
#else //ifdef TRANSMITTER
bool receiveRawWriteRequest(cJSON* idObject, cJSON* root) {
int id = idObject->valueint;
cJSON* dataObject = cJSON_GetObjectItem(root, "data");
if(dataObject == NULL) {
debug("Raw write request missing data\r\n", id);
return true;
}
int data = dataObject->valueint;
CanMessage message = {id, data};
QUEUE_PUSH(CanMessage, &getCanBuses()[0].sendQueue, message);
return true;
}
bool receiveWriteRequest(uint8_t* message) {
cJSON *root = cJSON_Parse((char*)message);
if(root != NULL) {
cJSON* nameObject = cJSON_GetObjectItem(root, "name");
if(nameObject == NULL) {
cJSON* idObject = cJSON_GetObjectItem(root, "id");
if(idObject == NULL) {
debug("Write request is malformed, "
"missing name or id: %s\r\n", message);
return true;
} else {
return receiveRawWriteRequest(idObject, root);
}
}
char* name = nameObject->valuestring;
cJSON* value = cJSON_GetObjectItem(root, "value");
if(value == NULL) {
debug("Write request for %s missing value\r\n", name);
return true;
}
CanSignal* signal = lookupSignal(name, getSignals(),
getSignalCount(), true);
CanCommand* command = lookupCommand(name, getCommands(),
getCommandCount());
if(signal != NULL) {
sendCanSignal(signal, value, getSignals(), getSignalCount());
} else if(command != NULL) {
command->handler(name, value, getSignals(), getSignalCount());
} else {
debug("Writing not allowed for signal with name %s\r\n", name);
}
cJSON_Delete(root);
return true;
}
return false;
}
#endif
/*
* Check to see if a packet has been received. If so, read the packet and print
* the packet payload to the serial monitor.
*/
void receiveCan(CanBus* bus) {
// TODO what happens if we process until the queue is empty?
if(!QUEUE_EMPTY(CanMessage, &bus->receiveQueue)) {
CanMessage message = QUEUE_POP(CanMessage, &bus->receiveQueue);
decodeCanMessage(message.id, message.data);
}
}
void reset() {
initializeAllCan();
}
#endif // CAN_EMULATOR
<commit_msg>Use CAN write queue when acting as a transmitter.<commit_after>#ifndef CAN_EMULATOR
#include "usbutil.h"
#include "canread.h"
#include "serialutil.h"
#include "signals.h"
#include "log.h"
#include "cJSON.h"
#include "listener.h"
#include <stdint.h>
extern SerialDevice SERIAL_DEVICE;
extern UsbDevice USB_DEVICE;
extern Listener listener;
/* Forward declarations */
void receiveCan(CanBus*);
void initializeAllCan();
bool receiveWriteRequest(uint8_t*);
void setup() {
initializeLogging();
initializeSerial(&SERIAL_DEVICE);
initializeUsb(&USB_DEVICE);
initializeAllCan();
}
void loop() {
for(int i = 0; i < getCanBusCount(); i++) {
receiveCan(&getCanBuses()[i]);
}
processListenerQueues(&listener);
readFromHost(&USB_DEVICE, &receiveWriteRequest);
readFromSerial(&SERIAL_DEVICE, &receiveWriteRequest);
for(int i = 0; i < getCanBusCount(); i++) {
processCanWriteQueue(&getCanBuses()[i]);
}
}
void initializeAllCan() {
for(int i = 0; i < getCanBusCount(); i++) {
initializeCan(&(getCanBuses()[i]));
}
}
bool receiveRawWriteRequest(cJSON* idObject, cJSON* root) {
int id = idObject->valueint;
cJSON* dataObject = cJSON_GetObjectItem(root, "data");
if(dataObject == NULL) {
debug("Raw write request missing data\r\n", id);
return true;
}
int data = dataObject->valueint;
CanMessage message = {id, data};
QUEUE_PUSH(CanMessage, &getCanBuses()[0].sendQueue, message);
return true;
}
bool receiveWriteRequest(uint8_t* message) {
#ifdef TRANSMITTER
int index = 0;
const int BINARY_CAN_WRITE_PACKET_LENGTH = 15;
while(message[index] != '!') {
if (index + BINARY_CAN_WRITE_PACKET_LENGTH >= 64) {
debug("!");
}
if(message[index] != '{' || message[index+5] != '|'
|| message[index+14] != '}') {
debug("Received a corrupted CAN message.\r\n");
for(int i = 0; i < 16; i++) {
debug("%02x ", message[index+i] );
}
debug("\r\n");
return false;
}
CanMessage outgoing = {0, 0};
memcpy((uint8_t*)&outgoing.id, &message[index+1], 4);
for(int i = 0; i < 8; i++) {
((uint8_t*)&(outgoing.data))[i] = message[index+i+6];
}
QUEUE_PUSH(CanMessage, &getCanBuses()[0].sendQueue, outgoing);
}
return true;
#else
cJSON *root = cJSON_Parse((char*)message);
if(root != NULL) {
cJSON* nameObject = cJSON_GetObjectItem(root, "name");
if(nameObject == NULL) {
cJSON* idObject = cJSON_GetObjectItem(root, "id");
if(idObject == NULL) {
debug("Write request is malformed, "
"missing name or id: %s\r\n", message);
return true;
} else {
return receiveRawWriteRequest(idObject, root);
}
}
char* name = nameObject->valuestring;
cJSON* value = cJSON_GetObjectItem(root, "value");
if(value == NULL) {
debug("Write request for %s missing value\r\n", name);
return true;
}
CanSignal* signal = lookupSignal(name, getSignals(),
getSignalCount(), true);
CanCommand* command = lookupCommand(name, getCommands(),
getCommandCount());
if(signal != NULL) {
sendCanSignal(signal, value, getSignals(), getSignalCount());
} else if(command != NULL) {
command->handler(name, value, getSignals(), getSignalCount());
} else {
debug("Writing not allowed for signal with name %s\r\n", name);
}
cJSON_Delete(root);
return true;
}
return false;
#endif
}
/*
* Check to see if a packet has been received. If so, read the packet and print
* the packet payload to the serial monitor.
*/
void receiveCan(CanBus* bus) {
// TODO what happens if we process until the queue is empty?
if(!QUEUE_EMPTY(CanMessage, &bus->receiveQueue)) {
CanMessage message = QUEUE_POP(CanMessage, &bus->receiveQueue);
decodeCanMessage(message.id, message.data);
}
}
void reset() {
initializeAllCan();
}
#endif // CAN_EMULATOR
<|endoftext|> |
<commit_before>
#include "world.hpp"
namespace hacky_internals {
// When a worldblock is inited, it DOESN'T call insert_water for all the water in it - the water is 'already there'.
// Water that starts out in a worldblock starts out inactive (observing the rule "the landscape takes zero time to process").
//
// We would have to make special rules for worldblocks that start out with
// active water in them, because it could invalidate iterators into the
// active_tiles map, because worldblocks can be created essentially any time in the processing.
// TODO: "init_if_needed" is because we don't know how to make unordered_map's mapped_types be constructed in place in a non-default way.
worldblock& worldblock::init_if_needed(world *w_, vector3<location_coordinate> global_position_) {
if (!inited) {
inited = true;
w = w_;
global_position = global_position_;
axis_aligned_bounding_box bounds{global_position, vector3<location_coordinate>(worldblock_dimension,worldblock_dimension,worldblock_dimension)};
w->worldgen_function(world_building_gun(w, bounds), bounds);
std::cerr << "A worldblock has been created!\n";
}
return (*this);
}
tile& worldblock::get_tile(vector3<location_coordinate> global_coords) {
vector3<location_coordinate> local_coords = global_coords - global_position;
return tiles[local_coords.x][local_coords.y][local_coords.z];
}
location worldblock::get_neighboring_loc(vector3<location_coordinate> const& old_coords, cardinal_direction dir) {
// this could be made more effecient, but I'm not sure how
vector3<location_coordinate> new_coords = old_coords + dir.v;
if (new_coords.x < global_position.x) return location(new_coords, neighbors[cdir_xminus]);
if (new_coords.y < global_position.y) return location(new_coords, neighbors[cdir_yminus]);
if (new_coords.z < global_position.z) return location(new_coords, neighbors[cdir_zminus]);
if (new_coords.x >= global_position.x + worldblock_dimension) return location(new_coords, neighbors[cdir_xplus]);
if (new_coords.y >= global_position.y + worldblock_dimension) return location(new_coords, neighbors[cdir_yplus]);
if (new_coords.z >= global_position.z + worldblock_dimension) return location(new_coords, neighbors[cdir_zplus]);
return location(new_coords, this);
}
location worldblock::get_loc_across_boundary(vector3<location_coordinate> const& new_coords, cardinal_direction dir) {
if (worldblock* neighbor = neighbors[dir]) return location(new_coords, neighbor);
return location(new_coords, (neighbors[dir] = w->create_if_necessary_and_get_worldblock(global_position + vector3<worldblock_dimension_type>(dir.v) * worldblock_dimension)));
}
location worldblock::get_loc_guaranteed_to_be_in_this_block(vector3<location_coordinate> coords) {
return location(coords, this);
}
}
location location::operator+(cardinal_direction dir)const {
return wb->get_neighboring_loc(v, dir);
}
tile const& location::stuff_at()const { return wb->get_tile(v); }
location world::make_location(vector3<location_coordinate> const& coords) {
return create_if_necessary_and_get_worldblock(vector3<location_coordinate>(
coords.x & ~(hacky_internals::worldblock_dimension-1),
coords.y & ~(hacky_internals::worldblock_dimension-1),
coords.z & ~(hacky_internals::worldblock_dimension-1)
))->get_loc_guaranteed_to_be_in_this_block(coords);
}
hacky_internals::worldblock* world::create_if_necessary_and_get_worldblock(vector3<location_coordinate> position) {
return &(blocks[position].init_if_needed(this, position));
}
void world::ensure_space_exists(axis_aligned_bounding_box space) {
const hacky_internals::worldblock_dimension_type wd = hacky_internals::worldblock_dimension;
for (location_coordinate
x = space.min.x / wd;
x < (space.min.x + space.size.x + (wd - 1)) / wd;
++x) {
for (location_coordinate
y = space.min.y / wd;
y < (space.min.y + space.size.y + (wd - 1)) / wd;
++y) {
for (location_coordinate
z = space.min.z / wd;
z < (space.min.z + space.size.z + (wd - 1)) / wd;
++z) {
const vector3<location_coordinate> worldblock_position(x*wd, y*wd, z*wd);
create_if_necessary_and_get_worldblock(worldblock_position);
}
}
}
}
<commit_msg>Fixed the segfault. Water now exists and simulates in real time, but the physics are wrong.<commit_after>
#include "world.hpp"
namespace hacky_internals {
// When a worldblock is inited, it DOESN'T call insert_water for all the water in it - the water is 'already there'.
// Water that starts out in a worldblock starts out inactive (observing the rule "the landscape takes zero time to process").
//
// We would have to make special rules for worldblocks that start out with
// active water in them, because it could invalidate iterators into the
// active_tiles map, because worldblocks can be created essentially any time in the processing.
// TODO: "init_if_needed" is because we don't know how to make unordered_map's mapped_types be constructed in place in a non-default way.
worldblock& worldblock::init_if_needed(world *w_, vector3<location_coordinate> global_position_) {
if (!inited) {
inited = true;
w = w_;
global_position = global_position_;
axis_aligned_bounding_box bounds{global_position, vector3<location_coordinate>(worldblock_dimension,worldblock_dimension,worldblock_dimension)};
w->worldgen_function(world_building_gun(w, bounds), bounds);
std::cerr << "A worldblock has been created!\n";
}
return (*this);
}
tile& worldblock::get_tile(vector3<location_coordinate> global_coords) {
vector3<location_coordinate> local_coords = global_coords - global_position;
return tiles[local_coords.x][local_coords.y][local_coords.z];
}
location worldblock::get_neighboring_loc(vector3<location_coordinate> const& old_coords, cardinal_direction dir) {
// this could be made more effecient, but I'm not sure how
vector3<location_coordinate> new_coords = old_coords + dir.v;
if (new_coords.x < global_position.x) return get_loc_across_boundary(new_coords, cdir_xminus);
if (new_coords.y < global_position.y) return get_loc_across_boundary(new_coords, cdir_yminus);
if (new_coords.z < global_position.z) return get_loc_across_boundary(new_coords, cdir_zminus);
if (new_coords.x >= global_position.x + worldblock_dimension) return get_loc_across_boundary(new_coords, cdir_xplus);
if (new_coords.y >= global_position.y + worldblock_dimension) return get_loc_across_boundary(new_coords, cdir_yplus);
if (new_coords.z >= global_position.z + worldblock_dimension) return get_loc_across_boundary(new_coords, cdir_zplus);
return location(new_coords, this);
}
location worldblock::get_loc_across_boundary(vector3<location_coordinate> const& new_coords, cardinal_direction dir) {
if (worldblock* neighbor = neighbors[dir]) return location(new_coords, neighbor);
return location(new_coords, (neighbors[dir] = w->create_if_necessary_and_get_worldblock(global_position + vector3<worldblock_dimension_type>(dir.v) * worldblock_dimension)));
}
location worldblock::get_loc_guaranteed_to_be_in_this_block(vector3<location_coordinate> coords) {
return location(coords, this);
}
}
location location::operator+(cardinal_direction dir)const {
return wb->get_neighboring_loc(v, dir);
}
tile const& location::stuff_at()const { return wb->get_tile(v); }
location world::make_location(vector3<location_coordinate> const& coords) {
return create_if_necessary_and_get_worldblock(vector3<location_coordinate>(
coords.x & ~(hacky_internals::worldblock_dimension-1),
coords.y & ~(hacky_internals::worldblock_dimension-1),
coords.z & ~(hacky_internals::worldblock_dimension-1)
))->get_loc_guaranteed_to_be_in_this_block(coords);
}
hacky_internals::worldblock* world::create_if_necessary_and_get_worldblock(vector3<location_coordinate> position) {
return &(blocks[position].init_if_needed(this, position));
}
void world::ensure_space_exists(axis_aligned_bounding_box space) {
const hacky_internals::worldblock_dimension_type wd = hacky_internals::worldblock_dimension;
for (location_coordinate
x = space.min.x / wd;
x < (space.min.x + space.size.x + (wd - 1)) / wd;
++x) {
for (location_coordinate
y = space.min.y / wd;
y < (space.min.y + space.size.y + (wd - 1)) / wd;
++y) {
for (location_coordinate
z = space.min.z / wd;
z < (space.min.z + space.size.z + (wd - 1)) / wd;
++z) {
const vector3<location_coordinate> worldblock_position(x*wd, y*wd, z*wd);
create_if_necessary_and_get_worldblock(worldblock_position);
}
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "library/tactic/location.h"
#include "frontends/lean/parser.h"
#include "frontends/lean/tokens.h"
#include "frontends/lean/parse_tactic_location.h"
namespace lean {
static occurrence parse_occurrence(parser & p) {
if (p.curr_is_token(get_lcurly_tk())) {
p.next();
bool has_pos = false;
bool has_neg = false;
buffer<unsigned> occs;
while (true) {
if (p.curr_is_token(get_sub_tk())) {
if (has_pos)
throw parser_error("invalid tactic location, cannot mix positive and negative occurrences", p.pos());
has_neg = true;
p.next();
occs.push_back(p.parse_small_nat());
} else {
auto pos = p.pos();
occs.push_back(p.parse_small_nat());
if (has_neg)
throw parser_error("invalid tactic location, cannot mix positive and negative occurrences", pos);
has_pos = true;
}
if (p.curr_is_token(get_rcurly_tk()))
break;
}
p.next();
if (has_pos)
return occurrence::mk_occurrences(occs);
else
return occurrence::mk_except_occurrences(occs);
} else {
return occurrence();
}
}
location parse_tactic_location(parser & p) {
if (p.curr_is_token(get_at_tk())) {
p.next();
if (p.curr_is_token(get_star_tk())) {
p.next();
if (p.curr_is_token(get_turnstile_tk())) {
p.next();
if (p.curr_is_token(get_star_tk())) {
// at * |- *
return location::mk_everywhere();
} else {
// at * |-
return location::mk_all_hypotheses();
}
} else {
// at *
return location::mk_everywhere();
}
} else if (p.curr_is_token(get_lparen_tk())) {
p.next();
buffer<name> hyps;
buffer<occurrence> hyp_occs;
while (true) {
hyps.push_back(p.get_name_val());
p.next();
hyp_occs.push_back(parse_occurrence(p));
if (!p.curr_is_token(get_comma_tk()))
break;
p.next();
}
p.check_token_next(get_rparen_tk(), "invalid tactic location, ')' expected");
if (p.curr_is_token(get_turnstile_tk())) {
p.next();
occurrence goal_occ = parse_occurrence(p);
return location::mk_at(goal_occ, hyps, hyp_occs);
} else {
return location::mk_hypotheses_at(hyps, hyp_occs);
}
} else if (p.curr_is_token(get_lcurly_tk())) {
occurrence o = parse_occurrence(p);
return location::mk_goal_at(o);
} else {
buffer<name> hyps;
buffer<occurrence> hyp_occs;
hyps.push_back(p.check_id_next("invalid tactic location, identifier expected"));
hyp_occs.push_back(parse_occurrence(p));
return location::mk_hypotheses_at(hyps, hyp_occs);
}
} else {
return location::mk_goal_only();
}
}
}
<commit_msg>feat(frontends/lean/parse_tactic_location): validate occurrence index<commit_after>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "library/tactic/location.h"
#include "frontends/lean/parser.h"
#include "frontends/lean/tokens.h"
#include "frontends/lean/parse_tactic_location.h"
namespace lean {
static occurrence parse_occurrence(parser & p) {
if (p.curr_is_token(get_lcurly_tk())) {
p.next();
bool has_pos = false;
bool has_neg = false;
buffer<unsigned> occs;
while (true) {
if (p.curr_is_token(get_sub_tk())) {
if (has_pos)
throw parser_error("invalid tactic location, cannot mix positive and negative occurrences", p.pos());
has_neg = true;
p.next();
auto pos = p.pos();
unsigned i = p.parse_small_nat();
if (i == 0)
throw parser_error("invalid tactic location, first occurrence is 1", pos);
occs.push_back(i);
} else {
auto pos = p.pos();
unsigned i = p.parse_small_nat();
if (i == 0)
throw parser_error("invalid tactic location, first occurrence is 1", pos);
occs.push_back(i);
if (has_neg)
throw parser_error("invalid tactic location, cannot mix positive and negative occurrences", pos);
has_pos = true;
}
if (p.curr_is_token(get_rcurly_tk()))
break;
}
p.next();
if (has_pos)
return occurrence::mk_occurrences(occs);
else
return occurrence::mk_except_occurrences(occs);
} else {
return occurrence();
}
}
location parse_tactic_location(parser & p) {
if (p.curr_is_token(get_at_tk())) {
p.next();
if (p.curr_is_token(get_star_tk())) {
p.next();
if (p.curr_is_token(get_turnstile_tk())) {
p.next();
if (p.curr_is_token(get_star_tk())) {
// at * |- *
return location::mk_everywhere();
} else {
// at * |-
return location::mk_all_hypotheses();
}
} else {
// at *
return location::mk_everywhere();
}
} else if (p.curr_is_token(get_lparen_tk())) {
p.next();
buffer<name> hyps;
buffer<occurrence> hyp_occs;
while (true) {
hyps.push_back(p.get_name_val());
p.next();
hyp_occs.push_back(parse_occurrence(p));
if (!p.curr_is_token(get_comma_tk()))
break;
p.next();
}
p.check_token_next(get_rparen_tk(), "invalid tactic location, ')' expected");
if (p.curr_is_token(get_turnstile_tk())) {
p.next();
occurrence goal_occ = parse_occurrence(p);
return location::mk_at(goal_occ, hyps, hyp_occs);
} else {
return location::mk_hypotheses_at(hyps, hyp_occs);
}
} else if (p.curr_is_token(get_lcurly_tk())) {
occurrence o = parse_occurrence(p);
return location::mk_goal_at(o);
} else {
buffer<name> hyps;
buffer<occurrence> hyp_occs;
hyps.push_back(p.check_id_next("invalid tactic location, identifier expected"));
hyp_occs.push_back(parse_occurrence(p));
return location::mk_hypotheses_at(hyps, hyp_occs);
}
} else {
return location::mk_goal_only();
}
}
}
<|endoftext|> |
<commit_before>#include "cbase.h"
#include "asw_door_area.h"
#include "func_movelinear.h"
#include "asw_button_area.h"
#include "asw_base_spawner.h"
#include "asw_marine_hint.h"
#include "ai_network.h"
#include "ai_link.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar asw_follow_ignore_hints("asw_follow_ignore_hints", "0.1", FCVAR_CHEAT, "If less than (by default) 10% of nodes are marine hints, use all nodes as marine hints.");
// BenLubar: I really wish I didn't have to do this, but there are popular campaigns that have huge problems in them.
class CASW_Campaign_Fixes : public CAutoGameSystem
{
public:
CASW_Campaign_Fixes() : CAutoGameSystem("CASW_Campaign_Fixes") {}
virtual void LevelInitPostEntity()
{
const char *pszMap = STRING(gpGlobals->mapname);
// Fixes cargo elevator leaving without all the marines if at least 4 marines are already on the elevator.
if (!V_stricmp(pszMap, "asi-jac1-landingbay_02"))
{
CASW_Door_Area *pMarinesPast = dynamic_cast<CASW_Door_Area *>(gEntList.FindEntityByName(NULL, "trigger_lift_marine_check"));
Assert(pMarinesPast);
if (pMarinesPast)
pMarinesPast->m_nPlayersRequired = ASW_MAX_MARINE_RESOURCES;
}
// Fixes the last segment of a bridge on deima being extended before the marines get there.
if (!V_stricmp(pszMap, "asi-jac2-deima"))
{
CFuncMoveLinear *pBridgeGate = dynamic_cast<CFuncMoveLinear *>(gEntList.FindEntityByName(NULL, "move_door_bridge"));
Assert(pBridgeGate);
if (pBridgeGate)
{
CBaseEntityOutput *pOutput = pBridgeGate->FindNamedOutput("OnFullyOpen");
Assert(pOutput);
if (pOutput)
{
Assert(pOutput->NumberOfElements() == 2);
pOutput->DeleteAllElements();
}
}
}
// Fixes the tech marine requirement never being turned off after the last hack.
if (!V_stricmp(pszMap, "dc1-omega_city"))
{
CASW_Button_Area *pEndButton = dynamic_cast<CASW_Button_Area *>(gEntList.FindEntityByName(NULL, "end_button"));
Assert(pEndButton);
if (pEndButton)
{
CBaseEntityOutput *pOutput = pEndButton->FindNamedOutput("OnButtonHackCompleted");
Assert(pOutput);
if (pOutput)
{
pOutput->ParseEventAction("asw_tech_marine_req,DisableTechMarineReq,,0,1");
}
}
}
// Fixes the tech marine requirement never being turned off after the last hack.
if (!V_stricmp(pszMap, "dc2-breaking_an_entry"))
{
CASW_Button_Area *pEndButton = NULL;
while ((pEndButton = dynamic_cast<CASW_Button_Area *>(gEntList.FindEntityByClassname(pEndButton, "trigger_asw_button_area"))))
{
if (!V_stricmp(STRING(pEndButton->m_szPanelPropName), "elevator_pc"))
{
CBaseEntityOutput *pOutput = pEndButton->FindNamedOutput("OnButtonHackCompleted");
Assert(pOutput);
if (pOutput)
{
pOutput->ParseEventAction("asw_tech_marine_req,DisableTechMarineReq,,0,1");
}
break;
}
}
}
// Fixes the tech marine requirement never being turned off after the last hack.
if (!V_stricmp(pszMap, "dc3-search_and_rescue"))
{
CASW_Button_Area *pC4PlantedButton = dynamic_cast<CASW_Button_Area *>(gEntList.FindEntityByName(NULL, "c4_planted_button"));
Assert(pC4PlantedButton);
if (pC4PlantedButton)
{
CBaseEntityOutput *pOutput = pC4PlantedButton->FindNamedOutput("OnButtonHackCompleted");
Assert(pOutput);
if (pOutput)
{
pOutput->ParseEventAction("asw_tech_marine_req,DisableTechMarineReq,,0,1");
}
}
}
// Fixes maps before the brutal update assuming there would always be exactly 4 difficulty levels.
bool bShouldFixSkillLevels = true;
CASW_Base_Spawner *pSpawner = NULL;
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_spawner"))) != NULL)
{
bShouldFixSkillLevels = bShouldFixSkillLevels && pSpawner->m_iMaxSkillLevel < 5;
}
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_holdout_spawner"))) != NULL)
{
bShouldFixSkillLevels = bShouldFixSkillLevels && pSpawner->m_iMaxSkillLevel < 5;
}
if (bShouldFixSkillLevels)
{
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_spawner"))) != NULL)
{
if (pSpawner->m_iMaxSkillLevel == 4)
pSpawner->m_iMaxSkillLevel = 5;
}
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_holdout_spawner"))) != NULL)
{
if (pSpawner->m_iMaxSkillLevel == 4)
pSpawner->m_iMaxSkillLevel = 5;
}
}
// Fixes maps without marine hints being confusing for marines. The hints are added in ai_initutils.cpp.
Assert( MarineHintManager() );
if ( MarineHintManager() && MarineHintManager()->m_LastResortHints.Count() )
{
CUtlVector<HintData_t *> &hints = MarineHintManager()->m_LastResortHints;
FOR_EACH_VEC_BACK( hints, i )
{
HintData_t *pHint = hints[i];
Assert( pHint );
Assert( g_pBigAINet );
int nNode = g_pBigAINet->NearestNodeToPoint( pHint->m_vecPosition, false );
CAI_Node *pNode = g_pBigAINet->GetNode( nNode );
Assert( pNode );
bool bAccessible = false;
if ( pNode )
{
// We consider nodes "accessible" if a marine can walk from there to any other node.
FOR_EACH_VEC( pNode->m_Links, j )
{
if ( pNode->m_Links[j]->m_iAcceptedMoveTypes[HULL_HUMAN] & bits_CAP_MOVE_GROUND )
{
bAccessible = true;
break;
}
}
}
if ( !bAccessible )
{
hints.FastRemove( i );
delete pHint;
}
}
if ( hints.Count() * asw_follow_ignore_hints.GetFloat() > MarineHintManager()->m_Hints.Count() )
{
// We have less than 10% marine hints. The mapper either forgot to add hints or added a few and forgot about it. Use the nodes instead.
MarineHintManager()->m_Hints.AddVectorToTail( hints );
hints.Purge();
// Reset the indices because we may have removed some from the middle.
FOR_EACH_VEC( MarineHintManager()->m_Hints, i )
{
MarineHintManager()->m_Hints[i]->m_nHintIndex = i;
}
}
else
{
hints.PurgeAndDeleteElements();
}
}
}
};
static CASW_Campaign_Fixes g_CampaignFixes;<commit_msg>MAPPING: fix the practice map as well<commit_after>#include "cbase.h"
#include "asw_door_area.h"
#include "func_movelinear.h"
#include "asw_button_area.h"
#include "asw_base_spawner.h"
#include "asw_marine_hint.h"
#include "ai_network.h"
#include "ai_link.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar asw_follow_ignore_hints("asw_follow_ignore_hints", "0.1", FCVAR_CHEAT, "If less than (by default) 10% of nodes are marine hints, use all nodes as marine hints.");
// BenLubar: I really wish I didn't have to do this, but there are popular campaigns that have huge problems in them.
class CASW_Campaign_Fixes : public CAutoGameSystem
{
public:
CASW_Campaign_Fixes() : CAutoGameSystem("CASW_Campaign_Fixes") {}
virtual void LevelInitPostEntity()
{
const char *pszMap = STRING(gpGlobals->mapname);
// Fixes cargo elevator leaving without all the marines if at least 4 marines are already on the elevator.
if (!V_stricmp(pszMap, "asi-jac1-landingbay_02") || !V_stricmp(pszMap, "asi-jac1-landingbay_pract"))
{
CASW_Door_Area *pMarinesPast = dynamic_cast<CASW_Door_Area *>(gEntList.FindEntityByName(NULL, "trigger_lift_marine_check"));
Assert(pMarinesPast);
if (pMarinesPast)
{
pMarinesPast->m_nPlayersRequired = ASW_MAX_MARINE_RESOURCES;
}
}
// Fixes the last segment of a bridge on deima being extended before the marines get there.
if (!V_stricmp(pszMap, "asi-jac2-deima"))
{
CFuncMoveLinear *pBridgeGate = dynamic_cast<CFuncMoveLinear *>(gEntList.FindEntityByName(NULL, "move_door_bridge"));
Assert(pBridgeGate);
if (pBridgeGate)
{
CBaseEntityOutput *pOutput = pBridgeGate->FindNamedOutput("OnFullyOpen");
Assert(pOutput);
if (pOutput)
{
Assert(pOutput->NumberOfElements() == 2);
pOutput->DeleteAllElements();
}
}
}
// Fixes the tech marine requirement never being turned off after the last hack.
if (!V_stricmp(pszMap, "dc1-omega_city"))
{
CASW_Button_Area *pEndButton = dynamic_cast<CASW_Button_Area *>(gEntList.FindEntityByName(NULL, "end_button"));
Assert(pEndButton);
if (pEndButton)
{
CBaseEntityOutput *pOutput = pEndButton->FindNamedOutput("OnButtonHackCompleted");
Assert(pOutput);
if (pOutput)
{
pOutput->ParseEventAction("asw_tech_marine_req,DisableTechMarineReq,,0,1");
}
}
}
// Fixes the tech marine requirement never being turned off after the last hack.
if (!V_stricmp(pszMap, "dc2-breaking_an_entry"))
{
CASW_Button_Area *pEndButton = NULL;
while ((pEndButton = dynamic_cast<CASW_Button_Area *>(gEntList.FindEntityByClassname(pEndButton, "trigger_asw_button_area"))))
{
if (!V_stricmp(STRING(pEndButton->m_szPanelPropName), "elevator_pc"))
{
CBaseEntityOutput *pOutput = pEndButton->FindNamedOutput("OnButtonHackCompleted");
Assert(pOutput);
if (pOutput)
{
pOutput->ParseEventAction("asw_tech_marine_req,DisableTechMarineReq,,0,1");
}
break;
}
}
}
// Fixes the tech marine requirement never being turned off after the last hack.
if (!V_stricmp(pszMap, "dc3-search_and_rescue"))
{
CASW_Button_Area *pC4PlantedButton = dynamic_cast<CASW_Button_Area *>(gEntList.FindEntityByName(NULL, "c4_planted_button"));
Assert(pC4PlantedButton);
if (pC4PlantedButton)
{
CBaseEntityOutput *pOutput = pC4PlantedButton->FindNamedOutput("OnButtonHackCompleted");
Assert(pOutput);
if (pOutput)
{
pOutput->ParseEventAction("asw_tech_marine_req,DisableTechMarineReq,,0,1");
}
}
}
// Fixes maps before the brutal update assuming there would always be exactly 4 difficulty levels.
bool bShouldFixSkillLevels = true;
CASW_Base_Spawner *pSpawner = NULL;
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_spawner"))) != NULL)
{
bShouldFixSkillLevels = bShouldFixSkillLevels && pSpawner->m_iMaxSkillLevel < 5;
}
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_holdout_spawner"))) != NULL)
{
bShouldFixSkillLevels = bShouldFixSkillLevels && pSpawner->m_iMaxSkillLevel < 5;
}
if (bShouldFixSkillLevels)
{
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_spawner"))) != NULL)
{
if (pSpawner->m_iMaxSkillLevel == 4)
pSpawner->m_iMaxSkillLevel = 5;
}
while ((pSpawner = dynamic_cast<CASW_Base_Spawner *>(gEntList.FindEntityByClassname(pSpawner, "asw_holdout_spawner"))) != NULL)
{
if (pSpawner->m_iMaxSkillLevel == 4)
pSpawner->m_iMaxSkillLevel = 5;
}
}
// Fixes maps without marine hints being confusing for marines. The hints are added in ai_initutils.cpp.
Assert( MarineHintManager() );
if ( MarineHintManager() && MarineHintManager()->m_LastResortHints.Count() )
{
CUtlVector<HintData_t *> &hints = MarineHintManager()->m_LastResortHints;
FOR_EACH_VEC_BACK( hints, i )
{
HintData_t *pHint = hints[i];
Assert( pHint );
Assert( g_pBigAINet );
int nNode = g_pBigAINet->NearestNodeToPoint( pHint->m_vecPosition, false );
CAI_Node *pNode = g_pBigAINet->GetNode( nNode );
Assert( pNode );
bool bAccessible = false;
if ( pNode )
{
// We consider nodes "accessible" if a marine can walk from there to any other node.
FOR_EACH_VEC( pNode->m_Links, j )
{
if ( pNode->m_Links[j]->m_iAcceptedMoveTypes[HULL_HUMAN] & bits_CAP_MOVE_GROUND )
{
bAccessible = true;
break;
}
}
}
if ( !bAccessible )
{
hints.FastRemove( i );
delete pHint;
}
}
if ( hints.Count() * asw_follow_ignore_hints.GetFloat() > MarineHintManager()->m_Hints.Count() )
{
// We have less than 10% marine hints. The mapper either forgot to add hints or added a few and forgot about it. Use the nodes instead.
MarineHintManager()->m_Hints.AddVectorToTail( hints );
hints.Purge();
// Reset the indices because we may have removed some from the middle.
FOR_EACH_VEC( MarineHintManager()->m_Hints, i )
{
MarineHintManager()->m_Hints[i]->m_nHintIndex = i;
}
}
else
{
hints.PurgeAndDeleteElements();
}
}
}
};
static CASW_Campaign_Fixes g_CampaignFixes;<|endoftext|> |
<commit_before>#include <wx/url.h>
#include <wx/log.h>
#include <wx/intl.h>
#include <wx/tokenzr.h>
#include <wx/listimpl.cpp>
#include <wx/utils.h>
#include "main.h"
#include "listserverhandler.h"
WX_DEFINE_LIST(ServerList);
void ListServerHandler::GetServerList() {
wxBusyCursor wait;
BZLauncherApp& app = wxGetApp();
app.SetStatusText(_("Fetching data from list-server..."));
this->ClearList();
if( this->GetListServerResponse() ) {
app.SetStatusText(_("Parsing data from list-server..."));
wxStringTokenizer tok(this->rawResponse, _T("\r\n"));
while(tok.HasMoreTokens()) {
wxString token = tok.GetNextToken();
this->ParseLine(token);
}
}
else {
wxLogError(_("Can't connect to listserver!"));
}
app.SetStatusText(wxString::Format(_("Found %d server(s)"), this->serverList.GetCount()));
}
bool ListServerHandler::ParseLine(const wxString& line) {
Server* s = new Server;
wxStringTokenizer tok(line, _T(" "));
int i = 0;
while(tok.HasMoreTokens()) {
wxString token = tok.GetNextToken();
switch(i) {
case 0:
s->serverHostPort = token;
break;
case 1:
s->protocolVersion = token;
// We only parse BZFS0026 for now
if( token.Cmp(_T("BZFS0026")) != 0 )
return false;
break;
case 2:
s->ParseServerInfo(token);
break;
case 3:
s->ip.Hostname(token);
// Get remaining stuff
s->name += tok.GetString();
break;
}
i++;
}
this->serverList.Append(s);
return true;
}
bool ListServerHandler::GetListServerResponse() {
wxURL listserv(wxT("http://my.bzflag.org/db?action=LIST"));
if(listserv.IsOk()) {
wxInputStream *in_stream;
in_stream = listserv.GetInputStream();
char buffer[1024];
this->rawResponse.Clear();
while(!in_stream->Read(buffer,1024).Eof())
this->rawResponse << wxString::From8BitData(buffer,in_stream->LastRead());
return true;
}
return false;
}
void ListServerHandler::ClearList() {
ServerList::iterator i;
for(i = this->serverList.begin(); i != this->serverList.end(); ++i) {
Server* current = *i;
delete current;
}
this->serverList.Clear();
}
<commit_msg>Clear selected server, everytime the server-list is refreshed (to avoid dangling pointers)<commit_after>#include <wx/url.h>
#include <wx/log.h>
#include <wx/intl.h>
#include <wx/tokenzr.h>
#include <wx/listimpl.cpp>
#include <wx/utils.h>
#include "main.h"
#include "listserverhandler.h"
WX_DEFINE_LIST(ServerList);
void ListServerHandler::GetServerList() {
wxBusyCursor wait;
BZLauncherApp& app = wxGetApp();
app.SetStatusText(_("Fetching data from list-server..."));
this->ClearList();
if( this->GetListServerResponse() ) {
app.SetStatusText(_("Parsing data from list-server..."));
wxStringTokenizer tok(this->rawResponse, _T("\r\n"));
while(tok.HasMoreTokens()) {
wxString token = tok.GetNextToken();
this->ParseLine(token);
}
}
else {
wxLogError(_("Can't connect to listserver!"));
}
app.SetStatusText(wxString::Format(_("Found %d server(s)"), this->serverList.GetCount()));
}
bool ListServerHandler::ParseLine(const wxString& line) {
Server* s = new Server;
wxStringTokenizer tok(line, _T(" "));
int i = 0;
while(tok.HasMoreTokens()) {
wxString token = tok.GetNextToken();
switch(i) {
case 0:
s->serverHostPort = token;
break;
case 1:
s->protocolVersion = token;
// We only parse BZFS0026 for now
if( token.Cmp(_T("BZFS0026")) != 0 )
return false;
break;
case 2:
s->ParseServerInfo(token);
break;
case 3:
s->ip.Hostname(token);
// Get remaining stuff
s->name += tok.GetString();
break;
}
i++;
}
this->serverList.Append(s);
return true;
}
bool ListServerHandler::GetListServerResponse() {
wxURL listserv(wxT("http://my.bzflag.org/db?action=LIST"));
if(listserv.IsOk()) {
wxInputStream *in_stream;
in_stream = listserv.GetInputStream();
char buffer[1024];
this->rawResponse.Clear();
while(!in_stream->Read(buffer,1024).Eof())
this->rawResponse << wxString::From8BitData(buffer,in_stream->LastRead());
return true;
}
return false;
}
void ListServerHandler::ClearList() {
BZLauncherApp& app = wxGetApp();
app.SetSelectedServer(NULL);
ServerList::iterator i;
for(i = this->serverList.begin(); i != this->serverList.end(); ++i) {
Server* current = *i;
delete current;
}
this->serverList.Clear();
}
<|endoftext|> |
<commit_before>/*
* Simple cache model for predicting miss rates.
*
* By Eric Anger <[email protected]>
*/
#include <algorithm>
#include <iterator>
#include "byfl.h"
namespace bytesflops {}
using namespace bytesflops;
using namespace std;
class Cache {
public:
void access(uint64_t baseaddr, uint64_t numaddrs);
Cache(uint64_t line_size) : line_size_{line_size}, accesses_{0} {}
uint64_t getAccesses() const { return accesses_; }
vector<uint64_t> getHits() const { return hits_; }
private:
vector<uint64_t> lines_; // back is mru, front is lru
uint64_t line_size_;
uint64_t accesses_;
vector<uint64_t> hits_; // back is lru, front is mru
};
void Cache::access(uint64_t baseaddr, uint64_t numaddrs){
uint64_t num_accesses = 0; // running total of number of lines accessed
for(uint64_t addr = baseaddr / line_size_ * line_size_;
addr <= (baseaddr + numaddrs ) / line_size_ * line_size_;
addr += line_size_){
++num_accesses;
auto line = lines_.rbegin();
auto hit = begin(hits_);
bool found = false;
for(; line != lines_.rend(); ++line, ++hit){
if(addr == *line){
found = true;
transform(hit, end(hits_), hit,
[=](const uint64_t cur_hits){return cur_hits + 1;});
// erase the line pointed to by this reverse iterator. see
// stackoverflow.com/questions/1830158/how-to-call-erase-with-a-reverse-iterator
lines_.erase((line + 1).base());
break;
}
}
if(!found){
// make a new entry containing all previous hits plus any that occur
// this time
hits_.push_back(accesses_ + num_accesses);
}
// move up this address to mru position
lines_.push_back(addr);
}
// we've made all our accesses
++accesses_;
}
static Cache* cache = NULL;
namespace bytesflops{
void initialize_cache(void){
cache = new Cache(bf_line_size);
}
// Access the cache model with this address.
void bf_touch_cache(uint64_t baseaddr, uint64_t numaddrs){
cache->access(baseaddr, numaddrs);
}
// Get cache accesses
uint64_t bf_get_cache_accesses(void){
return cache->getAccesses();
}
// Get cache hits
vector<uint64_t> bf_get_cache_hits(void){
return cache->getHits();
}
} // namespace bytesflops
<commit_msg>Increment total accesses with the number of distinct cache lines requested.<commit_after>/*
* Simple cache model for predicting miss rates.
*
* By Eric Anger <[email protected]>
*/
#include <algorithm>
#include <iterator>
#include "byfl.h"
namespace bytesflops {}
using namespace bytesflops;
using namespace std;
class Cache {
public:
void access(uint64_t baseaddr, uint64_t numaddrs);
Cache(uint64_t line_size) : line_size_{line_size}, accesses_{0} {}
uint64_t getAccesses() const { return accesses_; }
vector<uint64_t> getHits() const { return hits_; }
private:
vector<uint64_t> lines_; // back is mru, front is lru
uint64_t line_size_;
uint64_t accesses_;
vector<uint64_t> hits_; // back is lru, front is mru
};
void Cache::access(uint64_t baseaddr, uint64_t numaddrs){
uint64_t num_accesses = 0; // running total of number of lines accessed
for(uint64_t addr = baseaddr / line_size_ * line_size_;
addr <= (baseaddr + numaddrs ) / line_size_ * line_size_;
addr += line_size_){
++num_accesses;
auto line = lines_.rbegin();
auto hit = begin(hits_);
bool found = false;
for(; line != lines_.rend(); ++line, ++hit){
if(addr == *line){
found = true;
transform(hit, end(hits_), hit,
[=](const uint64_t cur_hits){return cur_hits + 1;});
// erase the line pointed to by this reverse iterator. see
// stackoverflow.com/questions/1830158/how-to-call-erase-with-a-reverse-iterator
lines_.erase((line + 1).base());
break;
}
}
if(!found){
// make a new entry containing all previous hits plus any that occur
// this time
hits_.push_back(accesses_ + num_accesses);
}
// move up this address to mru position
lines_.push_back(addr);
}
// we've made all our accesses
accesses_ += num_accesses;
}
static Cache* cache = NULL;
namespace bytesflops{
void initialize_cache(void){
cache = new Cache(bf_line_size);
}
// Access the cache model with this address.
void bf_touch_cache(uint64_t baseaddr, uint64_t numaddrs){
cache->access(baseaddr, numaddrs);
}
// Get cache accesses
uint64_t bf_get_cache_accesses(void){
return cache->getAccesses();
}
// Get cache hits
vector<uint64_t> bf_get_cache_hits(void){
return cache->getHits();
}
} // namespace bytesflops
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both syscoind and syscoin-qt, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Syscoin Core");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
std::string FormatDashVersion()
{
return DASH_VERSION;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/syscoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
<commit_msg>fix build.h include<commit_after>// Copyright (c) 2012-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both syscoind and syscoin-qt, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Syscoin Core");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include <obj/build.h>
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
std::string FormatDashVersion()
{
return DASH_VERSION;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/syscoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "reports/ReportBuilder.h"
#include "reports/JoinedQueryTableReport.h"
#include "reports/CTRByPositionReport.h"
#include "reports/CTRCounterMerge.h"
#include "reports/CTRCounterSSTableSink.h"
#include "reports/CTRCounterSSTableSource.h"
using namespace fnord;
using namespace cm;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"artifacts",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
fnord::fts::Analyzer analyzer(flags.getString("conf"));
cm::ReportBuilder report_builder;
Set<uint64_t> generations { };
/* find all generations */
auto dir = flags.getString("artifacts");
FileUtil::ls(dir, [&generations] (const String& file) -> bool {
String prefix = "dawanda_joined_queries.";
if (StringUtil::beginsWith(file, prefix)) {
generations.emplace(std::stoul(file.substr(prefix.length())));
}
return true;
});
uint64_t min_gen = std::numeric_limits<uint64_t>::max();
uint64_t max_gen = std::numeric_limits<uint64_t>::min();
for (const auto g : generations) {
if (g < min_gen) {
min_gen = g;
}
if (g > max_gen) {
max_gen = g;
}
}
/* dawanda -- MAP: input joined queries */
for (const auto& g : generations) {
auto jq_report = new JoinedQueryTableReport(Set<String> {
StringUtil::format("$0/dawanda_joined_queries.$1.sstable", dir, g) });
report_builder.addReport(jq_report);
auto ctr_by_posi_report = new CTRByPositionReport(ItemEligibility::ALL);
ctr_by_posi_report->addReport(new CTRCounterSSTableSink(
StringUtil::format("$0/dawanda_ctr_by_position.$1.sstable", dir, g)));
jq_report->addReport(ctr_by_posi_report);
}
/* dawanda -- REDUCE: rollup ctr_by_position */
if (generations.size() > 0) {
Set<String> ctr_posi_sources;
for (const auto& g : generations) {
ctr_posi_sources.emplace(
StringUtil::format("$0/dawanda_ctr_by_position.$1.sstable", dir, g));
}
auto ctr_posi_rollup_in = new CTRCounterSSTableSource(ctr_posi_sources);
report_builder.addReport(ctr_posi_rollup_in);
auto ctr_posi_rollup = new CTRCounterMerge();
ctr_posi_rollup->addReport(new CTRCounterSSTableSink(
StringUtil::format(
"$0/dawanda_ctr_by_position_merged.$1-$1.sstable",
dir,
min_gen,
max_gen)));
ctr_posi_rollup_in->addReport(ctr_posi_rollup);
}
report_builder.buildAll();
return 0;
}
<commit_msg>enqueue all generations<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "reports/ReportBuilder.h"
#include "reports/JoinedQueryTableReport.h"
#include "reports/CTRByPositionReport.h"
#include "reports/CTRCounterMerge.h"
#include "reports/CTRCounterSSTableSink.h"
#include "reports/CTRCounterSSTableSource.h"
using namespace fnord;
using namespace cm;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"artifacts",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
fnord::fts::Analyzer analyzer(flags.getString("conf"));
cm::ReportBuilder report_builder;
auto dir = flags.getString("artifacts");
Set<uint64_t> generations;
auto now = WallClock::unixMicros();
auto gen_window = kMicrosPerSecond * 3600 * 4;
for (uint64_t i = 0; i < kMicrosPerDay * 32; i += gen_window) {
generations.emplace((now - i) / gen_window);
}
uint64_t min_gen = std::numeric_limits<uint64_t>::max();
uint64_t max_gen = std::numeric_limits<uint64_t>::min();
for (const auto g : generations) {
if (g < min_gen) {
min_gen = g;
}
if (g > max_gen) {
max_gen = g;
}
}
/* dawanda -- MAP: input joined queries */
for (const auto& g : generations) {
auto jq_report = new JoinedQueryTableReport(Set<String> {
StringUtil::format("$0/dawanda_joined_queries.$1.sstable", dir, g) });
report_builder.addReport(jq_report);
auto ctr_by_posi_report = new CTRByPositionReport(ItemEligibility::ALL);
ctr_by_posi_report->addReport(new CTRCounterSSTableSink(
StringUtil::format("$0/dawanda_ctr_by_position.$1.sstable", dir, g)));
jq_report->addReport(ctr_by_posi_report);
}
/* dawanda -- REDUCE: rollup ctr_by_position */
if (generations.size() > 0) {
Set<String> ctr_posi_sources;
for (const auto& g : generations) {
ctr_posi_sources.emplace(
StringUtil::format("$0/dawanda_ctr_by_position.$1.sstable", dir, g));
}
auto ctr_posi_rollup_in = new CTRCounterSSTableSource(ctr_posi_sources);
report_builder.addReport(ctr_posi_rollup_in);
auto ctr_posi_rollup = new CTRCounterMerge();
ctr_posi_rollup->addReport(new CTRCounterSSTableSink(
StringUtil::format(
"$0/dawanda_ctr_by_position_merged.$1-$1.sstable",
dir,
min_gen,
max_gen)));
ctr_posi_rollup_in->addReport(ctr_posi_rollup);
}
report_builder.buildAll();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "master_util.h"
#include <sstream>
#include <sys/utsname.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include <gflags/gflags.h>
#include <logging.h>
#include "proto/galaxy.pb.h"
#include "proto/master.pb.h"
DECLARE_string(master_port);
namespace baidu {
namespace galaxy {
std::string MasterUtil::UUID() {
boost::uuids::uuid uuid = boost::uuids::random_generator()();
return boost::lexical_cast<std::string>(uuid);
}
void MasterUtil::AddResource(const Resource& from, Resource* to) {
to->set_millicores(to->millicores() + from.millicores());
to->set_memory(to->memory() + from.memory());
}
void MasterUtil::SubstractResource(const Resource& from, Resource* to) {
assert(FitResource(from, *to));
to->set_millicores(to->millicores() - from.millicores());
to->set_memory(to->memory() - from.memory());
}
bool MasterUtil::FitResource(const Resource& from, const Resource& to) {
if (to.millicores() < from.millicores()) {
return false;
}
if (to.memory() < from.memory()) {
return false;
}
// TODO: check port & disk & ssd
return true;
}
std::string MasterUtil::SelfEndpoint() {
std::string hostname = "";
struct utsname buf;
if (0 != uname(&buf)) {
*buf.nodename = '\0';
}
hostname = buf.nodename;
return hostname + ":" + FLAGS_master_port;
}
void MasterUtil::TraceJobDesc(const JobDescriptor& job_desc) {
LOG(INFO, "job descriptor: \"%s\", "
"replica:%d, "
"deploy_step:%d",
job_desc.name().c_str(),
job_desc.replica(),
job_desc.deploy_step()
);
LOG(INFO, "pod descriptor mem:%ld, cpu:%d, port_size:%d",
job_desc.pod().requirement().memory(),
job_desc.pod().requirement().millicores(),
job_desc.pod().requirement().ports_size());
for (int i = 0; i < job_desc.pod().tasks_size(); i++) {
const TaskDescriptor& task_desc = job_desc.pod().tasks(i);
LOG(INFO, "job[%s]:task[%d] descriptor: "
"start_cmd: \"%s\", stop_cmd: \"%s\", binary_size:%d, mem:%ld, cpu:%d ",
job_desc.name().c_str(),
i,
task_desc.start_command().c_str(),
task_desc.stop_command().c_str(),
task_desc.binary().size(),
task_desc.requirement().memory(),
task_desc.requirement().millicores()
);
}
}
void MasterUtil::SetDiff(const std::set<std::string>& left_set,
const std::set<std::string>& right_set,
std::set<std::string>* left_diff,
std::set<std::string>* right_diff) {
if (left_diff == NULL || right_diff == NULL) {
LOG(WARNING, "set diff error for input NULL");
return;
}
if (left_set.size() == 0) {
*right_diff = right_set;
return;
}
if (right_set.size() == 0) {
*left_diff = left_set;
return;
}
std::set<std::string>::iterator it_left = left_set.begin();
std::set<std::string>::iterator it_right = right_set.begin();
while (it_left != left_set.end()
&& it_right != right_set.end()) {
if (*it_left == *it_right) {
++it_left;
++it_right;
} else if (*it_left > *it_right) {
right_diff->insert(*it_right);
++it_right;
} else {
left_diff->insert(*it_left);
++it_left;
}
}
for (; it_left != left_set.end(); ++it_left) {
left_diff->insert(*it_left);
}
for (; it_right != right_set.end(); ++it_right) {
right_diff->insert(*it_right);
}
return;
}
void MasterUtil::ResetLabels(AgentInfo* agent,
const std::set<std::string>& labels) {
if (agent == NULL) {
return;
}
agent->clear_tags();
std::set<std::string>::iterator it = labels.begin();
for (; it != labels.end(); ++it) {
agent->add_tags(*it);
}
return;
}
}
}
<commit_msg>update uuid generator<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "master_util.h"
#include <sstream>
#include <sys/utsname.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include <gflags/gflags.h>
#include <logging.h>
#include "proto/galaxy.pb.h"
#include "proto/master.pb.h"
DECLARE_string(master_port);
namespace baidu {
namespace galaxy {
static boost::uuids::random_generator gen;
std::string MasterUtil::UUID() {
boost::uuids::uuid uuid = gen();
return boost::lexical_cast<std::string>(uuid);
}
void MasterUtil::AddResource(const Resource& from, Resource* to) {
to->set_millicores(to->millicores() + from.millicores());
to->set_memory(to->memory() + from.memory());
}
void MasterUtil::SubstractResource(const Resource& from, Resource* to) {
assert(FitResource(from, *to));
to->set_millicores(to->millicores() - from.millicores());
to->set_memory(to->memory() - from.memory());
}
bool MasterUtil::FitResource(const Resource& from, const Resource& to) {
if (to.millicores() < from.millicores()) {
return false;
}
if (to.memory() < from.memory()) {
return false;
}
// TODO: check port & disk & ssd
return true;
}
std::string MasterUtil::SelfEndpoint() {
std::string hostname = "";
struct utsname buf;
if (0 != uname(&buf)) {
*buf.nodename = '\0';
}
hostname = buf.nodename;
return hostname + ":" + FLAGS_master_port;
}
void MasterUtil::TraceJobDesc(const JobDescriptor& job_desc) {
LOG(INFO, "job descriptor: \"%s\", "
"replica:%d, "
"deploy_step:%d",
job_desc.name().c_str(),
job_desc.replica(),
job_desc.deploy_step()
);
LOG(INFO, "pod descriptor mem:%ld, cpu:%d, port_size:%d",
job_desc.pod().requirement().memory(),
job_desc.pod().requirement().millicores(),
job_desc.pod().requirement().ports_size());
for (int i = 0; i < job_desc.pod().tasks_size(); i++) {
const TaskDescriptor& task_desc = job_desc.pod().tasks(i);
LOG(INFO, "job[%s]:task[%d] descriptor: "
"start_cmd: \"%s\", stop_cmd: \"%s\", binary_size:%d, mem:%ld, cpu:%d ",
job_desc.name().c_str(),
i,
task_desc.start_command().c_str(),
task_desc.stop_command().c_str(),
task_desc.binary().size(),
task_desc.requirement().memory(),
task_desc.requirement().millicores()
);
}
}
void MasterUtil::SetDiff(const std::set<std::string>& left_set,
const std::set<std::string>& right_set,
std::set<std::string>* left_diff,
std::set<std::string>* right_diff) {
if (left_diff == NULL || right_diff == NULL) {
LOG(WARNING, "set diff error for input NULL");
return;
}
if (left_set.size() == 0) {
*right_diff = right_set;
return;
}
if (right_set.size() == 0) {
*left_diff = left_set;
return;
}
std::set<std::string>::iterator it_left = left_set.begin();
std::set<std::string>::iterator it_right = right_set.begin();
while (it_left != left_set.end()
&& it_right != right_set.end()) {
if (*it_left == *it_right) {
++it_left;
++it_right;
} else if (*it_left > *it_right) {
right_diff->insert(*it_right);
++it_right;
} else {
left_diff->insert(*it_left);
++it_left;
}
}
for (; it_left != left_set.end(); ++it_left) {
left_diff->insert(*it_left);
}
for (; it_right != right_set.end(); ++it_right) {
right_diff->insert(*it_right);
}
return;
}
void MasterUtil::ResetLabels(AgentInfo* agent,
const std::set<std::string>& labels) {
if (agent == NULL) {
return;
}
agent->clear_tags();
std::set<std::string>::iterator it = labels.begin();
for (; it != labels.end(); ++it) {
agent->add_tags(*it);
}
return;
}
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "global.h"
GlobalDBItem globalDBItems[] = {
{ "_gravity", "-9.8", false, StateDatabase::Locked},
{ "_worldSize", "800.0", false, StateDatabase::Locked},
{ "_tankLength", "6.0", false, StateDatabase::Locked},
{ "_tankWidth", "2.8", false, StateDatabase::Locked},
{ "_tankHeight", "2.05", false, StateDatabase::Locked},
{ "_tankRadius", "0.72 * _tankLength", false, StateDatabase::Locked},
{ "_muzzleHeight", "1.57", false, StateDatabase::Locked},
{ "_muzzleFront", "_tankRadius + 0.1", false, StateDatabase::Locked},
{ "_tankSpeed", "25.0", false, StateDatabase::Locked},
{ "_tankAngVel", "0.785398", false, StateDatabase::Locked},
{ "_shotSpeed", "100.0", false, StateDatabase::Locked},
{ "_shotRange", "350.0", false, StateDatabase::Locked},
{ "_reloadTime", "_shotRange / _shotSpeed", false, StateDatabase::Locked},
{ "_explodeTime", "5.0", false, StateDatabase::Locked},
{ "_teleportTime", "1.0", false, StateDatabase::Locked},
{ "_flagAltitude", "11.0", false, StateDatabase::Locked},
{ "_flagRadius", "2.5", false, StateDatabase::Locked},
{ "_velocityAd", "1.5", false, StateDatabase::Locked},
{ "_angularAd", "1.5", false, StateDatabase::Locked},
{ "_rFireAdVel", "1.5", false, StateDatabase::Locked},
{ "_rFireAdRate", "2.0", false, StateDatabase::Locked},
{ "_rFireAdLife", "1.0 / _rFireAdRate", false, StateDatabase::Locked},
{ "_mGunAdVel", "1.5", false, StateDatabase::Locked},
{ "_mGunAdRate", "10.0", false, StateDatabase::Locked},
{ "_mGunAdLife", "1.0 / _mGunAdRate", false, StateDatabase::Locked},
{ "_laserAdVel", "1000.0", false, StateDatabase::Locked},
{ "_laserAdRate", "0.5", false, StateDatabase::Locked},
{ "_laserAdLife", "0.1", false, StateDatabase::Locked},
{ "_gMissileAng", "0.628319", false, StateDatabase::Locked},
{ "_tinyFactor", "0.4", false, StateDatabase::Locked},
{ "_shieldFlight", "2.7", false, StateDatabase::Locked},
{ "_srRadiusMult", "2.0", false, StateDatabase::Locked},
{ "_shockAdLife", "0.2", false, StateDatabase::Locked},
{ "_shockInRadius", "_tankLength", false, StateDatabase::Locked},
{ "_shockOutRadius", "60.0", false, StateDatabase::Locked},
{ "_jumpVelocity", "19.0", false, StateDatabase::Locked},
{ "_identifyRange", "50.0", false, StateDatabase::Locked},
{ "_obeseFactor", "2.5", false, StateDatabase::Locked},
{ "_wideAngleAng", "1.745329", false, StateDatabase::Locked},
{ "_thiefVelAd", "1.67", false, StateDatabase::Locked},
{ "_thiefTinyFactor", "0.5", false, StateDatabase::Locked},
{ "_thiefAdShotVel", "10.0", false, StateDatabase::Locked},
{ "_thiefAdLife", "0.05", false, StateDatabase::Locked},
{ "_thiefAdRate", "10.0", false, StateDatabase::Locked},
{ "_momentumLinAcc", "1.0", false, StateDatabase::Locked},
{ "_momentumAngAcc", "1.0", false, StateDatabase::Locked},
{ "_burrowDepth", "-1.32", false, StateDatabase::Locked},
{ "_burrowSpeedAd", "0.75", false, StateDatabase::Locked},
{ "_burrowAngularAd", "0.33", false, StateDatabase::Locked},
{ "_lRAdRate", "0.5", false, StateDatabase::Locked},
{ "_lockOnAngle", "0.15", false, StateDatabase::Locked},
{ "_targetingAngle", "0.3", false, StateDatabase::Locked},
{ "_flagHeight", "10.0", false, StateDatabase::Locked},
{ "_wallHeight", "3.0*_tankHeight", false, StateDatabase::Locked},
{ "_boxHeight", "6.0*_muzzleHeight", false, StateDatabase::Locked},
{ "_pyrBase", "4.0*_tankHeight", false, StateDatabase::Locked},
{ "_pyrHeight", "5.0*_tankHeight", false, StateDatabase::Locked},
};
<commit_msg>thief should shoot a lil shorter, with faster reload<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "global.h"
GlobalDBItem globalDBItems[] = {
{ "_gravity", "-9.8", false, StateDatabase::Locked},
{ "_worldSize", "800.0", false, StateDatabase::Locked},
{ "_tankLength", "6.0", false, StateDatabase::Locked},
{ "_tankWidth", "2.8", false, StateDatabase::Locked},
{ "_tankHeight", "2.05", false, StateDatabase::Locked},
{ "_tankRadius", "0.72 * _tankLength", false, StateDatabase::Locked},
{ "_muzzleHeight", "1.57", false, StateDatabase::Locked},
{ "_muzzleFront", "_tankRadius + 0.1", false, StateDatabase::Locked},
{ "_tankSpeed", "25.0", false, StateDatabase::Locked},
{ "_tankAngVel", "0.785398", false, StateDatabase::Locked},
{ "_shotSpeed", "100.0", false, StateDatabase::Locked},
{ "_shotRange", "350.0", false, StateDatabase::Locked},
{ "_reloadTime", "_shotRange / _shotSpeed", false, StateDatabase::Locked},
{ "_explodeTime", "5.0", false, StateDatabase::Locked},
{ "_teleportTime", "1.0", false, StateDatabase::Locked},
{ "_flagAltitude", "11.0", false, StateDatabase::Locked},
{ "_flagRadius", "2.5", false, StateDatabase::Locked},
{ "_velocityAd", "1.5", false, StateDatabase::Locked},
{ "_angularAd", "1.5", false, StateDatabase::Locked},
{ "_rFireAdVel", "1.5", false, StateDatabase::Locked},
{ "_rFireAdRate", "2.0", false, StateDatabase::Locked},
{ "_rFireAdLife", "1.0 / _rFireAdRate", false, StateDatabase::Locked},
{ "_mGunAdVel", "1.5", false, StateDatabase::Locked},
{ "_mGunAdRate", "10.0", false, StateDatabase::Locked},
{ "_mGunAdLife", "1.0 / _mGunAdRate", false, StateDatabase::Locked},
{ "_laserAdVel", "1000.0", false, StateDatabase::Locked},
{ "_laserAdRate", "0.5", false, StateDatabase::Locked},
{ "_laserAdLife", "0.1", false, StateDatabase::Locked},
{ "_gMissileAng", "0.628319", false, StateDatabase::Locked},
{ "_tinyFactor", "0.4", false, StateDatabase::Locked},
{ "_shieldFlight", "2.7", false, StateDatabase::Locked},
{ "_srRadiusMult", "2.0", false, StateDatabase::Locked},
{ "_shockAdLife", "0.2", false, StateDatabase::Locked},
{ "_shockInRadius", "_tankLength", false, StateDatabase::Locked},
{ "_shockOutRadius", "60.0", false, StateDatabase::Locked},
{ "_jumpVelocity", "19.0", false, StateDatabase::Locked},
{ "_identifyRange", "50.0", false, StateDatabase::Locked},
{ "_obeseFactor", "2.5", false, StateDatabase::Locked},
{ "_wideAngleAng", "1.745329", false, StateDatabase::Locked},
{ "_thiefVelAd", "1.67", false, StateDatabase::Locked},
{ "_thiefTinyFactor", "0.5", false, StateDatabase::Locked},
{ "_thiefAdShotVel", "8.0", false, StateDatabase::Locked},
{ "_thiefAdLife", "0.05", false, StateDatabase::Locked},
{ "_thiefAdRate", "12.0", false, StateDatabase::Locked},
{ "_momentumLinAcc", "1.0", false, StateDatabase::Locked},
{ "_momentumAngAcc", "1.0", false, StateDatabase::Locked},
{ "_burrowDepth", "-1.32", false, StateDatabase::Locked},
{ "_burrowSpeedAd", "0.75", false, StateDatabase::Locked},
{ "_burrowAngularAd", "0.33", false, StateDatabase::Locked},
{ "_lRAdRate", "0.5", false, StateDatabase::Locked},
{ "_lockOnAngle", "0.15", false, StateDatabase::Locked},
{ "_targetingAngle", "0.3", false, StateDatabase::Locked},
{ "_flagHeight", "10.0", false, StateDatabase::Locked},
{ "_wallHeight", "3.0*_tankHeight", false, StateDatabase::Locked},
{ "_boxHeight", "6.0*_muzzleHeight", false, StateDatabase::Locked},
{ "_pyrBase", "4.0*_tankHeight", false, StateDatabase::Locked},
{ "_pyrHeight", "5.0*_tankHeight", false, StateDatabase::Locked},
};
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_ARRAY_OPS_HPP_INCLUDED
#define OVK_CORE_ARRAY_OPS_HPP_INCLUDED
#include <ovk/core/ArrayTraits.hpp>
#include <ovk/core/ArrayView.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/IteratorTraits.hpp>
#include <ovk/core/Requires.hpp>
#include <type_traits>
#include <utility>
namespace ovk {
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!std::is_const<T>::value
)> void ArrayFill(const array_view<T, Rank, Layout> &View, const T &Value) {
View.Fill(Value);
}
template <typename ArrayType, OVK_FUNCTION_REQUIRES(core::IsArray<ArrayType>())> void ArrayFill(
ArrayType &Array, const core::array_value_type<ArrayType> &Value) {
long long NumValues = core::ArrayCount(Array);
for (long long i = 0; i < NumValues; ++i) {
Array[i] = Value;
}
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!std::is_const<T>::value
)> void ArrayFill(const array_view<T, Rank, Layout> &View, std::initializer_list<T> ValuesList) {
View.Fill(ValuesList);
}
template <typename ArrayType, OVK_FUNCTION_REQUIRES(core::IsArray<ArrayType>())> void ArrayFill(
ArrayType &Array, std::initializer_list<core::array_value_type<ArrayType>> ValuesList) {
long long NumValues = core::ArrayCount(Array);
auto Iter = ValuesList.begin();
for (long long i = 0; i < NumValues; ++i) {
Array[i] = *Iter++;
}
}
template <typename T, int Rank, array_layout Layout, typename IterType, OVK_FUNCTION_REQUIRES(
!std::is_const<T>::value && core::IsInputIterator<IterType>() && std::is_convertible<
core::iterator_reference_type<IterType>, T>::value)> void ArrayFill(const array_view<T, Rank,
Layout> &View, IterType First) {
View.Fill(First);
}
template <typename ArrayType, typename IterType, OVK_FUNCTION_REQUIRES(core::IsArray<ArrayType>() &&
core::IsInputIterator<IterType>() && std::is_convertible<core::iterator_reference_type<IterType>,
core::array_value_type<ArrayType>>::value)> void ArrayFill(ArrayType &Array, IterType First) {
long long NumValues = core::ArrayCount(Array);
IterType Iter = First;
for (long long i = 0; i < NumValues; ++i) {
Array[i] = *Iter++;
}
}
template <typename T, typename U, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(
!std::is_const<T>::value && std::is_convertible<typename std::remove_const<U>::type, T>::value)>
void ArrayFill(const array_view<T, Rank, Layout> &View, const array_view<U, Rank, Layout>
&SourceView) {
View.Fill(SourceView);
}
template <typename ArrayType, typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(
core::IsArray<ArrayType>() && core::ArrayHasFootprint<ArrayType, Rank, Layout>() &&
std::is_convertible<typename std::remove_const<T>::type, core::array_value_type<ArrayType>>::
value)> void ArrayFill(ArrayType &Array, const array_view<T, Rank, Layout> &SourceView) {
long long NumValues = core::ArrayCount(Array);
for (long long i = 0; i < NumValues; ++i) {
Array[i] = SourceView[i];
}
}
template <typename T, int Rank, array_layout Layout, typename SourceArrayRefType,
OVK_FUNCTION_REQUIRES(!std::is_const<T>::value && core::IsArray<core::remove_cvref<
SourceArrayRefType>>() && !core::IsIterator<typename std::decay<SourceArrayRefType>::type>()
&& core::ArrayHasFootprint<core::remove_cvref<SourceArrayRefType>, Rank, Layout>() &&
std::is_convertible<core::array_access_type<SourceArrayRefType &&>, T>::value)> void ArrayFill(
const array_view<T, Rank, Layout> &View, SourceArrayRefType &&SourceArray) {
View.Fill(std::forward<SourceArrayRefType>(SourceArray));
}
template <typename ArrayType, typename SourceArrayRefType, OVK_FUNCTION_REQUIRES(core::IsArray<
ArrayType>() && core::IsArray<core::remove_cvref<SourceArrayRefType>>() && !core::IsIterator<
typename std::decay<SourceArrayRefType>::type>() && core::ArraysAreSimilar<ArrayType,
core::remove_cvref<SourceArrayRefType>>() && std::is_convertible<core::array_access_type<
SourceArrayRefType &&>, core::array_value_type<ArrayType>>::value)> void ArrayFill(ArrayType
&Array, SourceArrayRefType &&SourceArray) {
long long NumValues = core::ArrayCount(Array);
for (long long i = 0; i < NumValues; ++i) {
Array[i] = static_cast<core::array_access_type<SourceArrayRefType &&>>(SourceArray[i]);
}
}
}
#endif
<commit_msg>cosmetic change<commit_after>// Copyright (c) 2019 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_ARRAY_OPS_HPP_INCLUDED
#define OVK_CORE_ARRAY_OPS_HPP_INCLUDED
#include <ovk/core/ArrayTraits.hpp>
#include <ovk/core/ArrayView.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/IteratorTraits.hpp>
#include <ovk/core/Requires.hpp>
#include <type_traits>
#include <utility>
namespace ovk {
template <typename ArrayType, OVK_FUNCTION_REQUIRES(core::IsArray<ArrayType>())> void ArrayFill(
ArrayType &Array, const core::array_value_type<ArrayType> &Value) {
long long NumValues = core::ArrayCount(Array);
for (long long i = 0; i < NumValues; ++i) {
Array[i] = Value;
}
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!std::is_const<T>::value
)> void ArrayFill(const array_view<T, Rank, Layout> &View, const T &Value) {
View.Fill(Value);
}
template <typename ArrayType, OVK_FUNCTION_REQUIRES(core::IsArray<ArrayType>())> void ArrayFill(
ArrayType &Array, std::initializer_list<core::array_value_type<ArrayType>> ValuesList) {
long long NumValues = core::ArrayCount(Array);
auto Iter = ValuesList.begin();
for (long long i = 0; i < NumValues; ++i) {
Array[i] = *Iter++;
}
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!std::is_const<T>::value
)> void ArrayFill(const array_view<T, Rank, Layout> &View, std::initializer_list<T> ValuesList) {
View.Fill(ValuesList);
}
template <typename ArrayType, typename IterType, OVK_FUNCTION_REQUIRES(core::IsArray<ArrayType>() &&
core::IsInputIterator<IterType>() && std::is_convertible<core::iterator_reference_type<IterType>,
core::array_value_type<ArrayType>>::value)> void ArrayFill(ArrayType &Array, IterType First) {
long long NumValues = core::ArrayCount(Array);
IterType Iter = First;
for (long long i = 0; i < NumValues; ++i) {
Array[i] = *Iter++;
}
}
template <typename T, int Rank, array_layout Layout, typename IterType, OVK_FUNCTION_REQUIRES(
!std::is_const<T>::value && core::IsInputIterator<IterType>() && std::is_convertible<
core::iterator_reference_type<IterType>, T>::value)> void ArrayFill(const array_view<T, Rank,
Layout> &View, IterType First) {
View.Fill(First);
}
template <typename ArrayType, typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(
core::IsArray<ArrayType>() && core::ArrayHasFootprint<ArrayType, Rank, Layout>() &&
std::is_convertible<typename std::remove_const<T>::type, core::array_value_type<ArrayType>>::
value)> void ArrayFill(ArrayType &Array, const array_view<T, Rank, Layout> &SourceView) {
long long NumValues = core::ArrayCount(Array);
for (long long i = 0; i < NumValues; ++i) {
Array[i] = SourceView[i];
}
}
template <typename T, typename U, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(
!std::is_const<T>::value && std::is_convertible<typename std::remove_const<U>::type, T>::value)>
void ArrayFill(const array_view<T, Rank, Layout> &View, const array_view<U, Rank, Layout>
&SourceView) {
View.Fill(SourceView);
}
template <typename ArrayType, typename SourceArrayRefType, OVK_FUNCTION_REQUIRES(core::IsArray<
ArrayType>() && core::IsArray<core::remove_cvref<SourceArrayRefType>>() && !core::IsIterator<
typename std::decay<SourceArrayRefType>::type>() && core::ArraysAreSimilar<ArrayType,
core::remove_cvref<SourceArrayRefType>>() && std::is_convertible<core::array_access_type<
SourceArrayRefType &&>, core::array_value_type<ArrayType>>::value)> void ArrayFill(ArrayType
&Array, SourceArrayRefType &&SourceArray) {
long long NumValues = core::ArrayCount(Array);
for (long long i = 0; i < NumValues; ++i) {
Array[i] = static_cast<core::array_access_type<SourceArrayRefType &&>>(SourceArray[i]);
}
}
template <typename T, int Rank, array_layout Layout, typename SourceArrayRefType,
OVK_FUNCTION_REQUIRES(!std::is_const<T>::value && core::IsArray<core::remove_cvref<
SourceArrayRefType>>() && !core::IsIterator<typename std::decay<SourceArrayRefType>::type>()
&& core::ArrayHasFootprint<core::remove_cvref<SourceArrayRefType>, Rank, Layout>() &&
std::is_convertible<core::array_access_type<SourceArrayRefType &&>, T>::value)> void ArrayFill(
const array_view<T, Rank, Layout> &View, SourceArrayRefType &&SourceArray) {
View.Fill(std::forward<SourceArrayRefType>(SourceArray));
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef Q_MOC_RUN
#ifndef MUMBLE_MUMBLE_MUMBLE_PCH_H_
#define MUMBLE_MUMBLE_MUMBLE_PCH_H_
#define QT_NO_CAST_TO_ASCII
#define QT_NO_CAST_FROM_ASCII
#define QT_USE_FAST_CONCATENATION
#define QT_USE_FAST_OPERATOR_PLUS
#define NOMINMAX
#define _WINSOCKAPI_
#define BOOST_TYPEOF_SUPPRESS_UNNAMED_NAMESPACE
#ifdef __APPLE__
#include <Carbon/Carbon.h>
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
#undef nil
#undef check
#undef TYPE_BOOL
#endif
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#if QT_VERSION >= 0x050000
# include "Qt4Compat.h"
# include <QtWidgets/QtWidgets>
#endif
#include <QtSvg/QtSvg>
#ifdef USE_DBUS
#include <QtDBus/QtDBus>
#endif
#include <QtNetwork/QtNetwork>
#include <QtSql/QtSql>
#include <QtXml/QtXml>
#ifdef Q_OS_WIN
#define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1
#endif
#include <sndfile.h>
#include <celt.h>
#ifdef USE_SBCELT
#include <sbcelt.h>
#endif
#include <speex/speex.h>
#include <speex/speex_jitter.h>
#include <speex/speex_preprocess.h>
#include <speex/speex_echo.h>
#include <speex/speex_resampler.h>
#include <boost/array.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/accumulators/statistics/extended_p_square.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/weak_ptr.hpp>
#include <algorithm>
#ifdef Q_OS_WIN
// Qt 5's qnetworksession.h undefs 'interface' (as defined in ObjBase.h on Windows).
// This causes Windows headers that use COM interfaces to break. Internally, it's
// just defined as 'struct', so we'll do that here as well to make things work again
// without too much hassle.
#ifndef interface
#define interface struct
#endif
#include <windows.h>
#include <shellapi.h>
#include <winsock2.h>
#include <qos2.h>
#include <wintrust.h>
#include <Softpub.h>
#include <Dbt.h>
#include <delayimp.h>
#include <shlobj.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <math.h>
#define STACKVAR(type, varname, count) type *varname=reinterpret_cast<type *>(_alloca(sizeof(type) * (count)))
#else // ifndef Q_OS_WIN
#include <math.h>
#define STACKVAR(type, varname, count) type varname[count]
#define CopyMemory(dst,ptr,len) memcpy(dst,ptr,len)
#define ZeroMemory(ptr,len) memset(ptr, 0, len)
#define __cdecl
typedef WId HWND;
#include <arpa/inet.h>
#endif
#if defined(__MMX__) || defined(Q_OS_WIN)
#include <mmintrin.h>
#endif
#define iroundf(x) ( static_cast<int>(x) )
#ifdef USE_BONJOUR
#include <dns_sd.h>
#endif
#ifdef __OBJC__
#define nil 0
#endif
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
#include <openssl/ssl.h>
/* OpenSSL defines set_key. This breaks our protobuf-generated setters. */
#undef set_key
#endif
#endif
<commit_msg>mumble_pch.hpp: add missing networking headers to fix FreeBSD build.<commit_after>#ifndef Q_MOC_RUN
#ifndef MUMBLE_MUMBLE_MUMBLE_PCH_H_
#define MUMBLE_MUMBLE_MUMBLE_PCH_H_
#define QT_NO_CAST_TO_ASCII
#define QT_NO_CAST_FROM_ASCII
#define QT_USE_FAST_CONCATENATION
#define QT_USE_FAST_OPERATOR_PLUS
#define NOMINMAX
#define _WINSOCKAPI_
#define BOOST_TYPEOF_SUPPRESS_UNNAMED_NAMESPACE
#ifdef __APPLE__
#include <Carbon/Carbon.h>
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
#undef nil
#undef check
#undef TYPE_BOOL
#endif
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#if QT_VERSION >= 0x050000
# include "Qt4Compat.h"
# include <QtWidgets/QtWidgets>
#endif
#include <QtSvg/QtSvg>
#ifdef USE_DBUS
#include <QtDBus/QtDBus>
#endif
#include <QtNetwork/QtNetwork>
#include <QtSql/QtSql>
#include <QtXml/QtXml>
#ifdef Q_OS_WIN
#define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1
#endif
#include <sndfile.h>
#include <celt.h>
#ifdef USE_SBCELT
#include <sbcelt.h>
#endif
#include <speex/speex.h>
#include <speex/speex_jitter.h>
#include <speex/speex_preprocess.h>
#include <speex/speex_echo.h>
#include <speex/speex_resampler.h>
#include <boost/array.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/accumulators/statistics/extended_p_square.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/weak_ptr.hpp>
#include <algorithm>
#ifdef Q_OS_WIN
// Qt 5's qnetworksession.h undefs 'interface' (as defined in ObjBase.h on Windows).
// This causes Windows headers that use COM interfaces to break. Internally, it's
// just defined as 'struct', so we'll do that here as well to make things work again
// without too much hassle.
#ifndef interface
#define interface struct
#endif
#include <windows.h>
#include <shellapi.h>
#include <winsock2.h>
#include <qos2.h>
#include <wintrust.h>
#include <Softpub.h>
#include <Dbt.h>
#include <delayimp.h>
#include <shlobj.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <math.h>
#define STACKVAR(type, varname, count) type *varname=reinterpret_cast<type *>(_alloca(sizeof(type) * (count)))
#else // ifndef Q_OS_WIN
#include <math.h>
#define STACKVAR(type, varname, count) type varname[count]
#define CopyMemory(dst,ptr,len) memcpy(dst,ptr,len)
#define ZeroMemory(ptr,len) memset(ptr, 0, len)
#define __cdecl
typedef WId HWND;
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#if defined(__MMX__) || defined(Q_OS_WIN)
#include <mmintrin.h>
#endif
#define iroundf(x) ( static_cast<int>(x) )
#ifdef USE_BONJOUR
#include <dns_sd.h>
#endif
#ifdef __OBJC__
#define nil 0
#endif
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
#include <openssl/ssl.h>
/* OpenSSL defines set_key. This breaks our protobuf-generated setters. */
#undef set_key
#endif
#endif
<|endoftext|> |
<commit_before>#include <algorithm>
#include <stdexcept>
#include <chrono>
#include <vector>
#include <memory>
#include <cmath>
#include <thread>
#include <signal.h>
#include <sched.h>
#include <sys/mman.h>
#include <eeros/core/Executor.hpp>
#include <eeros/task/Async.hpp>
#include <eeros/task/Lambda.hpp>
#include <eeros/task/HarmonicTaskList.hpp>
#include <eeros/control/TimeDomain.hpp>
#include <eeros/safety/SafetySystem.hpp>
#include <ros/callback_queue_interface.h>
#include <ros/callback_queue.h>
volatile bool running = true;
using namespace eeros;
namespace {
using Logger = logger::Logger;
struct TaskThread {
TaskThread(double period, task::Periodic &task, task::HarmonicTaskList tasks) :
taskList(tasks), async(taskList, task.getRealtime(), task.getNice())
{
async.counter.setPeriod(period);
async.counter.monitors = task.monitors;
}
task::HarmonicTaskList taskList;
task::Async async;
};
template < typename F >
void traverse(std::vector<task::Periodic> &tasks, F func) {
for (auto &t: tasks) {
func(&t);
traverse(t.before, func);
traverse(t.after, func);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output);
void createThreads(Logger &log, std::vector<task::Periodic> &tasks, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, task::HarmonicTaskList &output) {
for (task::Periodic &t: tasks) {
createThread(log, t, baseTask, threads, output.tasks);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output) {
int k = static_cast<int>(task.getPeriod() / baseTask.getPeriod());
double actualPeriod = k * baseTask.getPeriod();
double deviation = std::abs(task.getPeriod() - actualPeriod) / task.getPeriod();
task::HarmonicTaskList taskList;
if (task.before.size() > 0) {
createThreads(log, task.before, task, threads, taskList);
}
taskList.add(task.getTask());
if (task.after.size() > 0) {
createThreads(log, task.after, task, threads, taskList);
}
if (task.getRealtime())
log.trace() << "creating harmonic realtime task '" << task.getName()
<< "' with period " << actualPeriod << " sec (k = "
<< k << ") and priority " << (Executor::basePriority - task.getNice())
<< " based on '" << baseTask.getName() << "'";
else
log.trace() << "creating harmonic task '" << task.getName() << "' with period "
<< actualPeriod << " sec (k = " << k << ")"
<< " based on '" << baseTask.getName() << "'";
if (deviation > 0.01) throw std::runtime_error("period deviation too high");
if (task.getRealtime() && task.getNice() <= 0)
throw std::runtime_error("priority not set");
if (taskList.tasks.size() == 0)
throw std::runtime_error("no task to execute");
threads.push_back(std::make_shared<TaskThread>(actualPeriod, task, taskList));
output.emplace_back(threads.back()->async, k);
}
}
Executor::Executor() :
log('E'), period(0), mainTask(nullptr), useRosTime(false), syncWithGazeboIsSet(false) { }
Executor::~Executor() {
}
Executor& Executor::instance() {
static Executor executor;
return executor;
}
#ifdef ECMASTERLIB_FOUND
void Executor::syncWithEtherCATSTack(ethercat::EtherCATMain* etherCATStack) {
this->etherCATStack = etherCATStack;
cv = etherCATStack->getConditionalVariable();
m = etherCATStack->getMutex();
}
#endif
void Executor::setMainTask(task::Periodic &mainTask) {
if (this->mainTask != nullptr)
throw std::runtime_error("you can only define one main task per executor");
period = mainTask.getPeriod();
counter.setPeriod(period);
this->mainTask = &mainTask;
}
void Executor::setMainTask(safety::SafetySystem &ss) {
task::Periodic *task = new task::Periodic("safety system", ss.getPeriod(), ss, true);
setMainTask(*task);
}
void Executor::add(task::Periodic &task) {
tasks.push_back(task);
}
void Executor::add(control::TimeDomain &timedomain) {
task::Periodic task(timedomain.getName().c_str(), timedomain.getPeriod(), timedomain, timedomain.getRealtime());
tasks.push_back(task);
}
void Executor::prefault_stack() {
unsigned char dummy[8*1024] = {};
}
bool Executor::lock_memory() {
return (mlockall(MCL_CURRENT | MCL_FUTURE) != -1);
}
bool Executor::set_priority(int nice) {
struct sched_param schedulingParam;
schedulingParam.sched_priority = (Executor::basePriority - nice);
return (sched_setscheduler(0, SCHED_FIFO, &schedulingParam) != -1);
}
void Executor::stop() {
running = false;
auto &instance = Executor::instance();
#ifdef ECMASTERLIB_FOUND
if(instance.etherCATStack) instance.cv->notify_one();
#endif
}
void Executor::useRosTimeForExecutor() {
useRosTime = true;
}
void Executor::syncWithGazebo(ros::CallbackQueue* syncRosCallbackQueue)
{
std::cout << "sync executor with gazebo" << std::endl;
syncWithGazeboIsSet = true;
this->syncRosCallbackQueue = syncRosCallbackQueue;
}
void Executor::assignPriorities() {
std::vector<task::Periodic*> priorityAssignments;
// add task to list of priority assignments
traverse(tasks, [&priorityAssignments] (task::Periodic *task) {
priorityAssignments.push_back(task);
});
// sort list of priority assignments
std::sort(priorityAssignments.begin(), priorityAssignments.end(), [] (task::Periodic *a, task::Periodic *b) -> bool {
if (a->getRealtime() == b->getRealtime())
return (a->getPeriod() < b->getPeriod());
else
return a->getRealtime();
});
// assign priorities
int nice = 1;
for (auto t: priorityAssignments) {
if (t->getRealtime()) {
t->setNice(nice++);
}
}
}
void Executor::run() {
log.trace() << "starting executor with base period " << period << " sec and priority " << basePriority;
if (period == 0.0)
throw std::runtime_error("period of executor not set");
log.trace() << "assigning priorities";
assignPriorities();
Runnable *mainTask = nullptr;
if (this->mainTask != nullptr) {
mainTask = &this->mainTask->getTask();
log.trace() << "setting '" << this->mainTask->getName() << "' as main task";
}
std::vector<std::shared_ptr<TaskThread>> threads; // smart pointer used because async objects must not be copied
task::HarmonicTaskList taskList;
task::Periodic executorTask("executor", period, this, true);
counter.monitors = this->mainTask->monitors;
createThreads(log, tasks, executorTask, threads, taskList);
using seconds = std::chrono::duration<double, std::chrono::seconds::period>;
// TODO: implement this with ready-flag (wait for all threads to be ready instead of blind sleep)
std::this_thread::sleep_for(seconds(1)); // wait 1 sec to allow threads to be created
if (!set_priority(0))
log.error() << "could not set realtime priority";
prefault_stack();
if (!lock_memory())
log.error() << "could not lock memory in RAM";
bool useDefaultExecutor = true;
#ifdef ECMASTERLIB_FOUND
if (etherCATStack) {
if (useRosTime || syncWithGazeboIsSet) log.error() << "Can't use both etherCAT and RosTime to sync executor";
log.trace() << "starting execution synced to etcherCAT stack";
useDefaultExecutor = false;
while (running) {
std::unique_lock<std::mutex> lk(*m);
cv->wait(lk);
lk.unlock();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
#ifdef ROS_FOUND
if (useRosTime) {
log.trace() << "starting execution synced to rosTime";
useDefaultExecutor = false;
long periodNsec = static_cast<long>(period * 1.0e9);
long next_cycle = ros::Time::now().toNSec()+periodNsec;
// auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
while (ros::Time::now().toNSec() < next_cycle && running) usleep(10);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += periodNsec;
}
}
else if (syncWithGazeboIsSet) {
log.trace() << "starting execution synced to gazebo";
useDefaultExecutor = false;
while (running) {
while (syncRosCallbackQueue->isEmpty() && running) usleep(1);
syncRosCallbackQueue->callAvailable();
ros::getGlobalCallbackQueue()->callAvailable();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
if (useDefaultExecutor) {
log.trace() << "starting periodic execution";
auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
std::this_thread::sleep_until(next_cycle);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += seconds(period);
}
}
log.trace() << "stopping all threads";
for (auto &t: threads)
t->async.stop();
log.trace() << "joining all threads";
for (auto &t: threads)
t->async.join();
log.trace() << "exiting executor";
}
<commit_msg>sync with gazebo now waits for timestamp to change<commit_after>#include <algorithm>
#include <stdexcept>
#include <chrono>
#include <vector>
#include <memory>
#include <cmath>
#include <thread>
#include <signal.h>
#include <sched.h>
#include <sys/mman.h>
#include <eeros/core/Executor.hpp>
#include <eeros/task/Async.hpp>
#include <eeros/task/Lambda.hpp>
#include <eeros/task/HarmonicTaskList.hpp>
#include <eeros/control/TimeDomain.hpp>
#include <eeros/safety/SafetySystem.hpp>
#include <ros/callback_queue_interface.h>
#include <ros/callback_queue.h>
volatile bool running = true;
using namespace eeros;
namespace {
using Logger = logger::Logger;
struct TaskThread {
TaskThread(double period, task::Periodic &task, task::HarmonicTaskList tasks) :
taskList(tasks), async(taskList, task.getRealtime(), task.getNice())
{
async.counter.setPeriod(period);
async.counter.monitors = task.monitors;
}
task::HarmonicTaskList taskList;
task::Async async;
};
template < typename F >
void traverse(std::vector<task::Periodic> &tasks, F func) {
for (auto &t: tasks) {
func(&t);
traverse(t.before, func);
traverse(t.after, func);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output);
void createThreads(Logger &log, std::vector<task::Periodic> &tasks, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, task::HarmonicTaskList &output) {
for (task::Periodic &t: tasks) {
createThread(log, t, baseTask, threads, output.tasks);
}
}
void createThread(Logger &log, task::Periodic &task, task::Periodic &baseTask, std::vector<std::shared_ptr<TaskThread>> &threads, std::vector<task::Harmonic> &output) {
int k = static_cast<int>(task.getPeriod() / baseTask.getPeriod());
double actualPeriod = k * baseTask.getPeriod();
double deviation = std::abs(task.getPeriod() - actualPeriod) / task.getPeriod();
task::HarmonicTaskList taskList;
if (task.before.size() > 0) {
createThreads(log, task.before, task, threads, taskList);
}
taskList.add(task.getTask());
if (task.after.size() > 0) {
createThreads(log, task.after, task, threads, taskList);
}
if (task.getRealtime())
log.trace() << "creating harmonic realtime task '" << task.getName()
<< "' with period " << actualPeriod << " sec (k = "
<< k << ") and priority " << (Executor::basePriority - task.getNice())
<< " based on '" << baseTask.getName() << "'";
else
log.trace() << "creating harmonic task '" << task.getName() << "' with period "
<< actualPeriod << " sec (k = " << k << ")"
<< " based on '" << baseTask.getName() << "'";
if (deviation > 0.01) throw std::runtime_error("period deviation too high");
if (task.getRealtime() && task.getNice() <= 0)
throw std::runtime_error("priority not set");
if (taskList.tasks.size() == 0)
throw std::runtime_error("no task to execute");
threads.push_back(std::make_shared<TaskThread>(actualPeriod, task, taskList));
output.emplace_back(threads.back()->async, k);
}
}
Executor::Executor() :
log('E'), period(0), mainTask(nullptr), useRosTime(false), syncWithGazeboIsSet(false) { }
Executor::~Executor() {
}
Executor& Executor::instance() {
static Executor executor;
return executor;
}
#ifdef ECMASTERLIB_FOUND
void Executor::syncWithEtherCATSTack(ethercat::EtherCATMain* etherCATStack) {
this->etherCATStack = etherCATStack;
cv = etherCATStack->getConditionalVariable();
m = etherCATStack->getMutex();
}
#endif
void Executor::setMainTask(task::Periodic &mainTask) {
if (this->mainTask != nullptr)
throw std::runtime_error("you can only define one main task per executor");
period = mainTask.getPeriod();
counter.setPeriod(period);
this->mainTask = &mainTask;
}
void Executor::setMainTask(safety::SafetySystem &ss) {
task::Periodic *task = new task::Periodic("safety system", ss.getPeriod(), ss, true);
setMainTask(*task);
}
void Executor::add(task::Periodic &task) {
tasks.push_back(task);
}
void Executor::add(control::TimeDomain &timedomain) {
task::Periodic task(timedomain.getName().c_str(), timedomain.getPeriod(), timedomain, timedomain.getRealtime());
tasks.push_back(task);
}
void Executor::prefault_stack() {
unsigned char dummy[8*1024] = {};
}
bool Executor::lock_memory() {
return (mlockall(MCL_CURRENT | MCL_FUTURE) != -1);
}
bool Executor::set_priority(int nice) {
struct sched_param schedulingParam;
schedulingParam.sched_priority = (Executor::basePriority - nice);
return (sched_setscheduler(0, SCHED_FIFO, &schedulingParam) != -1);
}
void Executor::stop() {
running = false;
auto &instance = Executor::instance();
#ifdef ECMASTERLIB_FOUND
if(instance.etherCATStack) instance.cv->notify_one();
#endif
}
void Executor::useRosTimeForExecutor() {
useRosTime = true;
}
void Executor::syncWithGazebo(ros::CallbackQueue* syncRosCallbackQueue)
{
std::cout << "sync executor with gazebo" << std::endl;
syncWithGazeboIsSet = true;
this->syncRosCallbackQueue = syncRosCallbackQueue;
}
void Executor::assignPriorities() {
std::vector<task::Periodic*> priorityAssignments;
// add task to list of priority assignments
traverse(tasks, [&priorityAssignments] (task::Periodic *task) {
priorityAssignments.push_back(task);
});
// sort list of priority assignments
std::sort(priorityAssignments.begin(), priorityAssignments.end(), [] (task::Periodic *a, task::Periodic *b) -> bool {
if (a->getRealtime() == b->getRealtime())
return (a->getPeriod() < b->getPeriod());
else
return a->getRealtime();
});
// assign priorities
int nice = 1;
for (auto t: priorityAssignments) {
if (t->getRealtime()) {
t->setNice(nice++);
}
}
}
void Executor::run() {
log.trace() << "starting executor with base period " << period << " sec and priority " << basePriority;
if (period == 0.0)
throw std::runtime_error("period of executor not set");
log.trace() << "assigning priorities";
assignPriorities();
Runnable *mainTask = nullptr;
if (this->mainTask != nullptr) {
mainTask = &this->mainTask->getTask();
log.trace() << "setting '" << this->mainTask->getName() << "' as main task";
}
std::vector<std::shared_ptr<TaskThread>> threads; // smart pointer used because async objects must not be copied
task::HarmonicTaskList taskList;
task::Periodic executorTask("executor", period, this, true);
counter.monitors = this->mainTask->monitors;
createThreads(log, tasks, executorTask, threads, taskList);
using seconds = std::chrono::duration<double, std::chrono::seconds::period>;
// TODO: implement this with ready-flag (wait for all threads to be ready instead of blind sleep)
std::this_thread::sleep_for(seconds(1)); // wait 1 sec to allow threads to be created
if (!set_priority(0))
log.error() << "could not set realtime priority";
prefault_stack();
if (!lock_memory())
log.error() << "could not lock memory in RAM";
bool useDefaultExecutor = true;
#ifdef ECMASTERLIB_FOUND
if (etherCATStack) {
if (useRosTime || syncWithGazeboIsSet) log.error() << "Can't use both etherCAT and RosTime to sync executor";
log.trace() << "starting execution synced to etcherCAT stack";
useDefaultExecutor = false;
while (running) {
std::unique_lock<std::mutex> lk(*m);
cv->wait(lk);
lk.unlock();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
#ifdef ROS_FOUND
if (useRosTime) {
log.trace() << "starting execution synced to rosTime";
useDefaultExecutor = false;
long periodNsec = static_cast<long>(period * 1.0e9);
long next_cycle = ros::Time::now().toNSec()+periodNsec;
// auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
while (ros::Time::now().toNSec() < next_cycle && running) usleep(10);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += periodNsec;
}
}
else if (syncWithGazeboIsSet) {
log.trace() << "starting execution synced to gazebo";
useDefaultExecutor = false;
auto timeOld = ros::Time::now();
auto timeNew = ros::Time::now();
static bool first = true;
while (running) {
while (syncRosCallbackQueue->isEmpty() && running) usleep(1);
timeNew = ros::Time::now();
if (!first) {
while (timeOld == timeNew) {
usleep(1); // waits for new rosTime beeing published
timeNew = ros::Time::now();
}
}
timeOld = timeNew;
syncRosCallbackQueue->callAvailable();
ros::getGlobalCallbackQueue()->callAvailable();
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
}
}
#endif
if (useDefaultExecutor) {
log.trace() << "starting periodic execution";
auto next_cycle = std::chrono::steady_clock::now() + seconds(period);
while (running) {
std::this_thread::sleep_until(next_cycle);
counter.tick();
taskList.run();
if (mainTask != nullptr)
mainTask->run();
counter.tock();
next_cycle += seconds(period);
}
}
log.trace() << "stopping all threads";
for (auto &t: threads)
t->async.stop();
log.trace() << "joining all threads";
for (auto &t: threads)
t->async.join();
log.trace() << "exiting executor";
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2009-2010, Piotr Korzuszek
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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 "RemoteCar.h"
#include "math/Float.h"
namespace Net
{
const int PASS_TIME = 500;
class RemoteCarImpl
{
public:
// To preserve lags, there are two car instances.
// The old one is car physics situated when car position didn't change.
// The new one is car physics forced by remote player.
//
// When new packet is received only the new car is positioned at new
// place and moving from one position to another is made step by step
// to make things smooth.
Race::Car m_phantomCar;
// Smooth pass float
// 0.0 is old car, 1.0 is new car
Math::Float m_passFloat;
mutable CL_Pointf m_pos;
mutable CL_Angle m_rot;
};
RemoteCar::RemoteCar() :
m_impl(new RemoteCarImpl())
{
// empty
}
RemoteCar::~RemoteCar()
{
// empty
}
void RemoteCar::update(unsigned int p_elapsedMS)
{
Car::update(p_elapsedMS);
m_impl->m_passFloat.update(p_elapsedMS);
const float newCarRatio = m_impl->m_passFloat.get();
if (fabs(newCarRatio - 1.0f) > 0.01) {
m_impl->m_phantomCar.update(p_elapsedMS);
}
}
void RemoteCar::deserialize(const CL_NetGameEvent &p_data)
{
CL_NetGameEvent ev("");
serialize(&ev);
m_impl->m_phantomCar.deserialize(ev);
Car::deserialize(p_data);
// start passing
m_impl->m_passFloat.animate(0.0f, 1.0f, PASS_TIME);
}
const CL_Pointf& RemoteCar::getPosition() const
{
const CL_Pointf &thisPos = Car::getPosition();
const float newCarRatio = m_impl->m_passFloat.get();
if (fabs(newCarRatio - 1.0f) > 0.01) {
const CL_Pointf &phanPos = m_impl->m_phantomCar.getPosition();
const CL_Vec2f delta = (thisPos - phanPos) * newCarRatio;
m_impl->m_pos = phanPos + delta;
return m_impl->m_pos;
}
return thisPos;
}
const CL_Angle &RemoteCar::getCorpseAngle() const
{
const CL_Angle &thisAngle = Car::getCorpseAngle();
// const float newCarRatio = m_impl->m_passFloat.get();
//
// if (fabs(newCarRatio - 1.0f) > 0.01) {
// const CL_Angle &phanAngle = m_impl->m_phantomCar.getCorpseAngle();
//
// const CL_Angle delta = (thisAngle - phanAngle) * newCarRatio;
// m_impl->m_rot = phanAngle + delta;
//
// return m_impl->m_rot;
// }
return thisAngle;
}
}
<commit_msg>Fix RemoteCar<commit_after>/*
* Copyright (c) 2009-2010, Piotr Korzuszek
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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 "RemoteCar.h"
#include "math/Float.h"
namespace Net
{
const int PASS_TIME = 250;
class RemoteCarImpl
{
public:
// To preserve lags, there are two car instances.
// The old one is car physics situated when car position didn't change.
// The new one is car physics forced by remote player.
//
// When new packet is received only the new car is positioned at new
// place and moving from one position to another is made step by step
// to make things smooth.
Race::Car m_phantomCar;
// Smooth pass float
// 0.0 is old car, 1.0 is new car
Math::Float m_passFloat;
mutable CL_Pointf m_pos;
mutable CL_Angle m_rot;
};
RemoteCar::RemoteCar() :
m_impl(new RemoteCarImpl())
{
// empty
}
RemoteCar::~RemoteCar()
{
// empty
}
void RemoteCar::update(unsigned int p_elapsedMS)
{
Car::update(p_elapsedMS);
m_impl->m_phantomCar.update(p_elapsedMS);
m_impl->m_passFloat.update(p_elapsedMS);
}
void RemoteCar::deserialize(const CL_NetGameEvent &p_data)
{
CL_NetGameEvent ev("");
serialize(&ev);
m_impl->m_phantomCar.deserialize(ev);
Car::deserialize(p_data);
// start passing
m_impl->m_passFloat.animate(0.0f, 1.0f, PASS_TIME);
}
const CL_Pointf& RemoteCar::getPosition() const
{
const CL_Pointf &thisPos = Car::getPosition();
const float newCarRatio = m_impl->m_passFloat.get();
if (fabs(newCarRatio - 1.0f) > 0.01) {
const CL_Pointf &phanPos = m_impl->m_phantomCar.getPosition();
const CL_Vec2f delta = (thisPos - phanPos) * newCarRatio;
m_impl->m_pos = phanPos + delta;
return m_impl->m_pos;
}
return thisPos;
}
const CL_Angle &RemoteCar::getCorpseAngle() const
{
const CL_Angle &thisAngle = Car::getCorpseAngle();
const float newCarRatio = m_impl->m_passFloat.get();
if (fabs(newCarRatio - 1.0f) > 0.01) {
const CL_Angle &phanAngle = m_impl->m_phantomCar.getCorpseAngle();
const CL_Angle delta = (thisAngle - phanAngle) * newCarRatio;
m_impl->m_rot = phanAngle + delta;
return m_impl->m_rot;
}
return thisAngle;
}
}
<|endoftext|> |
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[email protected]>
//
// 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 <nvtt/nvtt.h>
#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>
#include <nvimage/BlockDXT.h>
#include <nvimage/ColorBlock.h>
#include <nvcore/Ptr.h>
#include <nvcore/Debug.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/TextWriter.h>
#include <stdlib.h> // free
#include <string.h> // memcpy
#include <time.h> // clock
using namespace nv;
static const char * s_fileNames[] = {
// Kodak image set
"kodim01.png",
"kodim02.png",
"kodim03.png",
"kodim04.png",
"kodim05.png",
"kodim06.png",
"kodim07.png",
"kodim08.png",
"kodim09.png",
"kodim10.png",
"kodim11.png",
"kodim12.png",
"kodim13.png",
"kodim14.png",
"kodim15.png",
"kodim16.png",
"kodim17.png",
"kodim18.png",
"kodim19.png",
"kodim20.png",
"kodim21.png",
"kodim22.png",
"kodim23.png",
"kodim24.png",
// Waterloo image set
"clegg.png",
"frymire.png",
"lena.png",
"monarch.png",
"peppers.png",
"sail.png",
"serrano.png",
"tulips.png",
// Epic image set
"Bradley1.png",
"Gradient.png",
"MoreRocks.png",
"Wall.png",
"Rainbow.png",
"Text.png",
};
const int s_fileCount = sizeof(s_fileNames)/sizeof(s_fileNames[0]);
struct MyOutputHandler : public nvtt::OutputHandler
{
MyOutputHandler() : m_data(NULL), m_ptr(NULL) {}
~MyOutputHandler()
{
free(m_data);
}
virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)
{
m_size = size;
m_width = width;
m_height = height;
free(m_data);
m_data = (unsigned char *)malloc(size);
m_ptr = m_data;
}
virtual bool writeData(const void * data, int size)
{
memcpy(m_ptr, data, size);
m_ptr += size;
return true;
}
Image * decompress(nvtt::Format format)
{
int bw = (m_width + 3) / 4;
int bh = (m_height + 3) / 4;
AutoPtr<Image> img( new Image() );
img->allocate(m_width, m_height);
if (format == nvtt::Format_BC1)
{
BlockDXT1 * block = (BlockDXT1 *)m_data;
for (int y = 0; y < bh; y++)
{
for (int x = 0; x < bw; x++)
{
ColorBlock colors;
block->decodeBlock(&colors);
for (int yy = 0; yy < 4; yy++)
{
for (int xx = 0; xx < 4; xx++)
{
Color32 c = colors.color(xx, yy);
if (x * 4 + xx < m_width && y * 4 + yy < m_height)
{
img->pixel(x * 4 + xx, y * 4 + yy) = c;
}
}
}
block++;
}
}
}
return img.release();
}
int m_size;
int m_width;
int m_height;
unsigned char * m_data;
unsigned char * m_ptr;
};
float rmsError(const Image * a, const Image * b)
{
nvCheck(a != NULL);
nvCheck(b != NULL);
nvCheck(a->width() == b->width());
nvCheck(a->height() == b->height());
float mse = 0;
const uint count = a->width() * a->height();
for (uint i = 0; i < count; i++)
{
Color32 c0 = a->pixel(i);
Color32 c1 = b->pixel(i);
int r = c0.r - c1.r;
int g = c0.g - c1.g;
int b = c0.b - c1.b;
//int a = c0.a - c1.a;
mse += r * r;
mse += g * g;
mse += b * b;
}
mse /= count;
return sqrtf(mse);
}
int main(int argc, char *argv[])
{
const uint version = nvtt::version();
const uint major = version / 100;
const uint minor = version % 100;
printf("NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007 - 2008\n\n", major, minor);
bool fast = false;
bool nocuda = false;
bool showHelp = false;
const char * outPath = "output";
const char * regressPath = NULL;
// Parse arguments.
for (int i = 1; i < argc; i++)
{
if (strcmp("-fast", argv[i]) == 0)
{
fast = true;
}
else if (strcmp("-nocuda", argv[i]) == 0)
{
nocuda = true;
}
else if (strcmp("-help", argv[i]) == 0)
{
showHelp = true;
}
else if (strcmp("-out", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') outPath = argv[i+1];
}
else if (strcmp("-regress", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') regressPath = argv[i+1];
}
}
if (showHelp)
{
printf("usage: nvtestsuite [options]\n\n");
printf("Input options:\n");
printf(" -regress <path>\tRegression directory.\n");
printf("Compression options:\n");
printf(" -fast \tFast compression.\n");
printf(" -nocuda \tDo not use cuda compressor.\n");
printf("Output options:\n");
printf(" -out <path> \tOutput directory.\n");
return 1;
}
nvtt::InputOptions inputOptions;
inputOptions.setMipmapGeneration(false);
nvtt::CompressionOptions compressionOptions;
compressionOptions.setFormat(nvtt::Format_BC1);
if (fast)
{
compressionOptions.setQuality(nvtt::Quality_Fastest);
}
else
{
compressionOptions.setQuality(nvtt::Quality_Production);
}
nvtt::OutputOptions outputOptions;
outputOptions.setOutputHeader(false);
MyOutputHandler outputHandler;
outputOptions.setOutputHandler(&outputHandler);
nvtt::Compressor compressor;
compressor.enableCudaAcceleration(!nocuda);
// @@ Create outPath.
Path csvFileName("%s/result.csv", outPath);
StdOutputStream csvStream(csvFileName);
TextWriter csvWriter(&csvStream);
float totalTime = 0;
float totalRMS = 0;
int failedTests = 0;
float totalDiff = 0;
for (int i = 0; i < s_fileCount; i++)
{
AutoPtr<Image> img( new Image() );
if (!img->load(s_fileNames[i]))
{
printf("Input image '%s' not found.\n", s_fileNames[i]);
return EXIT_FAILURE;
}
inputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());
inputOptions.setMipmapData(img->pixels(), img->width(), img->height());
printf("Compressing: \t'%s'\n", s_fileNames[i]);
clock_t start = clock();
compressor.process(inputOptions, compressionOptions, outputOptions);
clock_t end = clock();
printf(" Time: \t%.3f sec\n", float(end-start) / CLOCKS_PER_SEC);
totalTime += float(end-start);
AutoPtr<Image> img_out( outputHandler.decompress(nvtt::Format_BC1) );
Path outputFileName("%s/%s", outPath, s_fileNames[i]);
outputFileName.stripExtension();
outputFileName.append(".tga");
if (!ImageIO::save(outputFileName, img_out.ptr()))
{
printf("Error saving file '%s'.\n", outputFileName.str());
}
float rms = rmsError(img.ptr(), img_out.ptr());
totalRMS += rms;
printf(" RMS: \t%.4f\n", rms);
// Output csv file
csvWriter << "\"" << s_fileNames[i] << "\"," << rms << "\n";
if (regressPath != NULL)
{
Path regressFileName("%s/%s", regressPath, s_fileNames[i]);
regressFileName.stripExtension();
regressFileName.append(".tga");
AutoPtr<Image> img_reg( new Image() );
if (!img_reg->load(regressFileName.str()))
{
printf("Regression image '%s' not found.\n", regressFileName.str());
return EXIT_FAILURE;
}
float rms_reg = rmsError(img.ptr(), img_reg.ptr());
float diff = rms_reg - rms;
totalDiff += diff;
const char * text = "PASSED";
if (equal(diff, 0)) text = "PASSED";
else if (diff < 0) {
text = "FAILED";
failedTests++;
}
printf(" Diff: \t%.4f (%s)\n", diff, text);
}
fflush(stdout);
}
totalRMS /= s_fileCount;
totalDiff /= s_fileCount;
printf("Total Results:\n");
printf(" Total Time: \t%.3f sec\n", totalTime / CLOCKS_PER_SEC);
printf(" Average RMS:\t%.4f\n", totalRMS);
if (regressPath != NULL)
{
printf("Regression Results:\n");
printf(" Diff: %.4f\n", totalDiff);
printf(" %d/%d tests failed.\n", failedTests, s_fileCount);
}
return EXIT_SUCCESS;
}
<commit_msg>Create output directory.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[email protected]>
//
// 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 <nvtt/nvtt.h>
#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>
#include <nvimage/BlockDXT.h>
#include <nvimage/ColorBlock.h>
#include <nvcore/Ptr.h>
#include <nvcore/Debug.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/TextWriter.h>
#include <nvcore/FileSystem.h>
#include <stdlib.h> // free
#include <string.h> // memcpy
#include <time.h> // clock
using namespace nv;
static const char * s_fileNames[] = {
// Kodak image set
"kodim01.png",
"kodim02.png",
"kodim03.png",
"kodim04.png",
"kodim05.png",
"kodim06.png",
"kodim07.png",
"kodim08.png",
"kodim09.png",
"kodim10.png",
"kodim11.png",
"kodim12.png",
"kodim13.png",
"kodim14.png",
"kodim15.png",
"kodim16.png",
"kodim17.png",
"kodim18.png",
"kodim19.png",
"kodim20.png",
"kodim21.png",
"kodim22.png",
"kodim23.png",
"kodim24.png",
// Waterloo image set
"clegg.png",
"frymire.png",
"lena.png",
"monarch.png",
"peppers.png",
"sail.png",
"serrano.png",
"tulips.png",
// Epic image set
"Bradley1.png",
"Gradient.png",
"MoreRocks.png",
"Wall.png",
"Rainbow.png",
"Text.png",
};
const int s_fileCount = sizeof(s_fileNames)/sizeof(s_fileNames[0]);
struct MyOutputHandler : public nvtt::OutputHandler
{
MyOutputHandler() : m_data(NULL), m_ptr(NULL) {}
~MyOutputHandler()
{
free(m_data);
}
virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)
{
m_size = size;
m_width = width;
m_height = height;
free(m_data);
m_data = (unsigned char *)malloc(size);
m_ptr = m_data;
}
virtual bool writeData(const void * data, int size)
{
memcpy(m_ptr, data, size);
m_ptr += size;
return true;
}
Image * decompress(nvtt::Format format)
{
int bw = (m_width + 3) / 4;
int bh = (m_height + 3) / 4;
AutoPtr<Image> img( new Image() );
img->allocate(m_width, m_height);
if (format == nvtt::Format_BC1)
{
BlockDXT1 * block = (BlockDXT1 *)m_data;
for (int y = 0; y < bh; y++)
{
for (int x = 0; x < bw; x++)
{
ColorBlock colors;
block->decodeBlock(&colors);
for (int yy = 0; yy < 4; yy++)
{
for (int xx = 0; xx < 4; xx++)
{
Color32 c = colors.color(xx, yy);
if (x * 4 + xx < m_width && y * 4 + yy < m_height)
{
img->pixel(x * 4 + xx, y * 4 + yy) = c;
}
}
}
block++;
}
}
}
return img.release();
}
int m_size;
int m_width;
int m_height;
unsigned char * m_data;
unsigned char * m_ptr;
};
float rmsError(const Image * a, const Image * b)
{
nvCheck(a != NULL);
nvCheck(b != NULL);
nvCheck(a->width() == b->width());
nvCheck(a->height() == b->height());
float mse = 0;
const uint count = a->width() * a->height();
for (uint i = 0; i < count; i++)
{
Color32 c0 = a->pixel(i);
Color32 c1 = b->pixel(i);
int r = c0.r - c1.r;
int g = c0.g - c1.g;
int b = c0.b - c1.b;
//int a = c0.a - c1.a;
mse += r * r;
mse += g * g;
mse += b * b;
}
mse /= count;
return sqrtf(mse);
}
int main(int argc, char *argv[])
{
const uint version = nvtt::version();
const uint major = version / 100;
const uint minor = version % 100;
printf("NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007 - 2008\n\n", major, minor);
bool fast = false;
bool nocuda = false;
bool showHelp = false;
const char * outPath = "output";
const char * regressPath = NULL;
// Parse arguments.
for (int i = 1; i < argc; i++)
{
if (strcmp("-fast", argv[i]) == 0)
{
fast = true;
}
else if (strcmp("-nocuda", argv[i]) == 0)
{
nocuda = true;
}
else if (strcmp("-help", argv[i]) == 0)
{
showHelp = true;
}
else if (strcmp("-out", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') outPath = argv[i+1];
}
else if (strcmp("-regress", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') regressPath = argv[i+1];
}
}
if (showHelp)
{
printf("usage: nvtestsuite [options]\n\n");
printf("Input options:\n");
printf(" -regress <path>\tRegression directory.\n");
printf("Compression options:\n");
printf(" -fast \tFast compression.\n");
printf(" -nocuda \tDo not use cuda compressor.\n");
printf("Output options:\n");
printf(" -out <path> \tOutput directory.\n");
return 1;
}
nvtt::InputOptions inputOptions;
inputOptions.setMipmapGeneration(false);
nvtt::CompressionOptions compressionOptions;
compressionOptions.setFormat(nvtt::Format_BC1);
if (fast)
{
compressionOptions.setQuality(nvtt::Quality_Fastest);
}
else
{
compressionOptions.setQuality(nvtt::Quality_Production);
}
nvtt::OutputOptions outputOptions;
outputOptions.setOutputHeader(false);
MyOutputHandler outputHandler;
outputOptions.setOutputHandler(&outputHandler);
nvtt::Compressor compressor;
compressor.enableCudaAcceleration(!nocuda);
FileSystem::createDirectory(outPath);
Path csvFileName("%s/result.csv", outPath);
StdOutputStream csvStream(csvFileName);
TextWriter csvWriter(&csvStream);
float totalTime = 0;
float totalRMS = 0;
int failedTests = 0;
float totalDiff = 0;
for (int i = 0; i < s_fileCount; i++)
{
AutoPtr<Image> img( new Image() );
if (!img->load(s_fileNames[i]))
{
printf("Input image '%s' not found.\n", s_fileNames[i]);
return EXIT_FAILURE;
}
inputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());
inputOptions.setMipmapData(img->pixels(), img->width(), img->height());
printf("Compressing: \t'%s'\n", s_fileNames[i]);
clock_t start = clock();
compressor.process(inputOptions, compressionOptions, outputOptions);
clock_t end = clock();
printf(" Time: \t%.3f sec\n", float(end-start) / CLOCKS_PER_SEC);
totalTime += float(end-start);
AutoPtr<Image> img_out( outputHandler.decompress(nvtt::Format_BC1) );
Path outputFileName("%s/%s", outPath, s_fileNames[i]);
outputFileName.stripExtension();
outputFileName.append(".tga");
if (!ImageIO::save(outputFileName, img_out.ptr()))
{
printf("Error saving file '%s'.\n", outputFileName.str());
}
float rms = rmsError(img.ptr(), img_out.ptr());
totalRMS += rms;
printf(" RMS: \t%.4f\n", rms);
// Output csv file
csvWriter << "\"" << s_fileNames[i] << "\"," << rms << "\n";
if (regressPath != NULL)
{
Path regressFileName("%s/%s", regressPath, s_fileNames[i]);
regressFileName.stripExtension();
regressFileName.append(".tga");
AutoPtr<Image> img_reg( new Image() );
if (!img_reg->load(regressFileName.str()))
{
printf("Regression image '%s' not found.\n", regressFileName.str());
return EXIT_FAILURE;
}
float rms_reg = rmsError(img.ptr(), img_reg.ptr());
float diff = rms_reg - rms;
totalDiff += diff;
const char * text = "PASSED";
if (equal(diff, 0)) text = "PASSED";
else if (diff < 0) {
text = "FAILED";
failedTests++;
}
printf(" Diff: \t%.4f (%s)\n", diff, text);
}
fflush(stdout);
}
totalRMS /= s_fileCount;
totalDiff /= s_fileCount;
printf("Total Results:\n");
printf(" Total Time: \t%.3f sec\n", totalTime / CLOCKS_PER_SEC);
printf(" Average RMS:\t%.4f\n", totalRMS);
if (regressPath != NULL)
{
printf("Regression Results:\n");
printf(" Diff: %.4f\n", totalDiff);
printf(" %d/%d tests failed.\n", failedTests, s_fileCount);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/// \file uparser.cc
#include <sdk/config.h> // YYDEBUG.
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <cassert>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <libport/foreach.hh>
#include <ast/nary.hh>
#include <ast/print.hh>
#include <parser/parser-impl.hh>
#include <parser/parser-utils.hh>
#include <parser/tweast.hh>
#include <parser/utoken.hh>
#include <kernel/server-timer.hh>
namespace parser
{
/*-------------.
| ParserImpl. |
`-------------*/
ParserImpl::ParserImpl()
: tweast_(0),
loc_(),
synclines_(),
result_(0),
debug_(!!getenv("YYDEBUG"))
{
}
void
ParserImpl::parse_(std::istream& source)
{
TIMER_PUSH("parse");
// Set up result_.
passert(*result_, !result_.get());
result_.reset(new ParseResult);
// Set up scanner.
yyFlexLexer scanner;
scanner.switch_streams(&source, 0);
// Set up parser.
parser_type p(*this, scanner);
#if defined YYDEBUG && YYDEBUG
p.set_debug_level(debug_);
#endif
// Parse.
if (debug_)
LIBPORT_ECHO("====================== Parse begin");
result_->status = p.parse();
if (debug_)
LIBPORT_ECHO("====================== Parse end:" << std::endl
<< *result_);
TIMER_POP("parse");
}
parse_result_type
ParserImpl::parse(const std::string& s)
{
if (debug_)
LIBPORT_ECHO("Parsing: " << s);
std::istringstream is(s);
parse_(is);
if (debug_)
LIBPORT_ECHO("Result: " << *result_);
return result_;
}
parse_result_type
ParserImpl::parse(Tweast& t)
{
// Recursive calls are forbidden. If we want to relax this
// constraint, note that we also need to save and restore other
// member changed during the parsing, such as warnings_ and
// errors_. But it is simpler to recurse with the standalone
// parse functions.
passert(tweast_, !tweast_);
tweast_ = &t;
std::istringstream is(t.input_get());
parse_(is);
tweast_ = 0;
return result_;
}
parse_result_type
ParserImpl::parse_file(const std::string& fn)
{
std::ifstream f(fn.c_str());
if (!f.good())
{
// Return an error instead of creating a valid empty ast.
result_.reset(new ParseResult);
result_->status = 1;
}
else
{
// A location pointing to it.
location_type loc;
loc.initialize(new libport::Symbol(fn));
// Exchange with the current location so that we can restore it
// afterwards (when reading the input flow, we want to be able to
// restore the cursor after having handled a load command).
std::swap(loc, loc_);
ECHO("Parsing file: " << fn);
parse_(f);
std::swap(loc, loc_);
}
return result_;
}
void
ParserImpl::error(const location_type& l, const std::string& msg)
{
result_->error(l, msg);
}
void
ParserImpl::warn(const location_type& l, const std::string& msg)
{
result_->warn(l, msg);
}
}
<commit_msg>Do not use passert if the evaluation of the subject triggers abortion.<commit_after>/// \file uparser.cc
#include <sdk/config.h> // YYDEBUG.
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <cassert>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <libport/foreach.hh>
#include <ast/nary.hh>
#include <ast/print.hh>
#include <parser/parser-impl.hh>
#include <parser/parser-utils.hh>
#include <parser/tweast.hh>
#include <parser/utoken.hh>
#include <kernel/server-timer.hh>
namespace parser
{
/*-------------.
| ParserImpl. |
`-------------*/
ParserImpl::ParserImpl()
: tweast_(0),
loc_(),
synclines_(),
result_(0),
debug_(!!getenv("YYDEBUG"))
{
}
void
ParserImpl::parse_(std::istream& source)
{
TIMER_PUSH("parse");
// Set up result_.
// FIXME: This check will evaluate (void)*result_ in NDEBUG,
// entailing an abortion since result_ == 0. Passert should
// probably be fixed.
// passert(*result_, !result_.get());
result_.reset(new ParseResult);
// Set up scanner.
yyFlexLexer scanner;
scanner.switch_streams(&source, 0);
// Set up parser.
parser_type p(*this, scanner);
#if defined YYDEBUG && YYDEBUG
p.set_debug_level(debug_);
#endif
// Parse.
if (debug_)
LIBPORT_ECHO("====================== Parse begin");
result_->status = p.parse();
if (debug_)
LIBPORT_ECHO("====================== Parse end:" << std::endl
<< *result_);
TIMER_POP("parse");
}
parse_result_type
ParserImpl::parse(const std::string& s)
{
if (debug_)
LIBPORT_ECHO("Parsing: " << s);
std::istringstream is(s);
parse_(is);
if (debug_)
LIBPORT_ECHO("Result: " << *result_);
return result_;
}
parse_result_type
ParserImpl::parse(Tweast& t)
{
// Recursive calls are forbidden. If we want to relax this
// constraint, note that we also need to save and restore other
// member changed during the parsing, such as warnings_ and
// errors_. But it is simpler to recurse with the standalone
// parse functions.
passert(tweast_, !tweast_);
tweast_ = &t;
std::istringstream is(t.input_get());
parse_(is);
tweast_ = 0;
return result_;
}
parse_result_type
ParserImpl::parse_file(const std::string& fn)
{
std::ifstream f(fn.c_str());
if (!f.good())
{
// Return an error instead of creating a valid empty ast.
result_.reset(new ParseResult);
result_->status = 1;
}
else
{
// A location pointing to it.
location_type loc;
loc.initialize(new libport::Symbol(fn));
// Exchange with the current location so that we can restore it
// afterwards (when reading the input flow, we want to be able to
// restore the cursor after having handled a load command).
std::swap(loc, loc_);
ECHO("Parsing file: " << fn);
parse_(f);
std::swap(loc, loc_);
}
return result_;
}
void
ParserImpl::error(const location_type& l, const std::string& msg)
{
result_->error(l, msg);
}
void
ParserImpl::warn(const location_type& l, const std::string& msg)
{
result_->warn(l, msg);
}
}
<|endoftext|> |
<commit_before>
/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#ifdef HAVE_SDL
#include <stdlib.h>
#include <string>
#include "SDLMedia.h"
#include "ErrorHandler.h"
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// SDLMedia
//
SDLMedia::SDLMedia() : BzfMedia()
{
cmdFill = 0;
audioReady = false;
}
double SDLMedia::stopwatch(bool start)
{
Uint32 currentTick = SDL_GetTicks(); //msec
if (start) {
stopwatchTime = currentTick;
return 0.0;
}
if (currentTick >= stopwatchTime)
return (double) (currentTick - stopwatchTime) * 0.001; // sec
else
//Clock is wrapped : happens after 49 days
//Should be "wrap value" - stopwatchtime. Now approx.
return (double) currentTick * 0.001;
}
bool SDLMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
printFatalError("Could not initialize SDL-Audio: %s.\n", SDL_GetError());
exit(-1);
};
static SDL_AudioSpec desired;
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
// probably SDL is using multiple buffering, make it a 3rd
int fragmentSize = (int)(0.03f * (float)audioOutputRate);
int n;
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each so double the size
audioBufferSize = 1 << (n + 1);
desired.freq = audioOutputRate;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = audioBufferSize >> 1; // In stereo samples
desired.callback = &fillAudioWrapper;
desired.userdata = (void *) this; // To handle Wrap of func
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&desired, NULL) < 0) {
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
return false;
}
// make an output buffer
outputBuffer = new short[audioBufferSize];
// ready to go
audioReady = true;
return true;
}
void SDLMedia::closeAudio()
{
// Stop Audio to avoid callback
SDL_PauseAudio(1);
SDL_CloseAudio();
delete [] outputBuffer;
outputBuffer = 0;
SDL_QuitSubSystem(SDL_INIT_AUDIO);
audioReady = false;
}
void SDLMedia::startAudioCallback(bool (*proc)(void))
{
userCallback = proc;
// Stop sending silence and start calling audio callback
SDL_PauseAudio(0);
}
void SDLMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
SDL_LockAudio();
// Discard command if full
if ((cmdFill + len) < 2048) {
memcpy(&cmdQueue[cmdFill], cmd, len);
// We should awake audioSleep - but game become unplayable
// using here an SDL_CondSignal(wakeCond)
cmdFill += len;
}
SDL_UnlockAudio();
}
bool SDLMedia::readSoundCommand(void* cmd, int len)
{
bool result = false;
if (cmdFill >= len) {
memcpy(cmd, cmdQueue, len);
// repack list of command waiting to be processed
memmove(cmdQueue, &cmdQueue[len], cmdFill - len);
cmdFill -= len;
result = true;
}
return result;
}
int SDLMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int SDLMedia::getAudioBufferSize() const
{
return audioBufferSize;
}
int SDLMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
void SDLMedia::fillAudio (Uint8 * stream, int len)
{
userCallback();
Uint8* soundBuffer = stream;
int transferSize = (audioBufferSize - sampleToSend) * 2;
if (transferSize > len)
transferSize = len;
// just copying into the soundBuffer is enough, SDL is looking for
// something different from silence sample
memcpy(soundBuffer,
(Uint8 *) &outputBuffer[sampleToSend],
transferSize);
sampleToSend += transferSize / 2;
soundBuffer += transferSize;
len -= transferSize;
}
void SDLMedia::fillAudioWrapper (void * userdata, Uint8 * stream, int len)
{
SDLMedia * me = (SDLMedia *) userdata;
me->fillAudio(stream, len);
};
void SDLMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
while (numSamples > 0) {
if (numSamples>audioBufferSize)
limit=audioBufferSize;
else
limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0)
outputBuffer[j] = -32767;
else
if (samples[j] > 32767.0)
outputBuffer[j] = 32767;
else
outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
}
sampleToSend = 0;
samples += audioBufferSize;
numSamples -= audioBufferSize;
}
}
// Setting Audio Driver
void SDLMedia::setDriver(std::string driverName) {
static char envAssign[256];
std::string envVar = "SDL_AUDIODRIVER=" + driverName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
// Setting Audio Device
void SDLMedia::setDevice(std::string deviceName) {
static char envAssign[256];
std::string envVar = "SDL_PATH_DSP=" + deviceName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
float* SDLMedia::doReadSound(const std::string &filename, int &numFrames,
int &rate) const
{
SDL_AudioSpec wav_spec;
Uint32 wav_length;
Uint8 *wav_buffer;
int ret;
SDL_AudioCVT wav_cvt;
int16_t *cvt16;
int i;
float *data = NULL;
rate = defaultAudioRate;
if (SDL_LoadWAV(filename.c_str(), &wav_spec, &wav_buffer, &wav_length)) {
/* Build AudioCVT */
ret = SDL_BuildAudioCVT(&wav_cvt,
wav_spec.format, wav_spec.channels, wav_spec.freq,
AUDIO_S16SYS, 2, defaultAudioRate);
/* Check that the convert was built */
if (ret == -1) {
printFatalError("Could not build converter for Wav file %s: %s.\n",
filename.c_str(), SDL_GetError());
} else {
/* Setup for conversion */
wav_cvt.buf = (Uint8*)malloc(wav_length * wav_cvt.len_mult);
wav_cvt.len = wav_length;
memcpy(wav_cvt.buf, wav_buffer, wav_length);
/* And now we're ready to convert */
SDL_ConvertAudio(&wav_cvt);
numFrames = (int)(wav_length * wav_cvt.len_ratio / 4);
cvt16 = (int16_t *)wav_cvt.buf;
data = new float[numFrames * 2];
for (i = 0; i < numFrames * 2; i++)
data[i] = cvt16[i];
free(wav_cvt.buf);
}
SDL_FreeWAV(wav_buffer);
}
return data;
}
void SDLMedia::audioDriver(std::string& driverName)
{
char driver[128] = "SDL: audio not available";
char *result = SDL_AudioDriverName(driver, sizeof(driver));
if (result)
driverName = driver;
else
driverName = "SDL: audio not available";
}
#endif //HAVE_SDL
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>SDL_PATH_DSP seems to be used only in oss. Use AUDIODEV instead<commit_after>
/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#ifdef HAVE_SDL
#include <stdlib.h>
#include <string>
#include "SDLMedia.h"
#include "ErrorHandler.h"
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// SDLMedia
//
SDLMedia::SDLMedia() : BzfMedia()
{
cmdFill = 0;
audioReady = false;
}
double SDLMedia::stopwatch(bool start)
{
Uint32 currentTick = SDL_GetTicks(); //msec
if (start) {
stopwatchTime = currentTick;
return 0.0;
}
if (currentTick >= stopwatchTime)
return (double) (currentTick - stopwatchTime) * 0.001; // sec
else
//Clock is wrapped : happens after 49 days
//Should be "wrap value" - stopwatchtime. Now approx.
return (double) currentTick * 0.001;
}
bool SDLMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
printFatalError("Could not initialize SDL-Audio: %s.\n", SDL_GetError());
exit(-1);
};
static SDL_AudioSpec desired;
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
// probably SDL is using multiple buffering, make it a 3rd
int fragmentSize = (int)(0.03f * (float)audioOutputRate);
int n;
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each so double the size
audioBufferSize = 1 << (n + 1);
desired.freq = audioOutputRate;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = audioBufferSize >> 1; // In stereo samples
desired.callback = &fillAudioWrapper;
desired.userdata = (void *) this; // To handle Wrap of func
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&desired, NULL) < 0) {
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
return false;
}
// make an output buffer
outputBuffer = new short[audioBufferSize];
// ready to go
audioReady = true;
return true;
}
void SDLMedia::closeAudio()
{
// Stop Audio to avoid callback
SDL_PauseAudio(1);
SDL_CloseAudio();
delete [] outputBuffer;
outputBuffer = 0;
SDL_QuitSubSystem(SDL_INIT_AUDIO);
audioReady = false;
}
void SDLMedia::startAudioCallback(bool (*proc)(void))
{
userCallback = proc;
// Stop sending silence and start calling audio callback
SDL_PauseAudio(0);
}
void SDLMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
SDL_LockAudio();
// Discard command if full
if ((cmdFill + len) < 2048) {
memcpy(&cmdQueue[cmdFill], cmd, len);
// We should awake audioSleep - but game become unplayable
// using here an SDL_CondSignal(wakeCond)
cmdFill += len;
}
SDL_UnlockAudio();
}
bool SDLMedia::readSoundCommand(void* cmd, int len)
{
bool result = false;
if (cmdFill >= len) {
memcpy(cmd, cmdQueue, len);
// repack list of command waiting to be processed
memmove(cmdQueue, &cmdQueue[len], cmdFill - len);
cmdFill -= len;
result = true;
}
return result;
}
int SDLMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int SDLMedia::getAudioBufferSize() const
{
return audioBufferSize;
}
int SDLMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
void SDLMedia::fillAudio (Uint8 * stream, int len)
{
userCallback();
Uint8* soundBuffer = stream;
int transferSize = (audioBufferSize - sampleToSend) * 2;
if (transferSize > len)
transferSize = len;
// just copying into the soundBuffer is enough, SDL is looking for
// something different from silence sample
memcpy(soundBuffer,
(Uint8 *) &outputBuffer[sampleToSend],
transferSize);
sampleToSend += transferSize / 2;
soundBuffer += transferSize;
len -= transferSize;
}
void SDLMedia::fillAudioWrapper (void * userdata, Uint8 * stream, int len)
{
SDLMedia * me = (SDLMedia *) userdata;
me->fillAudio(stream, len);
};
void SDLMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
while (numSamples > 0) {
if (numSamples>audioBufferSize)
limit=audioBufferSize;
else
limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0)
outputBuffer[j] = -32767;
else
if (samples[j] > 32767.0)
outputBuffer[j] = 32767;
else
outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
}
sampleToSend = 0;
samples += audioBufferSize;
numSamples -= audioBufferSize;
}
}
// Setting Audio Driver
void SDLMedia::setDriver(std::string driverName) {
static char envAssign[256];
std::string envVar = "SDL_AUDIODRIVER=" + driverName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
// Setting Audio Device
void SDLMedia::setDevice(std::string deviceName) {
static char envAssign[256];
std::string envVar = "AUDIODEV=" + deviceName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
float* SDLMedia::doReadSound(const std::string &filename, int &numFrames,
int &rate) const
{
SDL_AudioSpec wav_spec;
Uint32 wav_length;
Uint8 *wav_buffer;
int ret;
SDL_AudioCVT wav_cvt;
int16_t *cvt16;
int i;
float *data = NULL;
rate = defaultAudioRate;
if (SDL_LoadWAV(filename.c_str(), &wav_spec, &wav_buffer, &wav_length)) {
/* Build AudioCVT */
ret = SDL_BuildAudioCVT(&wav_cvt,
wav_spec.format, wav_spec.channels, wav_spec.freq,
AUDIO_S16SYS, 2, defaultAudioRate);
/* Check that the convert was built */
if (ret == -1) {
printFatalError("Could not build converter for Wav file %s: %s.\n",
filename.c_str(), SDL_GetError());
} else {
/* Setup for conversion */
wav_cvt.buf = (Uint8*)malloc(wav_length * wav_cvt.len_mult);
wav_cvt.len = wav_length;
memcpy(wav_cvt.buf, wav_buffer, wav_length);
/* And now we're ready to convert */
SDL_ConvertAudio(&wav_cvt);
numFrames = (int)(wav_length * wav_cvt.len_ratio / 4);
cvt16 = (int16_t *)wav_cvt.buf;
data = new float[numFrames * 2];
for (i = 0; i < numFrames * 2; i++)
data[i] = cvt16[i];
free(wav_cvt.buf);
}
SDL_FreeWAV(wav_buffer);
}
return data;
}
void SDLMedia::audioDriver(std::string& driverName)
{
char driver[128];
char *result = SDL_AudioDriverName(driver, sizeof(driver));
if (result)
driverName = driver;
else
driverName = "audio not available";
}
#endif //HAVE_SDL
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "TextEngine.h"
#include "../base/Logger.h"
#include "../base/OSHelper.h"
#include "../base/Exception.h"
#include "../base/FileHelper.h"
#include "../base/StringHelper.h"
#include <algorithm>
namespace avg {
using namespace std;
static void
text_subst_func_hint(FcPattern *pattern, gpointer data)
{
FcPatternAddBool(pattern, FC_HINTING, true);
FcPatternAddInteger(pattern, FC_HINT_STYLE, FC_HINT_MEDIUM);
FcPatternAddInteger(pattern, FC_RGBA, FC_RGBA_NONE);
FcPatternAddBool(pattern, FC_ANTIALIAS, true);
}
static void
text_subst_func_nohint(FcPattern *pattern, gpointer data)
{
FcPatternAddBool(pattern, FC_HINTING, false);
FcPatternAddBool(pattern, FC_AUTOHINT, false);
FcPatternAddInteger(pattern, FC_HINT_STYLE, FC_HINT_NONE);
FcPatternAddInteger(pattern, FC_RGBA, FC_RGBA_NONE);
FcPatternAddBool(pattern, FC_ANTIALIAS, true);
}
TextEngine& TextEngine::get(bool bHint)
{
if (bHint) {
static TextEngine s_Instance(true);
return s_Instance;
} else {
static TextEngine s_Instance(false);
return s_Instance;
}
}
TextEngine::TextEngine(bool bHint)
: m_bHint(bHint)
{
m_sFontDirs.push_back("fonts/");
init();
}
TextEngine::~TextEngine()
{
deinit();
}
void TextEngine::init()
{
m_pFontMap = PANGO_FT2_FONT_MAP(pango_ft2_font_map_new());
pango_ft2_font_map_set_resolution(m_pFontMap, 72, 72);
if (m_bHint) {
pango_ft2_font_map_set_default_substitute(m_pFontMap, text_subst_func_hint,
0, 0);
} else {
pango_ft2_font_map_set_default_substitute(m_pFontMap, text_subst_func_nohint,
0, 0);
}
m_pPangoContext = pango_ft2_font_map_create_context(m_pFontMap);
pango_context_set_language(m_pPangoContext,
pango_language_from_string ("en_US"));
pango_context_set_base_dir(m_pPangoContext, PANGO_DIRECTION_LTR);
initFonts();
string sOldLang = "";
getEnv("LC_CTYPE", sOldLang);
setEnv("LC_CTYPE", "en-us");
pango_font_map_list_families(PANGO_FONT_MAP(m_pFontMap), &m_ppFontFamilies,
&m_NumFontFamilies);
setEnv("LC_CTYPE", sOldLang);
for (int i = 0; i < m_NumFontFamilies; ++i) {
m_sFonts.push_back(pango_font_family_get_name(m_ppFontFamilies[i]));
}
sort(m_sFonts.begin(), m_sFonts.end());
}
void TextEngine::deinit()
{
g_object_unref(m_pFontMap);
g_free(m_ppFontFamilies);
g_object_unref(m_pPangoContext);
m_sFonts.clear();
}
void TextEngine::addFontDir(const std::string& sDir)
{
deinit();
m_sFontDirs.push_back(sDir);
init();
}
PangoContext * TextEngine::getPangoContext()
{
return m_pPangoContext;
}
const vector<string>& TextEngine::getFontFamilies()
{
return m_sFonts;
}
const vector<string>& TextEngine::getFontVariants(const string& sFontName)
{
PangoFontFamily * pCurFamily = getFontFamily(sFontName);
PangoFontFace ** ppFaces;
int numFaces;
pango_font_family_list_faces (pCurFamily, &ppFaces, &numFaces);
static vector<string> sVariants;
for (int i = 0; i < numFaces; ++i) {
sVariants.push_back(pango_font_face_get_face_name(ppFaces[i]));
}
g_free(ppFaces);
return sVariants;
}
PangoFontDescription * TextEngine::getFontDescription(const string& sFamily,
const string& sVariant)
{
PangoFontDescription* pDescription;
FontDescriptionCache::iterator it;
it = m_FontDescriptionCache.find(pair<string, string>(sFamily, sVariant));
if (it == m_FontDescriptionCache.end()) {
PangoFontFamily * pFamily;
bool bFamilyFound = true;
try {
pFamily = getFontFamily(sFamily);
} catch (Exception&) {
if (m_sFontsNotFound.find(sFamily) == m_sFontsNotFound.end()) {
AVG_TRACE(Logger::WARNING, "Could not find font face " << sFamily <<
". Using sans instead.");
m_sFontsNotFound.insert(sFamily);
}
bFamilyFound = false;
pFamily = getFontFamily("sans");
}
PangoFontFace ** ppFaces;
int numFaces;
pango_font_family_list_faces(pFamily, &ppFaces, &numFaces);
PangoFontFace * pFace = 0;
if (sVariant == "") {
pFace = ppFaces[0];
} else {
for (int i = 0; i < numFaces; ++i) {
if (equalIgnoreCase(pango_font_face_get_face_name(ppFaces[i]), sVariant)) {
pFace = ppFaces[i];
}
}
}
if (!pFace) {
pFace = ppFaces[0];
if (bFamilyFound) {
pair<string, string> variant(sFamily, sVariant);
if (m_VariantsNotFound.find(variant) == m_VariantsNotFound.end()) {
m_VariantsNotFound.insert(variant);
AVG_TRACE(Logger::WARNING, "Could not find font variant "
<< sFamily << ":" << sVariant << ". Using " <<
pango_font_face_get_face_name(pFace) << " instead.");
}
}
}
g_free(ppFaces);
pDescription = pango_font_face_describe(pFace);
m_FontDescriptionCache[pair<string, string>(sFamily, sVariant)] =
pDescription;
} else {
pDescription = it->second;
}
return pango_font_description_copy(pDescription);
}
void GLibLogFunc(const gchar *log_domain, GLogLevelFlags log_level,
const gchar *message, gpointer unused_data)
{
#ifndef WIN32
string s = "Pango ";
if (log_level & G_LOG_LEVEL_ERROR) {
s += "error: ";
} else if (log_level & G_LOG_LEVEL_CRITICAL) {
s += string("critical: ")+message;
AVG_TRACE(Logger::ERROR, s);
AVG_ASSERT(false);
} else if (log_level & G_LOG_LEVEL_WARNING) {
s += "warning: ";
} else if (log_level & G_LOG_LEVEL_MESSAGE) {
s += "message: ";
} else if (log_level & G_LOG_LEVEL_INFO) {
s += "info: ";
} else if (log_level & G_LOG_LEVEL_DEBUG) {
s += "debug: ";
}
s += message;
AVG_TRACE(Logger::WARNING, s);
#endif
}
void TextEngine::initFonts()
{
std::vector<std::string> fontConfPathPrefixList;
#ifndef WIN32
fontConfPathPrefixList.push_back("/");
fontConfPathPrefixList.push_back("/usr/local/");
fontConfPathPrefixList.push_back("/opt/local/");
#endif
fontConfPathPrefixList.push_back(getAvgLibPath());
std::string sFontConfPath;
for (size_t i = 0; i < fontConfPathPrefixList.size(); ++i) {
sFontConfPath = fontConfPathPrefixList[i] + "etc/fonts/fonts.conf";
if (fileExists(sFontConfPath)) {
break;
}
}
FcConfig * pConfig = FcConfigCreate();
int ok = (int)FcConfigParseAndLoad(pConfig,
(const FcChar8 *)(sFontConfPath.c_str()), true);
checkFontError(ok, string("Font error: could not load config file ")+sFontConfPath);
ok = (int)FcConfigBuildFonts(pConfig);
checkFontError(ok, string("Font error: FcConfigBuildFonts failed."));
ok = (int)FcConfigSetCurrent(pConfig);
checkFontError(ok, string("Font error: FcConfigSetCurrent failed."));
for(std::vector<std::string>::const_iterator it = m_sFontDirs.begin();
it != m_sFontDirs.end(); ++it)
{
ok = (int)FcConfigAppFontAddDir(pConfig, (const FcChar8 *)it->c_str());
checkFontError(ok, string("Font error: FcConfigAppFontAddDir("
+ *it + ") failed."));
}
/*
FcStrList * pCacheDirs = FcConfigGetCacheDirs(pConfig);
FcChar8 * pDir;
do {
pDir = FcStrListNext(pCacheDirs);
if (pDir) {
cerr << pDir << endl;
}
} while (pDir);
*/
g_log_set_default_handler(GLibLogFunc, 0);
}
PangoFontFamily * TextEngine::getFontFamily(const string& sFamily)
{
PangoFontFamily * pFamily = 0;
AVG_ASSERT(m_NumFontFamilies != 0);
for (int i=0; i<m_NumFontFamilies; ++i) {
if (equalIgnoreCase(pango_font_family_get_name(m_ppFontFamilies[i]), sFamily)) {
pFamily = m_ppFontFamilies[i];
}
}
if (!pFamily) {
throw(Exception(AVG_ERR_INVALID_ARGS,
"getFontFamily: Font family "+sFamily+" not found."));
}
return pFamily;
}
void TextEngine::checkFontError(int ok, const string& sMsg)
{
if (ok == 0) {
throw Exception(AVG_ERR_FONT_INIT_FAILED, sMsg);
}
}
}
<commit_msg>Fixed Pango deprecation warnings.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "TextEngine.h"
#include "../base/Logger.h"
#include "../base/OSHelper.h"
#include "../base/Exception.h"
#include "../base/FileHelper.h"
#include "../base/StringHelper.h"
#include <algorithm>
namespace avg {
using namespace std;
static void
text_subst_func_hint(FcPattern *pattern, gpointer data)
{
FcPatternAddBool(pattern, FC_HINTING, true);
FcPatternAddInteger(pattern, FC_HINT_STYLE, FC_HINT_MEDIUM);
FcPatternAddInteger(pattern, FC_RGBA, FC_RGBA_NONE);
FcPatternAddBool(pattern, FC_ANTIALIAS, true);
}
static void
text_subst_func_nohint(FcPattern *pattern, gpointer data)
{
FcPatternAddBool(pattern, FC_HINTING, false);
FcPatternAddBool(pattern, FC_AUTOHINT, false);
FcPatternAddInteger(pattern, FC_HINT_STYLE, FC_HINT_NONE);
FcPatternAddInteger(pattern, FC_RGBA, FC_RGBA_NONE);
FcPatternAddBool(pattern, FC_ANTIALIAS, true);
}
TextEngine& TextEngine::get(bool bHint)
{
if (bHint) {
static TextEngine s_Instance(true);
return s_Instance;
} else {
static TextEngine s_Instance(false);
return s_Instance;
}
}
TextEngine::TextEngine(bool bHint)
: m_bHint(bHint)
{
m_sFontDirs.push_back("fonts/");
init();
}
TextEngine::~TextEngine()
{
deinit();
}
void TextEngine::init()
{
m_pFontMap = PANGO_FT2_FONT_MAP(pango_ft2_font_map_new());
pango_ft2_font_map_set_resolution(m_pFontMap, 72, 72);
if (m_bHint) {
pango_ft2_font_map_set_default_substitute(m_pFontMap, text_subst_func_hint,
0, 0);
} else {
pango_ft2_font_map_set_default_substitute(m_pFontMap, text_subst_func_nohint,
0, 0);
}
#if PANGO_VERSION > PANGO_VERSION_ENCODE(1,22,0)
m_pPangoContext = pango_font_map_create_context(PANGO_FONT_MAP(m_pFontMap));
#else
m_pPangoContext = pango_ft2_font_map_create_context(m_pFontMap);
#endif
pango_context_set_language(m_pPangoContext,
pango_language_from_string ("en_US"));
pango_context_set_base_dir(m_pPangoContext, PANGO_DIRECTION_LTR);
initFonts();
string sOldLang = "";
getEnv("LC_CTYPE", sOldLang);
setEnv("LC_CTYPE", "en-us");
pango_font_map_list_families(PANGO_FONT_MAP(m_pFontMap), &m_ppFontFamilies,
&m_NumFontFamilies);
setEnv("LC_CTYPE", sOldLang);
for (int i = 0; i < m_NumFontFamilies; ++i) {
m_sFonts.push_back(pango_font_family_get_name(m_ppFontFamilies[i]));
}
sort(m_sFonts.begin(), m_sFonts.end());
}
void TextEngine::deinit()
{
g_object_unref(m_pFontMap);
g_free(m_ppFontFamilies);
g_object_unref(m_pPangoContext);
m_sFonts.clear();
}
void TextEngine::addFontDir(const std::string& sDir)
{
deinit();
m_sFontDirs.push_back(sDir);
init();
}
PangoContext * TextEngine::getPangoContext()
{
return m_pPangoContext;
}
const vector<string>& TextEngine::getFontFamilies()
{
return m_sFonts;
}
const vector<string>& TextEngine::getFontVariants(const string& sFontName)
{
PangoFontFamily * pCurFamily = getFontFamily(sFontName);
PangoFontFace ** ppFaces;
int numFaces;
pango_font_family_list_faces (pCurFamily, &ppFaces, &numFaces);
static vector<string> sVariants;
for (int i = 0; i < numFaces; ++i) {
sVariants.push_back(pango_font_face_get_face_name(ppFaces[i]));
}
g_free(ppFaces);
return sVariants;
}
PangoFontDescription * TextEngine::getFontDescription(const string& sFamily,
const string& sVariant)
{
PangoFontDescription* pDescription;
FontDescriptionCache::iterator it;
it = m_FontDescriptionCache.find(pair<string, string>(sFamily, sVariant));
if (it == m_FontDescriptionCache.end()) {
PangoFontFamily * pFamily;
bool bFamilyFound = true;
try {
pFamily = getFontFamily(sFamily);
} catch (Exception&) {
if (m_sFontsNotFound.find(sFamily) == m_sFontsNotFound.end()) {
AVG_TRACE(Logger::WARNING, "Could not find font face " << sFamily <<
". Using sans instead.");
m_sFontsNotFound.insert(sFamily);
}
bFamilyFound = false;
pFamily = getFontFamily("sans");
}
PangoFontFace ** ppFaces;
int numFaces;
pango_font_family_list_faces(pFamily, &ppFaces, &numFaces);
PangoFontFace * pFace = 0;
if (sVariant == "") {
pFace = ppFaces[0];
} else {
for (int i = 0; i < numFaces; ++i) {
if (equalIgnoreCase(pango_font_face_get_face_name(ppFaces[i]), sVariant)) {
pFace = ppFaces[i];
}
}
}
if (!pFace) {
pFace = ppFaces[0];
if (bFamilyFound) {
pair<string, string> variant(sFamily, sVariant);
if (m_VariantsNotFound.find(variant) == m_VariantsNotFound.end()) {
m_VariantsNotFound.insert(variant);
AVG_TRACE(Logger::WARNING, "Could not find font variant "
<< sFamily << ":" << sVariant << ". Using " <<
pango_font_face_get_face_name(pFace) << " instead.");
}
}
}
g_free(ppFaces);
pDescription = pango_font_face_describe(pFace);
m_FontDescriptionCache[pair<string, string>(sFamily, sVariant)] =
pDescription;
} else {
pDescription = it->second;
}
return pango_font_description_copy(pDescription);
}
void GLibLogFunc(const gchar *log_domain, GLogLevelFlags log_level,
const gchar *message, gpointer unused_data)
{
#ifndef WIN32
string s = "Pango ";
if (log_level & G_LOG_LEVEL_ERROR) {
s += "error: ";
} else if (log_level & G_LOG_LEVEL_CRITICAL) {
s += string("critical: ")+message;
AVG_TRACE(Logger::ERROR, s);
AVG_ASSERT(false);
} else if (log_level & G_LOG_LEVEL_WARNING) {
s += "warning: ";
} else if (log_level & G_LOG_LEVEL_MESSAGE) {
s += "message: ";
} else if (log_level & G_LOG_LEVEL_INFO) {
s += "info: ";
} else if (log_level & G_LOG_LEVEL_DEBUG) {
s += "debug: ";
}
s += message;
AVG_TRACE(Logger::WARNING, s);
#endif
}
void TextEngine::initFonts()
{
std::vector<std::string> fontConfPathPrefixList;
#ifndef WIN32
fontConfPathPrefixList.push_back("/");
fontConfPathPrefixList.push_back("/usr/local/");
fontConfPathPrefixList.push_back("/opt/local/");
#endif
fontConfPathPrefixList.push_back(getAvgLibPath());
std::string sFontConfPath;
for (size_t i = 0; i < fontConfPathPrefixList.size(); ++i) {
sFontConfPath = fontConfPathPrefixList[i] + "etc/fonts/fonts.conf";
if (fileExists(sFontConfPath)) {
break;
}
}
FcConfig * pConfig = FcConfigCreate();
int ok = (int)FcConfigParseAndLoad(pConfig,
(const FcChar8 *)(sFontConfPath.c_str()), true);
checkFontError(ok, string("Font error: could not load config file ")+sFontConfPath);
ok = (int)FcConfigBuildFonts(pConfig);
checkFontError(ok, string("Font error: FcConfigBuildFonts failed."));
ok = (int)FcConfigSetCurrent(pConfig);
checkFontError(ok, string("Font error: FcConfigSetCurrent failed."));
for(std::vector<std::string>::const_iterator it = m_sFontDirs.begin();
it != m_sFontDirs.end(); ++it)
{
ok = (int)FcConfigAppFontAddDir(pConfig, (const FcChar8 *)it->c_str());
checkFontError(ok, string("Font error: FcConfigAppFontAddDir("
+ *it + ") failed."));
}
/*
FcStrList * pCacheDirs = FcConfigGetCacheDirs(pConfig);
FcChar8 * pDir;
do {
pDir = FcStrListNext(pCacheDirs);
if (pDir) {
cerr << pDir << endl;
}
} while (pDir);
*/
g_log_set_default_handler(GLibLogFunc, 0);
}
PangoFontFamily * TextEngine::getFontFamily(const string& sFamily)
{
PangoFontFamily * pFamily = 0;
AVG_ASSERT(m_NumFontFamilies != 0);
for (int i=0; i<m_NumFontFamilies; ++i) {
if (equalIgnoreCase(pango_font_family_get_name(m_ppFontFamilies[i]), sFamily)) {
pFamily = m_ppFontFamilies[i];
}
}
if (!pFamily) {
throw(Exception(AVG_ERR_INVALID_ARGS,
"getFontFamily: Font family "+sFamily+" not found."));
}
return pFamily;
}
void TextEngine::checkFontError(int ok, const string& sMsg)
{
if (ok == 0) {
throw Exception(AVG_ERR_FONT_INIT_FAILED, sMsg);
}
}
}
<|endoftext|> |
<commit_before>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
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 "flusspferd/create.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/class_description.hpp"
#include <sstream>
#include <curl/curl.h>
using namespace flusspferd;
namespace {
long global_init(long flags) {
return curl_global_init(flags);
}
FLUSSPFERD_CLASS_DESCRIPTION
(
Easy,
(constructor_name, "Easy")
(full_name, "cURL.Easy")
(methods,
("cleanup", bind, cleanup)
("perform", bind, perform)
("reset", bind, reset)
("escape", bind, escape)
("unescape", bind, unescape)
("setopt", bind, setopt)
("valid", bind, valid))
)
{
CURL *handle;
object writecallback;
static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {
assert(stream);
Easy &self = *reinterpret_cast<Easy*>(stream);
// self.writecallback.call();
// TODO ...
return size * nmemb;
}
protected:
void trace(flusspferd::tracer &trc) {
trc("writecallback", writecallback);
}
public:
CURL *data() { return handle; }
bool valid() { return handle; }
CURL *get() {
if(!handle) {
throw flusspferd::exception("CURL handle not valid!");
}
return handle;
}
Easy(flusspferd::object const &self, flusspferd::call_context&)
: base_type(self), handle(curl_easy_init())
{
if(!handle) {
throw flusspferd::exception("curl_easy_init");
}
}
Easy(flusspferd::object const &self, CURL *hnd)
: base_type(self), handle(hnd)
{
assert(handle);
}
void cleanup() {
if(handle) {
curl_easy_cleanup(handle);
handle = 0x0;
}
}
~Easy() { cleanup(); }
int perform() {
return curl_easy_perform(get());
}
void reset() {
curl_easy_reset(get());
}
std::string unescape(char const *input) {
int len;
char *uesc = curl_easy_unescape(get(), input, 0, &len);
if(!uesc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(uesc, len);
curl_free(uesc);
return ret;
}
std::string escape(char const *input) {
char *esc = curl_easy_escape(get(), input, 0);
if(!esc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(esc);
curl_free(esc);
return ret;
}
#define OPT_NUMBER(what) \
case what : \
if(x.arg.size() != 2) { \
std::stringstream ss; \
ss << "curl_easy_setopt: Expected two arguments. Got (" << x.arg.size() << ')'; \
throw flusspferd::exception(ss.str()); \
} \
int res = curl_easy_setopt(get(), what , x.arg[1].to_number()); \
if(res != 0) { \
throw flusspferd::exception(std::string("curl_easy_setopt: ") + \
curl_easy_strerror(res)); \
} \
break; \
/**/
#define OPT_FUNCTION(what, data, callback, func)
void setopt(flusspferd::call_context &x) {
int what = x.arg.front().to_number();
switch(what) {
//OPT_NUMBER(CURLOPT_HEADER)
case CURLOPT_WRITEFUNCTION: {
// TODO reset to default function (0x0 parameter!)
if(!x.arg[1].is_object()) {
throw flusspferd::exception("curl_easy_setopt: expected a function as second parameter!");
}
writecallback = x.arg[1].to_object();
int res = curl_easy_setopt(get(), CURLOPT_WRITEDATA, this);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror((CURLcode)res));
}
res = curl_easy_setopt(get(), CURLOPT_WRITEFUNCTION, writefunction);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror((CURLcode)res));
}
}
default: {
std::stringstream ss;
ss << "curl_easy_setopt unkown or unsupported option (" << what << ')';
throw flusspferd::exception(ss.str());
}
};
}
#undef OPT_FUNCTION
#undef OPT_NUMBER
static Easy &create(CURL *hnd) {
return flusspferd::create_native_object<Easy>(object(), hnd);
}
};
Easy &wrap(CURL *hnd) {
return Easy::create(hnd);
}
CURL *unwrap(Easy &c) {
return c.data();
}
FLUSSPFERD_LOADER_SIMPLE(cURL) {
local_root_scope scope;
cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING),
read_only_property | permanent_property);
create_native_function(cURL, "globalInit", &global_init);
cURL.define_property("version", value(curl_version()),
read_only_property | permanent_property);
load_class<Easy>(cURL);
cURL.define_property("OPT_HEADER", value((int)CURLOPT_HEADER),
read_only_property | permanent_property);
cURL.define_property("OPT_WRITEFUNCTION", value((int)CURLOPT_WRITEFUNCTION),
read_only_property | permanent_property);
}
}
<commit_msg>curl: global_init now throws an exception instead of returning the error code<commit_after>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
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 "flusspferd/create.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/class_description.hpp"
#include <sstream>
#include <curl/curl.h>
using namespace flusspferd;
namespace {
void global_init(long flags) {
CURLcode ret = curl_global_init(flags);
if(ret != 0) {
throw flusspferd::exception(std::string("curl_global_init: ") +
curl_easy_strerror(ret));
}
}
FLUSSPFERD_CLASS_DESCRIPTION
(
Easy,
(constructor_name, "Easy")
(full_name, "cURL.Easy")
(methods,
("cleanup", bind, cleanup)
("perform", bind, perform)
("reset", bind, reset)
("escape", bind, escape)
("unescape", bind, unescape)
("setopt", bind, setopt)
("valid", bind, valid))
)
{
CURL *handle;
object writecallback;
static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {
assert(stream);
Easy &self = *reinterpret_cast<Easy*>(stream);
// self.writecallback.call();
// TODO ...
return size * nmemb;
}
protected:
void trace(flusspferd::tracer &trc) {
trc("writecallback", writecallback);
}
public:
CURL *data() { return handle; }
bool valid() { return handle; }
CURL *get() {
if(!handle) {
throw flusspferd::exception("CURL handle not valid!");
}
return handle;
}
Easy(flusspferd::object const &self, flusspferd::call_context&)
: base_type(self), handle(curl_easy_init())
{
if(!handle) {
throw flusspferd::exception("curl_easy_init");
}
}
Easy(flusspferd::object const &self, CURL *hnd)
: base_type(self), handle(hnd)
{
assert(handle);
}
void cleanup() {
if(handle) {
curl_easy_cleanup(handle);
handle = 0x0;
}
}
~Easy() { cleanup(); }
int perform() {
return curl_easy_perform(get());
}
void reset() {
curl_easy_reset(get());
}
std::string unescape(char const *input) {
int len;
char *uesc = curl_easy_unescape(get(), input, 0, &len);
if(!uesc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(uesc, len);
curl_free(uesc);
return ret;
}
std::string escape(char const *input) {
char *esc = curl_easy_escape(get(), input, 0);
if(!esc) {
throw flusspferd::exception("curl_easy_escape");
}
std::string ret(esc);
curl_free(esc);
return ret;
}
#define OPT_NUMBER(what) \
case what : \
if(x.arg.size() != 2) { \
std::stringstream ss; \
ss << "curl_easy_setopt: Expected two arguments. Got (" << x.arg.size() << ')'; \
throw flusspferd::exception(ss.str()); \
} \
int res = curl_easy_setopt(get(), what , x.arg[1].to_number()); \
if(res != 0) { \
throw flusspferd::exception(std::string("curl_easy_setopt: ") + \
curl_easy_strerror(res)); \
} \
break; \
/**/
#define OPT_FUNCTION(what, data, callback, func)
void setopt(flusspferd::call_context &x) {
int what = x.arg.front().to_number();
switch(what) {
//OPT_NUMBER(CURLOPT_HEADER)
case CURLOPT_WRITEFUNCTION: {
// TODO reset to default function (0x0 parameter!)
if(!x.arg[1].is_object()) {
throw flusspferd::exception("curl_easy_setopt: expected a function as second parameter!");
}
writecallback = x.arg[1].to_object();
int res = curl_easy_setopt(get(), CURLOPT_WRITEDATA, this);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror((CURLcode)res));
}
res = curl_easy_setopt(get(), CURLOPT_WRITEFUNCTION, writefunction);
if(res != 0) {
throw flusspferd::exception(std::string("curl_easy_setopt: ") +
curl_easy_strerror((CURLcode)res));
}
}
default: {
std::stringstream ss;
ss << "curl_easy_setopt unkown or unsupported option (" << what << ')';
throw flusspferd::exception(ss.str());
}
};
}
#undef OPT_FUNCTION
#undef OPT_NUMBER
static Easy &create(CURL *hnd) {
return flusspferd::create_native_object<Easy>(object(), hnd);
}
};
Easy &wrap(CURL *hnd) {
return Easy::create(hnd);
}
CURL *unwrap(Easy &c) {
return c.data();
}
FLUSSPFERD_LOADER_SIMPLE(cURL) {
local_root_scope scope;
cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32),
read_only_property | permanent_property);
cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING),
read_only_property | permanent_property);
create_native_function(cURL, "globalInit", &global_init);
cURL.define_property("version", value(curl_version()),
read_only_property | permanent_property);
load_class<Easy>(cURL);
cURL.define_property("OPT_HEADER", value((int)CURLOPT_HEADER),
read_only_property | permanent_property);
cURL.define_property("OPT_WRITEFUNCTION", value((int)CURLOPT_WRITEFUNCTION),
read_only_property | permanent_property);
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
dump.c - Skeleton of backends to access the Key Database
-------------------
begin : Mon May 3 15:22:44 CEST 2010
copyright : by Markus Raab
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the BSD License (revised). *
* *
***************************************************************************/
#include "dump.hpp"
using namespace ckdb;
#include <kdberrors.h>
namespace dump
{
int serialize(std::ostream &os, ckdb::Key *, ckdb::KeySet *ks)
{
ckdb::Key *cur;
os << "kdbOpen 1" << std::endl;
os << "ksNew " << ckdb::ksGetSize(ks) << std::endl;
ckdb::KeySet *metacopies = ckdb::ksNew(0);
ksRewind(ks);
while ((cur = ksNext(ks)) != 0)
{
size_t namesize = ckdb::keyGetNameSize(cur);
size_t valuesize = ckdb::keyGetValueSize(cur);
os << "keyNew " << namesize
<< " " << valuesize << std::endl;
os.write(ckdb::keyName(cur), namesize);
os.write(static_cast<const char*>(ckdb::keyValue(cur)), valuesize);
os << std::endl;
const ckdb::Key *meta;
ckdb::keyRewindMeta(cur);
while ((meta = ckdb::keyNextMeta(cur)) != 0)
{
std::stringstream ss;
ss << "user/" << meta; // use the address of pointer as name
ckdb::Key *search = ckdb::keyNew(
ss.str().c_str(),
KEY_END);
ckdb::Key *ret = ksLookup(metacopies, search, 0);
if (!ret)
{
/* This meta key was not serialized up to now */
size_t metanamesize = ckdb::keyGetNameSize(meta);
size_t metavaluesize = ckdb::keyGetValueSize(meta);
os << "keyMeta " << metanamesize
<< " " << metavaluesize << std::endl;
os.write (ckdb::keyName(meta), metanamesize);
os.write (static_cast<const char*>(ckdb::keyValue(meta)), metavaluesize);
os << std::endl;
std::stringstream ssv;
ssv << namesize << " " << metanamesize << std::endl;
ssv.write(ckdb::keyName(cur), namesize);
ssv.write (ckdb::keyName(meta), metanamesize);
ckdb::keySetRaw(search, ssv.str().c_str(), ssv.str().size());
ksAppendKey(metacopies, search);
} else {
/* Meta key already serialized, write out a reference to it */
keyDel (search);
os << "keyCopyMeta ";
os.write(static_cast<const char*>(ckdb::keyValue(ret)), ckdb::keyGetValueSize(ret));
os << std::endl;
}
}
os << "keyEnd" << std::endl;
}
os << "ksEnd" << std::endl;
ksDel (metacopies);
return 1;
}
int unserialize(std::istream &is, ckdb::Key *errorKey, ckdb::KeySet *ks)
{
ckdb::Key *cur = 0;
std::vector<char> namebuffer(4048);
std::vector<char> valuebuffer(4048);
std::string line;
std::string command;
size_t nrKeys;
size_t namesize;
size_t valuesize;
while(std::getline (is, line))
{
std::stringstream ss (line);
ss >> command;
if (command == "kdbOpen")
{
std::string version;
ss >> version;
if (version != "1")
{
ELEKTRA_SET_ERROR (50, errorKey, version.c_str());
return -1;
}
}
else if (command == "ksNew")
{
ss >> nrKeys;
ksClear(ks);
}
else if (command == "keyNew")
{
cur = ckdb::keyNew(0);
ss >> namesize;
ss >> valuesize;
if (namesize > namebuffer.size()) namebuffer.resize(namesize);
is.read(&namebuffer[0], namesize);
namebuffer[namesize] = 0;
ckdb::keySetName(cur, &namebuffer[0]);
if (valuesize > valuebuffer.size()) valuebuffer.resize(valuesize);
is.read(&valuebuffer[0], valuesize);
ckdb::keySetRaw (cur, &valuebuffer[0], valuesize);
std::getline (is, line);
}
else if (command == "keyMeta")
{
ss >> namesize;
ss >> valuesize;
if (namesize > namebuffer.size()) namebuffer.resize(namesize);
is.read(&namebuffer[0], namesize);
namebuffer[namesize] = 0;
if (valuesize > valuebuffer.size()) valuebuffer.resize(valuesize);
is.read(&valuebuffer[0], valuesize);
keySetMeta (cur, &namebuffer[0], &valuebuffer[0]);
std::getline (is, line);
}
else if (command == "keyCopyMeta")
{
ss >> namesize;
ss >> valuesize;
if (namesize > namebuffer.size()) namebuffer.resize(namesize);
is.read(&namebuffer[0], namesize);
namebuffer[namesize] = 0;
if (valuesize > valuebuffer.size()) valuebuffer.resize(valuesize);
is.read(&valuebuffer[0], valuesize);
ckdb::Key * search = ckdb::ksLookupByName(ks, &namebuffer[0], 0);
ckdb::keyCopyMeta(cur, search, &valuebuffer[0]);
std::getline (is, line);
}
else if (command == "keyEnd")
{
ckdb::ksAppendKey(ks, cur);
cur = 0;
}
else if (command == "ksEnd")
{
break;
} else {
ELEKTRA_SET_ERROR (49, errorKey, command.c_str());
return -1;
}
}
return 1;
}
} // namespace dump
extern "C" {
int elektraDumpGet(ckdb::Plugin *, ckdb::KeySet *returned, ckdb::Key *parentKey)
{
Key *root = ckdb::keyNew("system/elektra/modules/dump", KEY_END);
if (keyRel(root, parentKey) >= 0)
{
keyDel (root);
void (*get) (void) = (void (*) (void)) elektraDumpGet;
void (*set) (void) = (void (*) (void)) elektraDumpSet;
void (*serialize) (void) = (void (*) (void)) dump::serialize;
void (*unserialize) (void) = (void (*) (void)) dump::unserialize;
KeySet *n = ksNew(50,
keyNew ("system/elektra/modules/dump",
KEY_VALUE, "dump plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/dump/exports", KEY_END),
keyNew ("system/elektra/modules/dump/exports/get",
KEY_SIZE, sizeof (get),
KEY_BINARY,
KEY_VALUE, &get, KEY_END),
keyNew ("system/elektra/modules/dump/exports/set",
KEY_SIZE, sizeof (set),
KEY_BINARY,
KEY_VALUE, &set, KEY_END),
keyNew ("system/elektra/modules/dump/exports/serialize",
KEY_SIZE, sizeof (serialize),
KEY_BINARY,
KEY_VALUE, &serialize, KEY_END),
keyNew ("system/elektra/modules/dump/exports/unserialize",
KEY_SIZE, sizeof (unserialize),
KEY_BINARY,
KEY_VALUE, &unserialize, KEY_END),
keyNew ("system/elektra/modules/dump/infos",
KEY_VALUE, "All information you want to know", KEY_END),
keyNew ("system/elektra/modules/dump/infos/author",
KEY_VALUE, "Markus Raab <[email protected]>", KEY_END),
keyNew ("system/elektra/modules/dump/infos/licence",
KEY_VALUE, "BSD", KEY_END),
keyNew ("system/elektra/modules/dump/infos/description",
KEY_VALUE, "Dumps complete Elektra Semantics", KEY_END),
keyNew ("system/elektra/modules/dump/infos/provides",
KEY_VALUE, "storage", KEY_END),
keyNew ("system/elektra/modules/dump/infos/placements",
KEY_VALUE, "getstorage setstorage", KEY_END),
keyNew ("system/elektra/modules/dump/infos/needs",
KEY_VALUE, "", KEY_END),
keyNew ("system/elektra/modules/dump/infos/version",
KEY_VALUE, PLUGINVERSION, KEY_END),
KS_END);
ksAppend(returned, n);
ksDel (n);
return 1;
}
keyDel (root);
std::ifstream ofs(keyString(parentKey), std::ios::binary);
if (!ofs.is_open()) return 0;
return dump::unserialize (ofs, parentKey, returned);
}
int elektraDumpSet(ckdb::Plugin *, ckdb::KeySet *returned, ckdb::Key *parentKey)
{
std::ofstream ofs(keyString(parentKey), std::ios::binary);
if (!ofs.is_open())
{
ELEKTRA_SET_ERROR (9, parentKey, "file is not open in dump");
return -1;
}
return dump::serialize (ofs, parentKey, returned);
}
ckdb::Plugin *ELEKTRA_PLUGIN_EXPORT(dump)
{
return elektraPluginExport("dump",
ELEKTRA_PLUGIN_GET, &elektraDumpGet,
ELEKTRA_PLUGIN_SET, &elektraDumpSet,
ELEKTRA_PLUGIN_END);
}
} // extern C
<commit_msg>improve dump contract's docu<commit_after>/***************************************************************************
dump.c - Skeleton of backends to access the Key Database
-------------------
begin : Mon May 3 15:22:44 CEST 2010
copyright : by Markus Raab
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the BSD License (revised). *
* *
***************************************************************************/
#include "dump.hpp"
using namespace ckdb;
#include <kdberrors.h>
namespace dump
{
int serialize(std::ostream &os, ckdb::Key *, ckdb::KeySet *ks)
{
ckdb::Key *cur;
os << "kdbOpen 1" << std::endl;
os << "ksNew " << ckdb::ksGetSize(ks) << std::endl;
ckdb::KeySet *metacopies = ckdb::ksNew(0);
ksRewind(ks);
while ((cur = ksNext(ks)) != 0)
{
size_t namesize = ckdb::keyGetNameSize(cur);
size_t valuesize = ckdb::keyGetValueSize(cur);
os << "keyNew " << namesize
<< " " << valuesize << std::endl;
os.write(ckdb::keyName(cur), namesize);
os.write(static_cast<const char*>(ckdb::keyValue(cur)), valuesize);
os << std::endl;
const ckdb::Key *meta;
ckdb::keyRewindMeta(cur);
while ((meta = ckdb::keyNextMeta(cur)) != 0)
{
std::stringstream ss;
ss << "user/" << meta; // use the address of pointer as name
ckdb::Key *search = ckdb::keyNew(
ss.str().c_str(),
KEY_END);
ckdb::Key *ret = ksLookup(metacopies, search, 0);
if (!ret)
{
/* This meta key was not serialized up to now */
size_t metanamesize = ckdb::keyGetNameSize(meta);
size_t metavaluesize = ckdb::keyGetValueSize(meta);
os << "keyMeta " << metanamesize
<< " " << metavaluesize << std::endl;
os.write (ckdb::keyName(meta), metanamesize);
os.write (static_cast<const char*>(ckdb::keyValue(meta)), metavaluesize);
os << std::endl;
std::stringstream ssv;
ssv << namesize << " " << metanamesize << std::endl;
ssv.write(ckdb::keyName(cur), namesize);
ssv.write (ckdb::keyName(meta), metanamesize);
ckdb::keySetRaw(search, ssv.str().c_str(), ssv.str().size());
ksAppendKey(metacopies, search);
} else {
/* Meta key already serialized, write out a reference to it */
keyDel (search);
os << "keyCopyMeta ";
os.write(static_cast<const char*>(ckdb::keyValue(ret)), ckdb::keyGetValueSize(ret));
os << std::endl;
}
}
os << "keyEnd" << std::endl;
}
os << "ksEnd" << std::endl;
ksDel (metacopies);
return 1;
}
int unserialize(std::istream &is, ckdb::Key *errorKey, ckdb::KeySet *ks)
{
ckdb::Key *cur = 0;
std::vector<char> namebuffer(4048);
std::vector<char> valuebuffer(4048);
std::string line;
std::string command;
size_t nrKeys;
size_t namesize;
size_t valuesize;
while(std::getline (is, line))
{
std::stringstream ss (line);
ss >> command;
if (command == "kdbOpen")
{
std::string version;
ss >> version;
if (version != "1")
{
ELEKTRA_SET_ERROR (50, errorKey, version.c_str());
return -1;
}
}
else if (command == "ksNew")
{
ss >> nrKeys;
ksClear(ks);
}
else if (command == "keyNew")
{
cur = ckdb::keyNew(0);
ss >> namesize;
ss >> valuesize;
if (namesize > namebuffer.size()) namebuffer.resize(namesize);
is.read(&namebuffer[0], namesize);
namebuffer[namesize] = 0;
ckdb::keySetName(cur, &namebuffer[0]);
if (valuesize > valuebuffer.size()) valuebuffer.resize(valuesize);
is.read(&valuebuffer[0], valuesize);
ckdb::keySetRaw (cur, &valuebuffer[0], valuesize);
std::getline (is, line);
}
else if (command == "keyMeta")
{
ss >> namesize;
ss >> valuesize;
if (namesize > namebuffer.size()) namebuffer.resize(namesize);
is.read(&namebuffer[0], namesize);
namebuffer[namesize] = 0;
if (valuesize > valuebuffer.size()) valuebuffer.resize(valuesize);
is.read(&valuebuffer[0], valuesize);
keySetMeta (cur, &namebuffer[0], &valuebuffer[0]);
std::getline (is, line);
}
else if (command == "keyCopyMeta")
{
ss >> namesize;
ss >> valuesize;
if (namesize > namebuffer.size()) namebuffer.resize(namesize);
is.read(&namebuffer[0], namesize);
namebuffer[namesize] = 0;
if (valuesize > valuebuffer.size()) valuebuffer.resize(valuesize);
is.read(&valuebuffer[0], valuesize);
ckdb::Key * search = ckdb::ksLookupByName(ks, &namebuffer[0], 0);
ckdb::keyCopyMeta(cur, search, &valuebuffer[0]);
std::getline (is, line);
}
else if (command == "keyEnd")
{
ckdb::ksAppendKey(ks, cur);
cur = 0;
}
else if (command == "ksEnd")
{
break;
} else {
ELEKTRA_SET_ERROR (49, errorKey, command.c_str());
return -1;
}
}
return 1;
}
} // namespace dump
extern "C" {
int elektraDumpGet(ckdb::Plugin *, ckdb::KeySet *returned, ckdb::Key *parentKey)
{
Key *root = ckdb::keyNew("system/elektra/modules/dump", KEY_END);
if (keyRel(root, parentKey) >= 0)
{
keyDel (root);
void (*get) (void) = (void (*) (void)) elektraDumpGet;
void (*set) (void) = (void (*) (void)) elektraDumpSet;
void (*serialize) (void) = (void (*) (void)) dump::serialize;
void (*unserialize) (void) = (void (*) (void)) dump::unserialize;
KeySet *n = ksNew(50,
keyNew ("system/elektra/modules/dump",
KEY_VALUE, "dump plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/dump/exports", KEY_END),
keyNew ("system/elektra/modules/dump/exports/get",
KEY_SIZE, sizeof (get),
KEY_BINARY,
KEY_VALUE, &get, KEY_END),
keyNew ("system/elektra/modules/dump/exports/set",
KEY_SIZE, sizeof (set),
KEY_BINARY,
KEY_VALUE, &set, KEY_END),
keyNew ("system/elektra/modules/dump/exports/serialize",
KEY_SIZE, sizeof (serialize),
KEY_BINARY,
KEY_VALUE, &serialize, KEY_END),
keyNew ("system/elektra/modules/dump/exports/unserialize",
KEY_SIZE, sizeof (unserialize),
KEY_BINARY,
KEY_VALUE, &unserialize, KEY_END),
keyNew ("system/elektra/modules/dump/infos",
KEY_VALUE, "Dumps into a format tailored to KeySet semantics", KEY_END),
keyNew ("system/elektra/modules/dump/infos/author",
KEY_VALUE, "Markus Raab <[email protected]>", KEY_END),
keyNew ("system/elektra/modules/dump/infos/licence",
KEY_VALUE, "BSD", KEY_END),
keyNew ("system/elektra/modules/dump/infos/description",
KEY_VALUE, "Dumps complete KeySet Semantics", KEY_END),
keyNew ("system/elektra/modules/dump/infos/provides",
KEY_VALUE, "storage", KEY_END),
keyNew ("system/elektra/modules/dump/infos/placements",
KEY_VALUE, "getstorage setstorage", KEY_END),
keyNew ("system/elektra/modules/dump/infos/needs",
KEY_VALUE, "", KEY_END),
keyNew ("system/elektra/modules/dump/infos/version",
KEY_VALUE, PLUGINVERSION, KEY_END),
KS_END);
ksAppend(returned, n);
ksDel (n);
return 1;
}
keyDel (root);
std::ifstream ofs(keyString(parentKey), std::ios::binary);
if (!ofs.is_open()) return 0;
return dump::unserialize (ofs, parentKey, returned);
}
int elektraDumpSet(ckdb::Plugin *, ckdb::KeySet *returned, ckdb::Key *parentKey)
{
std::ofstream ofs(keyString(parentKey), std::ios::binary);
if (!ofs.is_open())
{
ELEKTRA_SET_ERROR (9, parentKey, "file is not open in dump");
return -1;
}
return dump::serialize (ofs, parentKey, returned);
}
ckdb::Plugin *ELEKTRA_PLUGIN_EXPORT(dump)
{
return elektraPluginExport("dump",
ELEKTRA_PLUGIN_GET, &elektraDumpGet,
ELEKTRA_PLUGIN_SET, &elektraDumpSet,
ELEKTRA_PLUGIN_END);
}
} // extern C
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright The University of Auckland
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.
*******************************************************************************/
//==============================================================================
// Preferences window
//==============================================================================
#include "mainwindow.h"
#include "preferenceswindow.h"
//==============================================================================
#include "ui_preferenceswindow.h"
//==============================================================================
namespace OpenCOR {
//==============================================================================
PreferencesWindow::PreferencesWindow(QWidget *pParent) :
QDialog(pParent),
mGui(new Ui::PreferencesWindow)
{
// Set up the GUI
mGui->setupUi(this);
}
//==============================================================================
PreferencesWindow::~PreferencesWindow()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Copyright The University of Auckland
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.
*******************************************************************************/
//==============================================================================
// Preferences window
//==============================================================================
#include "preferenceswindow.h"
//==============================================================================
#include "ui_preferenceswindow.h"
//==============================================================================
namespace OpenCOR {
//==============================================================================
PreferencesWindow::PreferencesWindow(QWidget *pParent) :
QDialog(pParent),
mGui(new Ui::PreferencesWindow)
{
// Set up the GUI
mGui->setupUi(this);
}
//==============================================================================
PreferencesWindow::~PreferencesWindow()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
* Action.cpp
*
*/
#include "Action.h"
Action::Action() {
// TODO Auto-generated constructor stub
}
Action::Action(Packet pkt, Database* db, Socket* sock){
if(pkt.m_MsgType < 0){
std::cout << "[E] No Information in Packet" << std::endl;
}
else{
m_db = db;
m_GivenPkt = pkt;
m_sock = sock;
TakeAction();
}
}
Action::Action(Database* db) {
m_db = db;
while(1) {
std::cout << "[D] Check Heartbeat" << std::endl;
CheckHeartbeat();
sleep(10);
}
}
Action::~Action() {
// TODO Auto-generated destructor stub
}
// Get Packet and command
// If the parameter is string parse it.
void Action::GivePacket(Packet pkt){
if(pkt.m_MsgType < 0){
std::cout << "[E] No Information in Packet" << std::endl;
}
else{
m_GivenPkt = pkt;
TakeAction();
}
}
// Decide proper action and perform the job.
void Action::TakeAction(){
// Do action following message type
Packet pkt;
std::string result;
std::string temp;
switch(m_GivenPkt.m_MsgType){
case AP_REGISTRATION_REQUEST:
InsertDatabase();
SendResponseMessage(AP_REGISTRATION_RESPONSE, pkt);
break;
//case AP_REGISTRATION_RESPONSE:
//break;
case AP_STATE_UPDATE_REQUEST:
UpdateDatabase();
SendResponseMessage(AP_STATE_UPDATE_RESPONSE, pkt);
break;
//case AP_STATE_UPDATE_RESPONSE:
//break;
case AP_LIST_REQUEST:
result = m_db->GetResult("select ID, IP, SSID from AP_Information;");
//Parse the result by '|' mark
//and make pkt context
while(true)
{
temp = result.substr(0,result.find('|'));
result.erase(0,result.find('|')+1);
pkt.AddValue(AP_ID, temp);
temp = result.substr(0,result.find('|'));
result.erase(0,result.find('|')+1);
pkt.AddValue(AP_IP, temp);
temp = result.substr(0,result.find('|'));
result.erase(0,result.find('|')+1);
pkt.AddValue(AP_SSID, temp);
if(result.length() < 1) break;
}
SendResponseMessage(AP_LIST_RESPONSE, pkt);
break;
default:
break;
}
}
//Add AP information on DB
void Action::InsertDatabase(){
std::string query;
query.assign("INSERT INTO AP_Information (");
for(int i=0; i<m_GivenPkt.m_paramNo; i++){
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[i]));
query.append(",");
}
query.erase(query.length()-1);
query.append(") VALUES ('");
for(int i=0; i<m_GivenPkt.m_paramNo; i++){
query.append(m_GivenPkt.m_Value[i]);
query.append("','");
}
query.erase(query.length()-2);
query.append(");");
m_db->SendQuery(query);
}
//Update AP Information on DB
void Action::UpdateDatabase(){
std::string query;
query.assign("UPDATE AP_Information SET ");
for(int i=1; i<m_GivenPkt.m_paramNo; i++){
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[i]));
query.append("='");
query.append(m_GivenPkt.m_Value[i]);
query.append("',");
}
query.erase(query.length()-1);
query.append(", time=CURRENT_TIMESTAMP");
query.append(" WHERE ");
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[0]));
query.append("='");
query.append(m_GivenPkt.m_Value[0]);
query.append("';");
m_db->SendQuery(query);
}
void Action::CheckHeartbeat() {
std::string query;
query.assign("DELETE FROM AP_Information WHERE (time - CURRENT_TIMESTAMP) < - 30;");
m_db->SendQuery(query);
}
//Send response to AP
void Action::SendResponseMessage(int messageType, Packet pkt){
pkt.DecideMessageType(messageType);
m_sock->send(pkt.CreateMessage());
std::cout << "[S] (" << pkt.m_MsgType << ") ";
std::cout << pkt.CreateMessage() << std::endl;
}
<commit_msg>solved db's bug and add heartbeat<commit_after>/*
* Action.cpp
*
*/
#include "Action.h"
Action::Action() {
// TODO Auto-generated constructor stub
}
Action::Action(Packet pkt, Database* db, Socket* sock){
if(pkt.m_MsgType < 0){
std::cout << "[E] No Information in Packet" << std::endl;
}
else{
m_db = db;
m_GivenPkt = pkt;
m_sock = sock;
TakeAction();
}
}
Action::Action(Database* db) {
m_db = db;
while(1) {
std::cout << "[D] Check Heartbeat" << std::endl;
CheckHeartbeat();
sleep(10);
}
}
Action::~Action() {
// TODO Auto-generated destructor stub
}
// Get Packet and command
// If the parameter is string parse it.
void Action::GivePacket(Packet pkt){
if(pkt.m_MsgType < 0){
std::cout << "[E] No Information in Packet" << std::endl;
}
else{
m_GivenPkt = pkt;
TakeAction();
}
}
// Decide proper action and perform the job.
void Action::TakeAction(){
// Do action following message type
Packet pkt;
std::string result;
std::string temp;
switch(m_GivenPkt.m_MsgType){
case AP_REGISTRATION_REQUEST:
InsertDatabase();
SendResponseMessage(AP_REGISTRATION_RESPONSE, pkt);
break;
//case AP_REGISTRATION_RESPONSE:
//break;
case AP_STATE_UPDATE_REQUEST:
UpdateDatabase();
SendResponseMessage(AP_STATE_UPDATE_RESPONSE, pkt);
break;
//case AP_STATE_UPDATE_RESPONSE:
//break;
case AP_LIST_REQUEST:
result = m_db->GetResult("select ID, IP, SSID from AP_Information;");
//Parse the result by '|' mark
//and make pkt context
while(true)
{
temp = result.substr(0,result.find('|'));
result.erase(0,result.find('|')+1);
pkt.AddValue(AP_ID, temp);
temp = result.substr(0,result.find('|'));
result.erase(0,result.find('|')+1);
pkt.AddValue(AP_IP, temp);
temp = result.substr(0,result.find('|'));
result.erase(0,result.find('|')+1);
pkt.AddValue(AP_SSID, temp);
if(result.length() < 1) break;
}
SendResponseMessage(AP_LIST_RESPONSE, pkt);
break;
default:
break;
}
}
//Add AP information on DB
void Action::InsertDatabase(){
std::string query;
query.assign("INSERT INTO AP_Information (");
for(int i=0; i<m_GivenPkt.m_paramNo; i++){
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[i]));
query.append(",");
}
query.erase(query.length()-1);
query.append(") VALUES ('");
for(int i=0; i<m_GivenPkt.m_paramNo; i++){
query.append(m_GivenPkt.m_Value[i]);
query.append("','");
}
query.erase(query.length()-2);
query.append(");");
m_db->SendQuery(query);
}
//Update AP Information on DB
void Action::UpdateDatabase(){
std::string query;
query.assign("INSERT INTO AP_Information (");
for(int i=0; i<m_GivenPkt.m_paramNo; i++){
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[i]));
query.append(",");
}
//query.erase(query.length()-1);
query.append("time");
query.append(") VALUES ('");
for(int i=0; i<m_GivenPkt.m_paramNo; i++){
query.append(m_GivenPkt.m_Value[i]);
query.append("','");
}
query.erase(query.length()-1);
query.append("CURRENT_TIMESTAMP");
//query.erase(query.length()-2);
query.append(") ON DUPLICATE KEY ");
//m_db->SendQuery(query);
//query.assign("UPDATE AP_Information SET ");
query.append("UPDATE ");
for(int i=1; i<m_GivenPkt.m_paramNo; i++){
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[i]));
query.append("='");
query.append(m_GivenPkt.m_Value[i]);
query.append("',");
}
query.erase(query.length()-1);
query.append(", time=CURRENT_TIMESTAMP;");
/*
query.append(" WHERE ");
query.append(ValueTypeToString(m_GivenPkt.m_ValueType[0]));
query.append("='");
query.append(m_GivenPkt.m_Value[0]);
query.append("';");
*/
//std::cout << query << std::endl;
m_db->SendQuery(query);
}
void Action::CheckHeartbeat() {
std::string query;
query.assign("DELETE FROM AP_Information WHERE (time - CURRENT_TIMESTAMP) <= - 30;");
m_db->SendQuery(query);
}
//Send response to AP
void Action::SendResponseMessage(int messageType, Packet pkt){
pkt.DecideMessageType(messageType);
m_sock->send(pkt.CreateMessage());
std::cout << "[S] (" << pkt.m_MsgType << ") ";
std::cout << pkt.CreateMessage() << std::endl;
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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 SignalFinder.cpp
*/
using namespace std;
#include <map>
#include <string>
#include <vector>
#include <JPetWriter/JPetWriter.h>
#include "SignalFinderTools.h"
#include "SignalFinder.h"
SignalFinder::SignalFinder(const char* name, const char* description, bool saveControlHistos)
: JPetTask(name, description)
{
fSaveControlHistos = saveControlHistos;
}
SignalFinder::~SignalFinder() {}
//SignalFinder init method
void SignalFinder::init(const JPetTaskInterface::Options& opts)
{
INFO("Signal finding started.");
if (opts.count(fEdgeMaxTimeParamKey)) {
kSigChEdgeMaxTime = std::atof(opts.at(fEdgeMaxTimeParamKey).c_str());
}
if (opts.count(fLeadTrailMaxTimeParamKey)) {
kSigChLeadTrailMaxTime = std::atof(opts.at(fLeadTrailMaxTimeParamKey).c_str());
}
fBarrelMap.buildMappings(getParamBank());
if (fSaveControlHistos) {
getStatistics().createHistogram(new TH1F("remainig_leading_sig_ch_per_thr", "Remainig Leading Signal Channels", 4, 0.5, 4.5));
getStatistics().createHistogram(new TH1F("remainig_trailing_sig_ch_per_thr", "Remainig Trailing Signal Channels", 4, 0.5, 4.5));
getStatistics().createHistogram(new TH1F("TOT_thr_1", "TOT on threshold 1 [ns]", 100, 20.0, 100.0));
getStatistics().createHistogram(new TH1F("TOT_thr_2", "TOT on threshold 2 [ns]", 100, 20.0, 100.0));
getStatistics().createHistogram(new TH1F("TOT_thr_3", "TOT on threshold 3 [ns]", 100, 20.0, 100.0));
getStatistics().createHistogram(new TH1F("TOT_thr_4", "TOT on threshold 4 [ns]", 100, 20.0, 100.0));
}
}
//SignalFinder execution method
void SignalFinder::exec()
{
//getting the data from event in propriate format
if (auto timeWindow = dynamic_cast<const JPetTimeWindow* const>(getEvent())) {
//mapping method invocation
map<int, vector<JPetSigCh>> sigChsPMMap = SignalFinderTools::getSigChsPMMapById(timeWindow);
std::cout <<"after getSigChsPMMapById" <<std::endl;
//building signals method invocation
vector<JPetRawSignal> allSignals = SignalFinderTools::buildAllSignals(timeWindow->getIndex(), sigChsPMMap, kNumOfThresholds , getStatistics(), fSaveControlHistos, kSigChEdgeMaxTime, kSigChLeadTrailMaxTime);
std::cout <<"after buildAllSignals" <<std::endl;
//saving method invocation
saveRawSignals(allSignals);
}
}
//SignalFinder finish method
void SignalFinder::terminate()
{
INFO("Signal finding ended.");
}
//saving method
void SignalFinder::saveRawSignals(const vector<JPetRawSignal>& sigChVec)
{
assert(fWriter);
for (const auto & sigCh : sigChVec) {
fWriter->write(sigCh);
}
}
//other methods - TODO check if neccessary
void SignalFinder::setWriter(JPetWriter* writer)
{
fWriter = writer;
}
void SignalFinder::setParamManager(JPetParamManager* paramManager)
{
fParamManager = paramManager;
}
const JPetParamBank& SignalFinder::getParamBank() const
{
return fParamManager->getParamBank();
}
<commit_msg>Remove remaining cout in SignalFinder<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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 SignalFinder.cpp
*/
using namespace std;
#include <map>
#include <string>
#include <vector>
#include <JPetWriter/JPetWriter.h>
#include "SignalFinderTools.h"
#include "SignalFinder.h"
SignalFinder::SignalFinder(const char* name, const char* description, bool saveControlHistos)
: JPetTask(name, description)
{
fSaveControlHistos = saveControlHistos;
}
SignalFinder::~SignalFinder() {}
//SignalFinder init method
void SignalFinder::init(const JPetTaskInterface::Options& opts)
{
INFO("Signal finding started.");
if (opts.count(fEdgeMaxTimeParamKey)) {
kSigChEdgeMaxTime = std::atof(opts.at(fEdgeMaxTimeParamKey).c_str());
}
if (opts.count(fLeadTrailMaxTimeParamKey)) {
kSigChLeadTrailMaxTime = std::atof(opts.at(fLeadTrailMaxTimeParamKey).c_str());
}
fBarrelMap.buildMappings(getParamBank());
if (fSaveControlHistos) {
getStatistics().createHistogram(new TH1F("remainig_leading_sig_ch_per_thr", "Remainig Leading Signal Channels", 4, 0.5, 4.5));
getStatistics().createHistogram(new TH1F("remainig_trailing_sig_ch_per_thr", "Remainig Trailing Signal Channels", 4, 0.5, 4.5));
getStatistics().createHistogram(new TH1F("TOT_thr_1", "TOT on threshold 1 [ns]", 100, 20.0, 100.0));
getStatistics().createHistogram(new TH1F("TOT_thr_2", "TOT on threshold 2 [ns]", 100, 20.0, 100.0));
getStatistics().createHistogram(new TH1F("TOT_thr_3", "TOT on threshold 3 [ns]", 100, 20.0, 100.0));
getStatistics().createHistogram(new TH1F("TOT_thr_4", "TOT on threshold 4 [ns]", 100, 20.0, 100.0));
}
}
//SignalFinder execution method
void SignalFinder::exec()
{
//getting the data from event in propriate format
if (auto timeWindow = dynamic_cast<const JPetTimeWindow* const>(getEvent())) {
//mapping method invocation
map<int, vector<JPetSigCh>> sigChsPMMap = SignalFinderTools::getSigChsPMMapById(timeWindow);
//building signals method invocation
vector<JPetRawSignal> allSignals = SignalFinderTools::buildAllSignals(timeWindow->getIndex(), sigChsPMMap, kNumOfThresholds , getStatistics(), fSaveControlHistos, kSigChEdgeMaxTime, kSigChLeadTrailMaxTime);
//saving method invocation
saveRawSignals(allSignals);
}
}
//SignalFinder finish method
void SignalFinder::terminate()
{
INFO("Signal finding ended.");
}
//saving method
void SignalFinder::saveRawSignals(const vector<JPetRawSignal>& sigChVec)
{
assert(fWriter);
for (const auto & sigCh : sigChVec) {
fWriter->write(sigCh);
}
}
//other methods - TODO check if neccessary
void SignalFinder::setWriter(JPetWriter* writer)
{
fWriter = writer;
}
void SignalFinder::setParamManager(JPetParamManager* paramManager)
{
fParamManager = paramManager;
}
const JPetParamBank& SignalFinder::getParamBank() const
{
return fParamManager->getParamBank();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "ui_interface.h"
#include "guiconstants.h"
#include <QMessageBox>
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->addAsData->setPlaceholderText(tr("Enter a message to send with your transfer"));
#endif
// normal bitcoin address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying bitcoin address(es)
ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont());
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
// If one of the widgets changes, the combined content changes as well
connect(ui->addAsData, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->addAsData->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
ui->addAsData_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
ui->addAsData_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
// If dropdown selection is 'Hex' and data input is in ASCII format reject it
if (ui->addAsData2->currentText() == "HEX" && !IsHex(ui->addAsData->text().toStdString())) {
QMessageBox::critical(0, tr("Data input was rejected!"),
tr("The data input must be a string in hexadecimal format"));
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
if(ui->addAsData2->currentText() == "ASCII") {
QString asciiData = ui->addAsData->text();
recipient.data = asciiData.toLatin1().toHex();
} else {
recipient.data = ui->addAsData->text();
}
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget::setTabOrder(ui->addAsLabel, ui->addAsData);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsData);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // insecure
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->addAsData_is->setText(recipient.data);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_InsecurePaymentRequest);
}
else // secure
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->addAsData_s->setText(recipient.data);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_SecurePaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->addAsData->setText(recipient.data);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<commit_msg>Bug fix in sendcoinsentry<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "ui_interface.h"
#include "guiconstants.h"
#include <QMessageBox>
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->addAsData->setPlaceholderText(tr("Enter a message to send with your transfer"));
#endif
// normal bitcoin address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying bitcoin address(es)
ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont());
ui->addAsData2->addItem("HEX");
ui->addAsData2->addItem("ASCII");
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
// If one of the widgets changes, the combined content changes as well
connect(ui->addAsData, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->addAsData->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
ui->addAsData_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
ui->addAsData_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
// If dropdown selection is 'Hex' and data input is in ASCII format reject it
if (ui->addAsData2->currentText() == "HEX" && !IsHex(ui->addAsData->text().toStdString())) {
QMessageBox::critical(0, tr("Data input was rejected!"),
tr("The data input must be a string in hexadecimal format"));
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
if(ui->addAsData2->currentText() == "ASCII") {
QString asciiData = ui->addAsData->text();
recipient.data = asciiData.toLatin1().toHex();
} else {
recipient.data = ui->addAsData->text();
}
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget::setTabOrder(ui->addAsLabel, ui->addAsData);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsData);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // insecure
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->addAsData_is->setText(recipient.data);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_InsecurePaymentRequest);
}
else // secure
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->addAsData_s->setText(recipient.data);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_SecurePaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->addAsData->setText(recipient.data);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<|endoftext|> |
<commit_before>// #include <cstdio>
// int n, m;
// int main() {
// scanf("%d %d", &n, &m);
// if (n == 1) {
// printf("1\n");
// }
// else if (n == 2) {
// if (m <= 6) {
// printf("%d\n", (m + 1) / 2);
// }
// else {
// printf("4\n");
// }
// }
// else {
// if (m <= 4) {
// printf("%d\n", m);
// }
// else if (m == 5 || m == 6) {
// printf("4\n");
// }
// else {
// printf("%d\n", m - 2);
// }
// }
// return 0;
// }
#include <cstdio>
using namespace std;
int n, m;
int main() {
scanf("%d %d", &n, &m);
if (n == 1) {
printf("1\n");
return 0;
}
if (n == 2) {
printf("%d\n", (4 < ((m + 1) / 2)) ? 4 : ((m + 1) / 2));
return 0;
}
if (m < 7) {
printf("%d\n", (4 < m) ? 4 : m);
return 0;
}
printf("%d\n", m - 7 + 5);
return 0;
}<commit_msg>add comment<commit_after>#include <cstdio>
#include <algorithm>
using namespace std;
int n, m;
int main() {
scanf("%d %d", &n, &m);
if (n == 1) { // 세로가 1일 때는 움직을 수 없다. 하지만 시작위치까지 움직였다 생각하므로 1이다
printf("1\n");
return 0;
}
if (n == 2) { // 세로가 2일 때는 2, 3번 조건만 사용할 수 있기 때문에 최대 3회 움직일 수 있다
printf("%d\n", min(4, (m + 1) / 2));
return 0;
}
if (m < 7) { // 가로가 6이하면 최대 4칸 이동가능
printf("%d\n", min(4, m));
return 0;
}
// 4회 이상 이동할 경우 모든 방법을 다 사용
// 2, 번 경우에 2칸 씩 오른쪽으로 이동
// 그러므로 한칸 씩은 손해를본다
printf("%d\n", m - 2);
return 0;
}<|endoftext|> |
<commit_before>#include <cstdio>
#include <algorithm>
using namespace std;
int n, weight;
int arr[100001];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
sort(arr, arr + n);
// 로프마다 들수 있는 중량이 다르다
// 그래서 제일 작은 중량 값 * 로프의 개수를 해주면 답이 나온다
for (int i = n - 1; i >= 0; i--) {
weight = max(weight, arr[i] * (n - i));
}
printf("%d\n", weight);
}<commit_msg>add comment 2217<commit_after>#include <cstdio>
#include <algorithm>
using namespace std;
int n, weight;
int arr[100001];
/*
[10, 15] 의 로프가 있을 때
15 / 1 = 15 이므로 15의 무게를 견딜 수 있다
(10 + 15) / 2 = 12.5 이므로 무게 10을 결딜 수 있는 로프는 견디지 못한다
그래서 사용한 로프는 2개 최대 하중은 10 이므로
10 * 2 = 20의 무게를 견딜 수 있다
*/
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
sort(arr, arr + n);
// 로프마다 들수 있는 중량이 다르다
// 그래서 제일 작은 중량 값 * 로프의 개수를 해주면 답이 나온다
for (int i = n - 1; i >= 0; i--) {
weight = max(weight, arr[i] * (n - i));
}
printf("%d\n", weight);
}<|endoftext|> |
<commit_before>// fmfrecord.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <FlyCapture2.h>
#include <omp.h>
#include <queue>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define TRIGGER_CAMERA 1
using namespace std;
using namespace FlyCapture2;
using namespace cv;
FILE **fout;
FILE *flog;
FlyCapture2::Camera** ppCameras;
char fname[10][100];
char flogname[100];
char wname[10][100];
void PrintCameraInfo( FlyCapture2::CameraInfo* pCamInfo )
{
printf("%u %s %s\n", pCamInfo->serialNumber, pCamInfo->modelName, pCamInfo->sensorResolution);
}
void PrintError( FlyCapture2::Error error )
{
error.PrintErrorTrace();
}
int RunSingleCamera(int i, int numImages)
{
int frameNumber = 0;
FlyCapture2::Image rawImage;
FlyCapture2::Error error;
bool stream = true;
// Create a converted image
FlyCapture2::Image convertedImage;
FlyCapture2::TimeStamp timestamp;
queue <int> frameCount;
queue <Image> rawImageStream;
queue <Image> dispImageStream;
queue <TimeStamp> rawTimeStamps;
#pragma omp parallel sections
{
#pragma omp section
{
// press [ESC] to exit from continuous streaming mode
while (stream)
{
// Start capturing images
error = ppCameras[i]->RetrieveBuffer( &rawImage );
//get image timestamp
timestamp = rawImage.GetTimeStamp();
// Convert the raw image
error = rawImage.Convert( FlyCapture2::PIXEL_FORMAT_MONO8, &convertedImage );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
}
#pragma omp critical
{
dispImageStream.push(convertedImage);
frameCount.push(frameNumber);
rawImageStream.push(convertedImage);
rawTimeStamps.push(timestamp);
}
frameNumber++;
if ( GetAsyncKeyState(VK_ESCAPE) || frameNumber == numImages )
stream = false;
}
}
#pragma omp section
{
while (stream || !rawImageStream.empty())
{
if (!rawImageStream.empty())
{
Image tImage = rawImageStream.front();
TimeStamp tStamp = rawTimeStamps.front();
double dtStamp = (double) tStamp.seconds;
fwrite(&dtStamp, sizeof(double), 1, fout[i]);
fwrite(tImage.GetData(), tImage.GetDataSize(), 1, fout[i]);
fprintf(flog, "Cam %d - Frame %d - TimeStamp [%d %d]\n", i, frameCount.front(), tStamp.seconds, tStamp.microSeconds);
#pragma omp critical
{
frameCount.pop();
rawImageStream.pop();
rawTimeStamps.pop();
}
}
}
}
#pragma omp section
{
while (stream)
{
if (!dispImageStream.empty())
{
Image dImage;
dImage.DeepCopy(&dispImageStream.back());
// convert to OpenCV Mat
unsigned int rowBytes = (double)dImage.GetReceivedDataSize() / (double)dImage.GetRows();
Mat frame = Mat(dImage.GetRows(), dImage.GetCols(), CV_8UC1, dImage.GetData(), rowBytes);
//int width=frame.size().width;
//int height=frame.size().height;
//line(frame, Point((width/2)-50,height/2), Point((width/2)+50, height/2), 255); //crosshair horizontal
//line(frame, Point(width/2,(height/2)-50), Point(width/2,(height/2)+50), 255); //crosshair vertical
imshow(wname[i], frame);
waitKey(1);
#pragma omp critical
dispImageStream = queue<Image>();
}
}
}
}
return frameNumber; //return frame number in the event that [ESC] was pressed to stop camera streaming before set nframes was reached
}
int _tmain(int argc, _TCHAR* argv[])
{
FlyCapture2::Error error;
const Mode k_fmt7Mode = MODE_0;
const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW8;
Format7Info fmt7Info;
bool supported;
FlyCapture2::PGRGuid guid;
FlyCapture2::BusManager busMgr;
unsigned int numCameras;
unsigned __int32 fmfVersion;
unsigned __int64 bytesPerChunk, nframes, nframesRun;
unsigned __int32 sizeHeight, sizeWidth;
TriggerMode triggerMode;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Number of cameras detected: %u\n\n", numCameras );
if ( numCameras < 1 )
{
printf( "Insufficient number of cameras\n" );
getchar();
return -1;
}
if (argc == 2)
nframes = _ttoi(argv[1]);
else
nframes = -1;
// initialize camera and video writer instances
ppCameras = new FlyCapture2::Camera*[numCameras];
fout = new FILE*[numCameras];
flog = new FILE;
SYSTEMTIME st;
GetLocalTime(&st);
for (unsigned int i = 0; i < numCameras; i++)
{
ppCameras[i] = new FlyCapture2::Camera();
error = busMgr.GetCameraFromIndex( i, &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Connect to a camera
error = ppCameras[i]->Connect( &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Power on the camera
const unsigned int k_cameraPower = 0x610;
const unsigned int k_powerVal = 0x80000000;
error = ppCameras[i]->WriteRegister( k_cameraPower, k_powerVal );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
const unsigned int millisecondsToSleep = 100;
unsigned int regVal = 0;
unsigned int retries = 10;
// Wait for camera to complete power-up
do
{
#if defined(WIN32) || defined(WIN64)
Sleep(millisecondsToSleep);
#else
usleep(millisecondsToSleep * 1000);
#endif
error = ppCameras[i]->ReadRegister(k_cameraPower, ®Val);
if (error == FlyCapture2::PGRERROR_TIMEOUT)
{
// ignore timeout errors, camera may not be responding to
// register reads during power-up
}
else if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
retries--;
} while ((regVal & k_powerVal) == 0 && retries > 0);
// Check for timeout errors after retrying
if (error == FlyCapture2::PGRERROR_TIMEOUT)
{
PrintError( error );
return -1;
}
// Get the camera information
FlyCapture2::CameraInfo camInfo;
error = ppCameras[i]->GetCameraInfo( &camInfo );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
PrintCameraInfo(&camInfo);
// Query for available Format 7 modes
fmt7Info.mode = k_fmt7Mode;
error = ppCameras[i]->GetFormat7Info( &fmt7Info, &supported );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( (k_fmt7PixFmt & fmt7Info.pixelFormatBitField) == 0 )
{
// Pixel format not supported!
printf("Pixel format is not supported\n");
return -1;
}
Format7ImageSettings fmt7ImageSettings;
fmt7ImageSettings.mode = k_fmt7Mode;
fmt7ImageSettings.offsetX = 0;
fmt7ImageSettings.offsetY = 0;
fmt7ImageSettings.width = fmt7Info.maxWidth;
fmt7ImageSettings.height = fmt7Info.maxHeight;
fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;
bool valid;
Format7PacketInfo fmt7PacketInfo;
// Validate the settings to make sure that they are valid
error = ppCameras[i]->ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( !valid )
{
// Settings are not valid
printf("Format7 settings are not valid\n");
return -1;
}
// Set the settings to the camera
error = ppCameras[i]->SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
//Lower shutter speed for fast triggering
FlyCapture2::Property pProp;
pProp.type = SHUTTER;
pProp.absControl = true;
pProp.onePush = false;
pProp.onOff = true;
pProp.autoManualMode = false;
pProp.absValue = 0.006;
error = ppCameras[i]->SetProperty( &pProp );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
#if TRIGGER_CAMERA
// Check for external trigger support
TriggerModeInfo triggerModeInfo;
error = ppCameras[i]->GetTriggerModeInfo( &triggerModeInfo );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( triggerModeInfo.present != true )
{
printf( "Camera does not support external trigger! Exiting...\n" );
return -1;
}
// Get current trigger settings
error = ppCameras[i]->GetTriggerMode( &triggerMode );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Set camera to trigger mode 0
triggerMode.onOff = true;
triggerMode.mode = 0;
triggerMode.parameter = 0;
// Triggering the camera externally using source 0.
triggerMode.source = 0;
error = ppCameras[i]->SetTriggerMode( &triggerMode );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
#endif
//settings for version 1.0 fmf header
fmfVersion = 1;
sizeHeight = fmt7ImageSettings.height;
sizeWidth = fmt7ImageSettings.width;
bytesPerChunk = sizeHeight*sizeWidth + sizeof(double);
sprintf_s(fname[i], "E:\\Cam%d-%d%02d%02dT%02d%02d%02d.fmf", i, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
remove(fname[i]);
fout[i] = fopen(fname[i], "wb");
if(fout[i]==NULL)
{
printf("\nError opening FMF writer. Recording terminated.");
return -1;
}
//write FMF header data
fwrite(&fmfVersion, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeHeight, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeWidth, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&bytesPerChunk, sizeof(unsigned __int64), 1, fout[i]);
fwrite(&nframes, sizeof(unsigned __int64), 1, fout[i]);
if (i == 0)
{
sprintf_s(flogname, "E:\\log-%d%02d%02dT%02d%02d%02d.txt", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
remove(flogname);
flog = fopen(flogname, "w");
if(flog==NULL)
{
printf("\nError creating log file. Recording terminated.");
return -1;
}
}
sprintf_s(wname[i], "camera view %d", i);
}
//Starting individual cameras
for (unsigned int i = 0; i < numCameras; i++)
{
error = ppCameras[i]->StartCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
getchar();
return -1;
}
}
//Retrieve frame rate property
Property frmRate;
frmRate.type = FRAME_RATE;
error = ppCameras[0]->GetProperty( &frmRate );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "\nFrame rate is %3.2f fps\n", frmRate.absValue );
printf("\nGrabbing ...\n");
//OpenMP parallel execution of camera streaming and recording to uncompressed fmf format videos
omp_set_nested(1);
#pragma omp parallel for num_threads(numCameras)
for (int i = 0; i < numCameras; i++ )
{
nframesRun = (unsigned __int64)RunSingleCamera(i, nframes);
}
printf( "\nFinished grabbing %d images\n", nframesRun );
for (unsigned int i = 0; i < numCameras; i++ )
{
//check if number of frames streamed from the camera were the same as what was initially set
if (nframesRun != nframes)
{
//seek to location in file where nframes is stored and replace
fseek (fout[i], 20 , SEEK_SET );
fwrite(&nframesRun, sizeof(unsigned __int64), 1, fout[i]);
}
// close fmf flies
fclose(fout[i]);
// Stop capturing images
ppCameras[i]->StopCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
fclose(flog);
#if TRIGGER_CAMERA
// Turn off trigger mode
triggerMode.onOff = false;
error = ppCameras[i]->SetTriggerMode( &triggerMode );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
#endif
// Disconnect the camera
ppCameras[i]->Disconnect();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Delete camera instances
delete ppCameras[i];
}
// Free up memory
delete [] ppCameras;
printf("Done! Press Enter to exit...\n");
getchar();
return 0;
}
<commit_msg>Code cleanup<commit_after>// fmfrecord.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <FlyCapture2.h>
#include <omp.h>
#include <queue>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define TRIGGER_CAMERA 1
using namespace std;
using namespace FlyCapture2;
using namespace cv;
FILE **fout;
FILE *flog;
FlyCapture2::Camera** ppCameras;
char fname[10][100];
char flogname[100];
char wname[10][100];
void PrintCameraInfo( FlyCapture2::CameraInfo* pCamInfo )
{
printf("%u %s %s\n", pCamInfo->serialNumber, pCamInfo->modelName, pCamInfo->sensorResolution);
}
void PrintError( FlyCapture2::Error error )
{
error.PrintErrorTrace();
}
int RunSingleCamera(int i, int numImages)
{
int frameNumber = 0;
FlyCapture2::Image rawImage;
FlyCapture2::Error error;
bool stream = true;
// Create a converted image
FlyCapture2::Image convertedImage;
FlyCapture2::TimeStamp timestamp;
queue <int> frameCount;
queue <Image> rawImageStream;
queue <Image> dispImageStream;
queue <TimeStamp> rawTimeStamps;
#pragma omp parallel sections
{
#pragma omp section
{
// press [ESC] to exit from continuous streaming mode
while (stream)
{
// Start capturing images
error = ppCameras[i]->RetrieveBuffer( &rawImage );
//get image timestamp
timestamp = rawImage.GetTimeStamp();
// Convert the raw image
error = rawImage.Convert( FlyCapture2::PIXEL_FORMAT_MONO8, &convertedImage );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
}
#pragma omp critical
{
dispImageStream.push(convertedImage);
frameCount.push(frameNumber);
rawImageStream.push(convertedImage);
rawTimeStamps.push(timestamp);
}
frameNumber++;
if ( GetAsyncKeyState(VK_ESCAPE) || frameNumber == numImages )
stream = false;
}
}
#pragma omp section
{
while (stream || !rawImageStream.empty())
{
if (!rawImageStream.empty())
{
Image tImage = rawImageStream.front();
TimeStamp tStamp = rawTimeStamps.front();
double dtStamp = (double) tStamp.seconds;
fwrite(&dtStamp, sizeof(double), 1, fout[i]);
fwrite(tImage.GetData(), tImage.GetDataSize(), 1, fout[i]);
fprintf(flog, "Cam %d - Frame %d - TimeStamp [%d %d]\n", i, frameCount.front(), tStamp.seconds, tStamp.microSeconds);
#pragma omp critical
{
frameCount.pop();
rawImageStream.pop();
rawTimeStamps.pop();
}
}
}
}
#pragma omp section
{
while (stream)
{
if (!dispImageStream.empty())
{
Image dImage;
dImage.DeepCopy(&dispImageStream.back());
// convert to OpenCV Mat
unsigned int rowBytes = (double)dImage.GetReceivedDataSize() / (double)dImage.GetRows();
Mat frame = Mat(dImage.GetRows(), dImage.GetCols(), CV_8UC1, dImage.GetData(), rowBytes);
imshow(wname[i], frame);
waitKey(1);
#pragma omp critical
dispImageStream = queue<Image>();
}
}
}
}
return frameNumber; //return frame number in the event that [ESC] was pressed to stop camera streaming before set nframes was reached
}
int _tmain(int argc, _TCHAR* argv[])
{
FlyCapture2::Error error;
const Mode k_fmt7Mode = MODE_0;
const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW8;
Format7Info fmt7Info;
bool supported;
FlyCapture2::PGRGuid guid;
FlyCapture2::BusManager busMgr;
unsigned int numCameras;
unsigned __int32 fmfVersion;
unsigned __int64 bytesPerChunk, nframes, nframesRun;
unsigned __int32 sizeHeight, sizeWidth;
TriggerMode triggerMode;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Number of cameras detected: %u\n\n", numCameras );
if ( numCameras < 1 )
{
printf( "Insufficient number of cameras\n" );
getchar();
return -1;
}
if (argc == 2)
nframes = _ttoi(argv[1]);
else
nframes = -1;
// initialize camera and video writer instances
ppCameras = new FlyCapture2::Camera*[numCameras];
fout = new FILE*[numCameras];
flog = new FILE;
SYSTEMTIME st;
GetLocalTime(&st);
for (unsigned int i = 0; i < numCameras; i++)
{
ppCameras[i] = new FlyCapture2::Camera();
error = busMgr.GetCameraFromIndex( i, &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Connect to a camera
error = ppCameras[i]->Connect( &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Power on the camera
const unsigned int k_cameraPower = 0x610;
const unsigned int k_powerVal = 0x80000000;
error = ppCameras[i]->WriteRegister( k_cameraPower, k_powerVal );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
const unsigned int millisecondsToSleep = 100;
unsigned int regVal = 0;
unsigned int retries = 10;
// Wait for camera to complete power-up
do
{
#if defined(WIN32) || defined(WIN64)
Sleep(millisecondsToSleep);
#else
usleep(millisecondsToSleep * 1000);
#endif
error = ppCameras[i]->ReadRegister(k_cameraPower, ®Val);
if (error == FlyCapture2::PGRERROR_TIMEOUT)
{
// ignore timeout errors, camera may not be responding to
// register reads during power-up
}
else if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
retries--;
} while ((regVal & k_powerVal) == 0 && retries > 0);
// Check for timeout errors after retrying
if (error == FlyCapture2::PGRERROR_TIMEOUT)
{
PrintError( error );
return -1;
}
// Get the camera information
FlyCapture2::CameraInfo camInfo;
error = ppCameras[i]->GetCameraInfo( &camInfo );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
PrintCameraInfo(&camInfo);
// Query for available Format 7 modes
fmt7Info.mode = k_fmt7Mode;
error = ppCameras[i]->GetFormat7Info( &fmt7Info, &supported );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( (k_fmt7PixFmt & fmt7Info.pixelFormatBitField) == 0 )
{
// Pixel format not supported!
printf("Pixel format is not supported\n");
return -1;
}
Format7ImageSettings fmt7ImageSettings;
fmt7ImageSettings.mode = k_fmt7Mode;
fmt7ImageSettings.offsetX = 0;
fmt7ImageSettings.offsetY = 0;
fmt7ImageSettings.width = fmt7Info.maxWidth;
fmt7ImageSettings.height = fmt7Info.maxHeight;
fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;
bool valid;
Format7PacketInfo fmt7PacketInfo;
// Validate the settings to make sure that they are valid
error = ppCameras[i]->ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( !valid )
{
// Settings are not valid
printf("Format7 settings are not valid\n");
return -1;
}
// Set the settings to the camera
error = ppCameras[i]->SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
//Lower shutter speed for fast triggering
FlyCapture2::Property pProp;
pProp.type = SHUTTER;
pProp.absControl = true;
pProp.onePush = false;
pProp.onOff = true;
pProp.autoManualMode = false;
pProp.absValue = 0.006;
error = ppCameras[i]->SetProperty( &pProp );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
#if TRIGGER_CAMERA
// Check for external trigger support
TriggerModeInfo triggerModeInfo;
error = ppCameras[i]->GetTriggerModeInfo( &triggerModeInfo );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( triggerModeInfo.present != true )
{
printf( "Camera does not support external trigger! Exiting...\n" );
return -1;
}
// Get current trigger settings
error = ppCameras[i]->GetTriggerMode( &triggerMode );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Set camera to trigger mode 0
triggerMode.onOff = true;
triggerMode.mode = 0;
triggerMode.parameter = 0;
// Triggering the camera externally using source 0.
triggerMode.source = 0;
error = ppCameras[i]->SetTriggerMode( &triggerMode );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
#endif
//settings for version 1.0 fmf header
fmfVersion = 1;
sizeHeight = fmt7ImageSettings.height;
sizeWidth = fmt7ImageSettings.width;
bytesPerChunk = sizeHeight*sizeWidth + sizeof(double);
sprintf_s(fname[i], "E:\\Cam%d-%d%02d%02dT%02d%02d%02d.fmf", i, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
remove(fname[i]);
fout[i] = fopen(fname[i], "wb");
if(fout[i]==NULL)
{
printf("\nError opening FMF writer. Recording terminated.");
return -1;
}
//write FMF header data
fwrite(&fmfVersion, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeHeight, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeWidth, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&bytesPerChunk, sizeof(unsigned __int64), 1, fout[i]);
fwrite(&nframes, sizeof(unsigned __int64), 1, fout[i]);
if (i == 0)
{
sprintf_s(flogname, "E:\\log-%d%02d%02dT%02d%02d%02d.txt", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
remove(flogname);
flog = fopen(flogname, "w");
if(flog==NULL)
{
printf("\nError creating log file. Recording terminated.");
return -1;
}
}
sprintf_s(wname[i], "camera view %d", i);
}
//Starting individual cameras
for (unsigned int i = 0; i < numCameras; i++)
{
error = ppCameras[i]->StartCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
getchar();
return -1;
}
}
//Retrieve frame rate property
Property frmRate;
frmRate.type = FRAME_RATE;
error = ppCameras[0]->GetProperty( &frmRate );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "\nFrame rate is %3.2f fps\n", frmRate.absValue );
printf("\nGrabbing ...\n");
//OpenMP parallel execution of camera streaming and recording to uncompressed fmf format videos
omp_set_nested(1);
#pragma omp parallel for num_threads(numCameras)
for (int i = 0; i < numCameras; i++ )
{
nframesRun = (unsigned __int64)RunSingleCamera(i, nframes);
}
printf( "\nFinished grabbing %d images\n", nframesRun );
for (unsigned int i = 0; i < numCameras; i++ )
{
//check if number of frames streamed from the camera were the same as what was initially set
if (nframesRun != nframes)
{
//seek to location in file where nframes is stored and replace
fseek (fout[i], 20 , SEEK_SET );
fwrite(&nframesRun, sizeof(unsigned __int64), 1, fout[i]);
}
// close fmf flies
fclose(fout[i]);
// Stop capturing images
ppCameras[i]->StopCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
fclose(flog);
#if TRIGGER_CAMERA
// Turn off trigger mode
triggerMode.onOff = false;
error = ppCameras[i]->SetTriggerMode( &triggerMode );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
#endif
// Disconnect the camera
ppCameras[i]->Disconnect();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Delete camera instances
delete ppCameras[i];
}
// Free up memory
delete [] ppCameras;
printf("Done! Press Enter to exit...\n");
getchar();
return 0;
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/util/binarymessagereader.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-sstable/sstablewriter.h>
#include <fnord-sstable/sstablereader.h>
#include <fnord-tsdb/RecordSet.h>
namespace fnord {
namespace tsdb {
RecordRef::RecordRef(
uint64_t _record_id,
uint64_t _time,
const Buffer& _record) :
record_id(_record_id),
time(_time),
record(_record) {}
RecordSet::RecordSet(
const String& filename_prefix,
RecordSetState state /* = RecordSetState{} */) :
filename_prefix_(filename_prefix),
state_(state),
max_datafile_size_(kDefaultMaxDatafileSize),
version_(0) {
auto id_index_fn = [this] (uint64_t id, const void* data, size_t size) {
commitlog_ids_.emplace(id);
};
for (const auto& o : state_.old_commitlogs) {
loadCommitlog(o, id_index_fn);
}
if (!state.commitlog.isEmpty()) {
loadCommitlog(state.commitlog.get(), id_index_fn);
}
}
RecordSet::RecordSetState RecordSet::getState() const {
std::unique_lock<std::mutex> lk(mutex_);
return state_;
}
size_t RecordSet::version() const {
std::unique_lock<std::mutex> lk(mutex_);
return version_;
}
size_t RecordSet::commitlogSize() const {
std::unique_lock<std::mutex> lk(mutex_);
return commitlog_ids_.size();
}
void RecordSet::addRecord(uint64_t record_id, const Buffer& message) {
util::BinaryMessageWriter buf;
buf.appendUInt64(record_id);
buf.appendVarUInt(message.size());
buf.append(message.data(), message.size());
std::unique_lock<std::mutex> lk(mutex_);
if (commitlog_ids_.count(record_id) > 0) {
return;
}
addRecords(buf);
commitlog_ids_.emplace(record_id);
}
void RecordSet::addRecords(const Vector<RecordRef>& records) {
std::unique_lock<std::mutex> lk(mutex_);
util::BinaryMessageWriter buf;
for (const auto& rec : records) {
if (commitlog_ids_.count(rec.record_id) > 0) {
continue;
}
buf.appendUInt64(rec.record_id);
buf.appendVarUInt(rec.record.size());
buf.append(rec.record.data(), rec.record.size());
}
if (buf.size() == 0) {
return;
}
addRecords(buf);
for (const auto& rec : records) {
commitlog_ids_.emplace(rec.record_id);
}
}
void RecordSet::addRecords(const util::BinaryMessageWriter& buf) {
String commitlog;
uint64_t commitlog_size;
if (state_.commitlog.isEmpty()) {
commitlog = filename_prefix_ + rnd_.hex64() + ".log";
commitlog_size = 0;
++version_;
} else {
commitlog = state_.commitlog.get();
commitlog_size = state_.commitlog_size;
}
auto file = File::openFile(commitlog, File::O_WRITE | File::O_CREATEOROPEN);
file.truncate(sizeof(uint64_t) + commitlog_size + buf.size());
file.seekTo(sizeof(uint64_t) + commitlog_size);
file.write(buf.data(), buf.size());
// FIXPAUL fsync here for non order preserving storage?
commitlog_size += buf.size();
file.seekTo(0);
file.write(&commitlog_size, sizeof(commitlog_size));
state_.commitlog = Some(commitlog);
state_.commitlog_size = commitlog_size;
}
void RecordSet::rollCommitlog() {
if (state_.commitlog.isEmpty()) {
return;
}
auto old_log = state_.commitlog.get();
FileUtil::truncate(old_log, state_.commitlog_size + sizeof(uint64_t));
state_.old_commitlogs.emplace(old_log);
state_.commitlog = None<String>();
state_.commitlog_size = 0;
++version_;
}
void RecordSet::compact() {
Set<String> deleted_files;
compact(&deleted_files);
}
void RecordSet::compact(Set<String>* deleted_files) {
std::unique_lock<std::mutex> compact_lk(compact_mutex_, std::defer_lock);
if (!compact_lk.try_lock()) {
return; // compaction is already running
}
std::unique_lock<std::mutex> lk(mutex_);
rollCommitlog();
auto snap = state_;
lk.unlock();
if (snap.old_commitlogs.size() == 0) {
return;
}
auto outfile_path = filename_prefix_ + rnd_.hex64() + ".sst";
auto outfile = sstable::SSTableWriter::create(
outfile_path + "~",
sstable::IndexProvider{},
nullptr,
0);
size_t outfile_nrecords = 0;
size_t outfile_offset = 0;
Set<uint64_t> old_id_set;
Set<uint64_t> new_id_set;
bool rewrite_last =
snap.datafiles.size() > 0 &&
FileUtil::size(snap.datafiles.back().filename) < max_datafile_size_;
if (rewrite_last) {
outfile_offset = snap.datafiles.back().offset;
} else {
outfile_offset = snap.datafiles.size() > 0 ?
snap.datafiles.back().offset + snap.datafiles.back().num_records :
0;
}
for (int j = 0; j < snap.datafiles.size(); ++j) {
sstable::SSTableReader reader(snap.datafiles[j].filename);
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
RAISE(kRuntimeError, "invalid row");
}
uint64_t msgid = *((uint64_t*) key);
old_id_set.emplace(msgid);
if (rewrite_last && j + 1 == snap.datafiles.size()) {
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
outfile->appendRow(key, key_size, data, data_size);
++outfile_nrecords;
}
if (!cursor->next()) {
break;
}
}
}
for (const auto& cl : snap.old_commitlogs) {
loadCommitlog(cl, [this, &outfile, &old_id_set, &new_id_set, &outfile_nrecords] (
uint64_t id,
const void* data,
size_t size) {
if (new_id_set.count(id) > 0) {
return;
}
new_id_set.emplace(id);
if (old_id_set.count(id) > 0) {
return;
}
outfile->appendRow(&id, sizeof(id), data, size);
++outfile_nrecords;
});
}
if (outfile_nrecords == 0) {
return;
}
outfile->finalize();
FileUtil::mv(outfile_path + "~", outfile_path);
lk.lock();
if (rewrite_last) {
deleted_files->emplace(state_.datafiles.back().filename);
state_.datafiles.pop_back();
}
state_.datafiles.emplace_back(DatafileRef {
.filename = outfile_path,
.num_records = outfile_nrecords,
.offset = outfile_offset
});
for (const auto& cl : snap.old_commitlogs) {
state_.old_commitlogs.erase(cl);
deleted_files->emplace(cl);
}
for (const auto& id : new_id_set) {
commitlog_ids_.erase(id);
}
++version_;
}
void RecordSet::loadCommitlog(
const String& filename,
Function<void (uint64_t, const void*, size_t)> fn) {
io::MmappedFile mmap(File::openFile(filename, File::O_READ));
util::BinaryMessageReader reader(mmap.data(), mmap.size());
auto limit = *reader.readUInt64() + sizeof(uint64_t);
while (reader.position() < limit) {
auto id = *reader.readUInt64();
auto len = reader.readVarUInt();
auto data = reader.read(len);
fn(id, data, len);
}
}
uint64_t RecordSet::numRecords() const {
uint64_t res = 0;
std::unique_lock<std::mutex> lk(mutex_);
for (const auto& df : state_.datafiles) {
res += df.num_records;
}
return res;
}
uint64_t RecordSet::firstOffset() const {
std::unique_lock<std::mutex> lk(mutex_);
if (state_.datafiles.size() == 0) {
return 0;
} else {
return state_.datafiles.front().offset;
}
}
uint64_t RecordSet::lastOffset() const {
std::unique_lock<std::mutex> lk(mutex_);
if (state_.datafiles.size() == 0) {
return 0;
} else {
return state_.datafiles.back().offset + state_.datafiles.back().num_records;
}
}
void RecordSet::fetchRecords(
uint64_t offset,
uint64_t limit,
Function<void (uint64_t record_id, const void* record_data, size_t record_size)> fn) {
Set<uint64_t> res;
std::unique_lock<std::mutex> lk(mutex_);
auto datafiles = state_.datafiles;
lk.unlock();
if (datafiles.size() == 0) {
return;
}
size_t o = datafiles.front().offset;
if (o > offset) {
RAISEF(kRuntimeError, "offset was garbage collected: $0", offset);
}
size_t l = 0;
for (const auto& datafile : datafiles) {
if (o + datafile.num_records <= offset) {
o += datafile.num_records;
continue;
}
sstable::SSTableReader reader(datafile.filename);
auto cursor = reader.getCursor();
while (cursor->valid()) {
if (++o > offset) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
RAISE(kRuntimeError, "invalid row");
}
uint64_t msgid = *((uint64_t*) key);
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
fn(msgid, data, data_size);
if (++l == limit) {
return;
}
}
if (!cursor->next()) {
break;
}
}
}
}
Set<uint64_t> RecordSet::listRecords() const {
Set<uint64_t> res;
std::unique_lock<std::mutex> lk(mutex_);
if (state_.datafiles.empty()) {
return res;
}
auto datafiles = state_.datafiles;
lk.unlock();
for (const auto& datafile : datafiles) {
sstable::SSTableReader reader(datafile.filename);
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
RAISE(kRuntimeError, "invalid row");
}
res.emplace(*((uint64_t*) key));
if (!cursor->next()) {
break;
}
}
}
return res;
}
Vector<String> RecordSet::listDatafiles() const {
std::unique_lock<std::mutex> lk(mutex_);
Vector<String> datafiles;
for (const auto& df : state_.datafiles) {
datafiles.emplace_back(df.filename);
}
return datafiles;
}
void RecordSet::setMaxDatafileSize(size_t size) {
max_datafile_size_ = size;
}
const String& RecordSet::filenamePrefix() const {
return filename_prefix_;
}
RecordSet::RecordSetState::RecordSetState() :
commitlog_size(0) {}
void RecordSet::RecordSetState::encode(
util::BinaryMessageWriter* writer) const {
Set<String> all_commitlogs = old_commitlogs;
if (!commitlog.isEmpty()) {
all_commitlogs.emplace(commitlog.get());
}
writer->appendVarUInt(datafiles.size());
for (const auto& d : datafiles) {
writer->appendVarUInt(d.num_records);
writer->appendVarUInt(d.offset);
writer->appendLenencString(d.filename);
}
writer->appendVarUInt(all_commitlogs.size());
for (const auto& cl : all_commitlogs) {
writer->appendLenencString(cl);
}
}
void RecordSet::RecordSetState::decode(util::BinaryMessageReader* reader) {
auto num_datafiles = reader->readVarUInt();
for (size_t i = 0; i < num_datafiles; ++i) {
auto num_records = reader->readVarUInt();
auto offset = reader->readVarUInt();
auto fname = reader->readLenencString();
datafiles.emplace_back(DatafileRef {
.filename = fname,
.num_records = num_records,
.offset = offset
});
}
auto num_commitlogs = reader->readVarUInt();
for (size_t i = 0; i < num_commitlogs; ++i) {
auto fname = reader->readLenencString();
old_commitlogs.emplace(fname);
}
}
} // namespace tsdb
} // namespace fnord
<commit_msg>delete commitlogs if they do not contain any unseen data<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/util/binarymessagereader.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-sstable/sstablewriter.h>
#include <fnord-sstable/sstablereader.h>
#include <fnord-tsdb/RecordSet.h>
namespace fnord {
namespace tsdb {
RecordRef::RecordRef(
uint64_t _record_id,
uint64_t _time,
const Buffer& _record) :
record_id(_record_id),
time(_time),
record(_record) {}
RecordSet::RecordSet(
const String& filename_prefix,
RecordSetState state /* = RecordSetState{} */) :
filename_prefix_(filename_prefix),
state_(state),
max_datafile_size_(kDefaultMaxDatafileSize),
version_(0) {
auto id_index_fn = [this] (uint64_t id, const void* data, size_t size) {
commitlog_ids_.emplace(id);
};
for (const auto& o : state_.old_commitlogs) {
loadCommitlog(o, id_index_fn);
}
if (!state.commitlog.isEmpty()) {
loadCommitlog(state.commitlog.get(), id_index_fn);
}
}
RecordSet::RecordSetState RecordSet::getState() const {
std::unique_lock<std::mutex> lk(mutex_);
return state_;
}
size_t RecordSet::version() const {
std::unique_lock<std::mutex> lk(mutex_);
return version_;
}
size_t RecordSet::commitlogSize() const {
std::unique_lock<std::mutex> lk(mutex_);
return commitlog_ids_.size();
}
void RecordSet::addRecord(uint64_t record_id, const Buffer& message) {
util::BinaryMessageWriter buf;
buf.appendUInt64(record_id);
buf.appendVarUInt(message.size());
buf.append(message.data(), message.size());
std::unique_lock<std::mutex> lk(mutex_);
if (commitlog_ids_.count(record_id) > 0) {
return;
}
addRecords(buf);
commitlog_ids_.emplace(record_id);
}
void RecordSet::addRecords(const Vector<RecordRef>& records) {
std::unique_lock<std::mutex> lk(mutex_);
util::BinaryMessageWriter buf;
for (const auto& rec : records) {
if (commitlog_ids_.count(rec.record_id) > 0) {
continue;
}
buf.appendUInt64(rec.record_id);
buf.appendVarUInt(rec.record.size());
buf.append(rec.record.data(), rec.record.size());
}
if (buf.size() == 0) {
return;
}
addRecords(buf);
for (const auto& rec : records) {
commitlog_ids_.emplace(rec.record_id);
}
}
void RecordSet::addRecords(const util::BinaryMessageWriter& buf) {
String commitlog;
uint64_t commitlog_size;
if (state_.commitlog.isEmpty()) {
commitlog = filename_prefix_ + rnd_.hex64() + ".log";
commitlog_size = 0;
++version_;
} else {
commitlog = state_.commitlog.get();
commitlog_size = state_.commitlog_size;
}
auto file = File::openFile(commitlog, File::O_WRITE | File::O_CREATEOROPEN);
file.truncate(sizeof(uint64_t) + commitlog_size + buf.size());
file.seekTo(sizeof(uint64_t) + commitlog_size);
file.write(buf.data(), buf.size());
// FIXPAUL fsync here for non order preserving storage?
commitlog_size += buf.size();
file.seekTo(0);
file.write(&commitlog_size, sizeof(commitlog_size));
state_.commitlog = Some(commitlog);
state_.commitlog_size = commitlog_size;
}
void RecordSet::rollCommitlog() {
if (state_.commitlog.isEmpty()) {
return;
}
auto old_log = state_.commitlog.get();
FileUtil::truncate(old_log, state_.commitlog_size + sizeof(uint64_t));
state_.old_commitlogs.emplace(old_log);
state_.commitlog = None<String>();
state_.commitlog_size = 0;
++version_;
}
void RecordSet::compact() {
Set<String> deleted_files;
compact(&deleted_files);
}
void RecordSet::compact(Set<String>* deleted_files) {
std::unique_lock<std::mutex> compact_lk(compact_mutex_, std::defer_lock);
if (!compact_lk.try_lock()) {
return; // compaction is already running
}
std::unique_lock<std::mutex> lk(mutex_);
rollCommitlog();
auto snap = state_;
lk.unlock();
if (snap.old_commitlogs.size() == 0) {
return;
}
auto outfile_path = filename_prefix_ + rnd_.hex64() + ".sst";
auto outfile = sstable::SSTableWriter::create(
outfile_path + "~",
sstable::IndexProvider{},
nullptr,
0);
size_t outfile_nrecords = 0;
size_t outfile_offset = 0;
Set<uint64_t> old_id_set;
Set<uint64_t> new_id_set;
bool rewrite_last =
snap.datafiles.size() > 0 &&
FileUtil::size(snap.datafiles.back().filename) < max_datafile_size_;
if (rewrite_last) {
outfile_offset = snap.datafiles.back().offset;
} else {
outfile_offset = snap.datafiles.size() > 0 ?
snap.datafiles.back().offset + snap.datafiles.back().num_records :
0;
}
for (int j = 0; j < snap.datafiles.size(); ++j) {
sstable::SSTableReader reader(snap.datafiles[j].filename);
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
RAISE(kRuntimeError, "invalid row");
}
uint64_t msgid = *((uint64_t*) key);
old_id_set.emplace(msgid);
if (rewrite_last && j + 1 == snap.datafiles.size()) {
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
outfile->appendRow(key, key_size, data, data_size);
++outfile_nrecords;
}
if (!cursor->next()) {
break;
}
}
}
for (const auto& cl : snap.old_commitlogs) {
loadCommitlog(cl, [this, &outfile, &old_id_set, &new_id_set, &outfile_nrecords] (
uint64_t id,
const void* data,
size_t size) {
if (new_id_set.count(id) > 0) {
return;
}
new_id_set.emplace(id);
if (old_id_set.count(id) > 0) {
return;
}
outfile->appendRow(&id, sizeof(id), data, size);
++outfile_nrecords;
});
}
if (outfile_nrecords == 0) {
FileUtil::rm(outfile_path + "~");
} else {
outfile->finalize();
FileUtil::mv(outfile_path + "~", outfile_path);
}
lk.lock();
if (rewrite_last) {
deleted_files->emplace(state_.datafiles.back().filename);
state_.datafiles.pop_back();
}
if (outfile_nrecords > 0) {
state_.datafiles.emplace_back(DatafileRef {
.filename = outfile_path,
.num_records = outfile_nrecords,
.offset = outfile_offset
});
}
for (const auto& cl : snap.old_commitlogs) {
state_.old_commitlogs.erase(cl);
deleted_files->emplace(cl);
}
for (const auto& id : new_id_set) {
commitlog_ids_.erase(id);
}
++version_;
}
void RecordSet::loadCommitlog(
const String& filename,
Function<void (uint64_t, const void*, size_t)> fn) {
io::MmappedFile mmap(File::openFile(filename, File::O_READ));
util::BinaryMessageReader reader(mmap.data(), mmap.size());
auto limit = *reader.readUInt64() + sizeof(uint64_t);
while (reader.position() < limit) {
auto id = *reader.readUInt64();
auto len = reader.readVarUInt();
auto data = reader.read(len);
fn(id, data, len);
}
}
uint64_t RecordSet::numRecords() const {
uint64_t res = 0;
std::unique_lock<std::mutex> lk(mutex_);
for (const auto& df : state_.datafiles) {
res += df.num_records;
}
return res;
}
uint64_t RecordSet::firstOffset() const {
std::unique_lock<std::mutex> lk(mutex_);
if (state_.datafiles.size() == 0) {
return 0;
} else {
return state_.datafiles.front().offset;
}
}
uint64_t RecordSet::lastOffset() const {
std::unique_lock<std::mutex> lk(mutex_);
if (state_.datafiles.size() == 0) {
return 0;
} else {
return state_.datafiles.back().offset + state_.datafiles.back().num_records;
}
}
void RecordSet::fetchRecords(
uint64_t offset,
uint64_t limit,
Function<void (uint64_t record_id, const void* record_data, size_t record_size)> fn) {
Set<uint64_t> res;
std::unique_lock<std::mutex> lk(mutex_);
auto datafiles = state_.datafiles;
lk.unlock();
if (datafiles.size() == 0) {
return;
}
size_t o = datafiles.front().offset;
if (o > offset) {
RAISEF(kRuntimeError, "offset was garbage collected: $0", offset);
}
size_t l = 0;
for (const auto& datafile : datafiles) {
if (o + datafile.num_records <= offset) {
o += datafile.num_records;
continue;
}
sstable::SSTableReader reader(datafile.filename);
auto cursor = reader.getCursor();
while (cursor->valid()) {
if (++o > offset) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
RAISE(kRuntimeError, "invalid row");
}
uint64_t msgid = *((uint64_t*) key);
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
fn(msgid, data, data_size);
if (++l == limit) {
return;
}
}
if (!cursor->next()) {
break;
}
}
}
}
Set<uint64_t> RecordSet::listRecords() const {
Set<uint64_t> res;
std::unique_lock<std::mutex> lk(mutex_);
if (state_.datafiles.empty()) {
return res;
}
auto datafiles = state_.datafiles;
lk.unlock();
for (const auto& datafile : datafiles) {
sstable::SSTableReader reader(datafile.filename);
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
RAISE(kRuntimeError, "invalid row");
}
res.emplace(*((uint64_t*) key));
if (!cursor->next()) {
break;
}
}
}
return res;
}
Vector<String> RecordSet::listDatafiles() const {
std::unique_lock<std::mutex> lk(mutex_);
Vector<String> datafiles;
for (const auto& df : state_.datafiles) {
datafiles.emplace_back(df.filename);
}
return datafiles;
}
void RecordSet::setMaxDatafileSize(size_t size) {
max_datafile_size_ = size;
}
const String& RecordSet::filenamePrefix() const {
return filename_prefix_;
}
RecordSet::RecordSetState::RecordSetState() :
commitlog_size(0) {}
void RecordSet::RecordSetState::encode(
util::BinaryMessageWriter* writer) const {
Set<String> all_commitlogs = old_commitlogs;
if (!commitlog.isEmpty()) {
all_commitlogs.emplace(commitlog.get());
}
writer->appendVarUInt(datafiles.size());
for (const auto& d : datafiles) {
writer->appendVarUInt(d.num_records);
writer->appendVarUInt(d.offset);
writer->appendLenencString(d.filename);
}
writer->appendVarUInt(all_commitlogs.size());
for (const auto& cl : all_commitlogs) {
writer->appendLenencString(cl);
}
}
void RecordSet::RecordSetState::decode(util::BinaryMessageReader* reader) {
auto num_datafiles = reader->readVarUInt();
for (size_t i = 0; i < num_datafiles; ++i) {
auto num_records = reader->readVarUInt();
auto offset = reader->readVarUInt();
auto fname = reader->readLenencString();
datafiles.emplace_back(DatafileRef {
.filename = fname,
.num_records = num_records,
.offset = offset
});
}
auto num_commitlogs = reader->readVarUInt();
for (size_t i = 0; i < num_commitlogs; ++i) {
auto fname = reader->readLenencString();
old_commitlogs.emplace(fname);
}
}
} // namespace tsdb
} // namespace fnord
<|endoftext|> |
<commit_before>#include "tests.h"
using namespace swoole;
static void coro1(void *arg)
{
int cid = coroutine_get_cid();
coroutine_t *co = coroutine_get_by_id(cid);
coroutine_yield(co);
}
TEST(coroutine, create)
{
int cid = coroutine_create(coro1, NULL);
ASSERT_GT(cid, 0);
coroutine_resume(coroutine_get_by_id(cid));
}
static void coro2(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9801, 0.5);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ECONNREFUSED);
}
TEST(coroutine, socket_connect_refused)
{
int cid = coroutine_create(coro2, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro3(void *arg)
{
Socket sock(SW_SOCK_TCP);
sock.setTimeout(0.5);
bool retval = sock.connect("192.0.0.1", 9801);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ETIMEDOUT);
}
TEST(coroutine, socket_connect_timeout)
{
int cid = coroutine_create(coro3, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro4(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("www.baidu.com", 80, 0.5);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_connect_with_dns)
{
int cid = coroutine_create(coro4, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro5(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("echo", 5);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(strcmp(buf, "hello world\n"), 0);
}
TEST(coroutine, socket_recv_success)
{
int cid = coroutine_create(coro5, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro6(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("close", 6);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(n, 0);
}
TEST(coroutine, socket_recv_fail)
{
int cid = coroutine_create(coro6, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
TEST(coroutine, socket_bind_success)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
}
TEST(coroutine, socket_bind_fail)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("192.111.11.1", 9909);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, EADDRNOTAVAIL);
}
TEST(coroutine, socket_listen)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
}
/**
* Accept
*/
static void coro7(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
Socket *conn = sock.accept();
ASSERT_NE(conn, nullptr);
}
/**
* Connect
*/
static void coro8(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9909, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_accept)
{
coroutine_create(coro7, NULL);
coroutine_create(coro8, NULL);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro9(void *arg)
{
Socket sock(SW_SOCK_TCP);
auto retval = sock.resolve("www.qq.com");
ASSERT_EQ(retval, "180.163.26.39");
}
TEST(coroutine, socket_resolve)
{
coroutine_create(coro9, NULL);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
#define CID_ALLOC_PRINT 0
TEST(coroutine, cid_alloc)
{
//alloc [1] full
for (int i = 0; i < 65536 * 8; i++)
{
int cid = coroutine_test_alloc_cid();
ASSERT_GT(cid, 0);
#if CID_ALLOC_PRINT
if (i % 1000 == 0)
{
printf("cid=%d\n", cid);
}
#endif
}
//limit
{
int cid = coroutine_test_alloc_cid();
ASSERT_EQ(cid, CORO_LIMIT);
}
//free
for (int i = 1; i < 65536; i++)
{
int cid = i * 7;
coroutine_test_free_cid(cid);
#if CID_ALLOC_PRINT
if (i % 1000 == 0)
{
printf("free cid=%d\n", cid);
}
#endif
}
//alloc [2]
for (int i = 0; i < 65536 / 2; i++)
{
int cid = coroutine_test_alloc_cid();
ASSERT_GT(cid, 0);
#if CID_ALLOC_PRINT
if (i % 1000 == 0)
{
printf("cid=%d\n", cid);
}
#endif
}
}
<commit_msg>fix core_test errors<commit_after>#include "tests.h"
using namespace swoole;
static void coro1(void *arg)
{
int cid = coroutine_get_current_cid();
coroutine_t *co = coroutine_get_by_id(cid);
coroutine_yield(co);
}
TEST(coroutine, create)
{
int cid = coroutine_create(coro1, NULL);
ASSERT_GT(cid, 0);
coroutine_resume(coroutine_get_by_id(cid));
}
static void coro2(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9801, 0.5);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ECONNREFUSED);
}
TEST(coroutine, socket_connect_refused)
{
int cid = coroutine_create(coro2, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro3(void *arg)
{
Socket sock(SW_SOCK_TCP);
sock.setTimeout(0.5);
bool retval = sock.connect("192.0.0.1", 9801);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ETIMEDOUT);
}
TEST(coroutine, socket_connect_timeout)
{
int cid = coroutine_create(coro3, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro4(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("www.baidu.com", 80, 0.5);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_connect_with_dns)
{
int cid = coroutine_create(coro4, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro5(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("echo", 5);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(strcmp(buf, "hello world\n"), 0);
}
TEST(coroutine, socket_recv_success)
{
int cid = coroutine_create(coro5, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro6(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("close", 6);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(n, 0);
}
TEST(coroutine, socket_recv_fail)
{
int cid = coroutine_create(coro6, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
TEST(coroutine, socket_bind_success)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
}
TEST(coroutine, socket_bind_fail)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("192.111.11.1", 9909);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, EADDRNOTAVAIL);
}
TEST(coroutine, socket_listen)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
}
/**
* Accept
*/
static void coro7(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
Socket *conn = sock.accept();
ASSERT_NE(conn, nullptr);
}
/**
* Connect
*/
static void coro8(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9909, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_accept)
{
coroutine_create(coro7, NULL);
coroutine_create(coro8, NULL);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro9(void *arg)
{
Socket sock(SW_SOCK_TCP);
auto retval = sock.resolve("www.qq.com");
ASSERT_EQ(retval, "180.163.26.39");
}
TEST(coroutine, socket_resolve)
{
coroutine_create(coro9, NULL);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
#define CID_ALLOC_PRINT 0
TEST(coroutine, cid_alloc)
{
//alloc [1] full
for (int i = 0; i < 65536 * 8; i++)
{
int cid = coroutine_test_alloc_cid();
ASSERT_GT(cid, 0);
#if CID_ALLOC_PRINT
if (i % 1000 == 0)
{
printf("cid=%d\n", cid);
}
#endif
}
//limit
{
int cid = coroutine_test_alloc_cid();
ASSERT_EQ(cid, CORO_LIMIT);
}
//free
for (int i = 1; i < 65536; i++)
{
int cid = i * 7;
coroutine_test_free_cid(cid);
#if CID_ALLOC_PRINT
if (i % 1000 == 0)
{
printf("free cid=%d\n", cid);
}
#endif
}
//alloc [2]
for (int i = 0; i < 65536 / 2; i++)
{
int cid = coroutine_test_alloc_cid();
ASSERT_GT(cid, 0);
#if CID_ALLOC_PRINT
if (i % 1000 == 0)
{
printf("cid=%d\n", cid);
}
#endif
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2007 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// $Id$
#include "sqlite_datasource.hpp"
#include "sqlite_featureset.hpp"
// mapnik
#include <mapnik/ptree_helpers.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(sqlite_datasource)
using mapnik::Envelope;
using mapnik::coord2d;
using mapnik::query;
using mapnik::featureset_ptr;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
using mapnik::datasource_exception;
sqlite_datasource::sqlite_datasource(parameters const& params)
: datasource(params),
extent_(),
extent_initialized_(false),
type_(datasource::Vector),
table_(*params.get<std::string>("table","")),
metadata_(*params.get<std::string>("metadata","")),
geometry_field_(*params.get<std::string>("geometry_field","geom")),
key_field_(*params.get<std::string>("key_field","PK_UID")),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> paramater");
multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false);
use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true);
dataset_ = new sqlite_connection (*file);
boost::optional<std::string> ext = params_.get<std::string>("extent");
if (ext)
{
boost::char_separator<char> sep(",");
boost::tokenizer<boost::char_separator<char> > tok(*ext,sep);
unsigned i = 0;
bool success = false;
double d[4];
for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin();
beg!=tok.end();++beg)
{
try
{
d[i] = boost::lexical_cast<double>(*beg);
}
catch (boost::bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
break;
}
if (i==3)
{
success = true;
break;
}
++i;
}
if (success)
{
extent_.init(d[0],d[1],d[2],d[3]);
extent_initialized_ = true;
}
}
if (metadata_ != "" && ! extent_initialized_)
{
std::ostringstream s;
s << "select xmin, ymin, xmax, ymax from " << metadata_;
s << " where lower(f_table_name) = lower('" << table_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
if (use_spatial_index_)
{
std::ostringstream s;
s << "select count (*) sqlite_master";
s << " where name = 'idx_" << table_ << "_" << geometry_field_ << "'";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
if (rs->column_integer (0) == 0)
{
#ifdef MAPNIK_DEBUG
clog << "cannot use the spatial index " << endl;
#endif
use_spatial_index_ = false;
}
}
}
{
/*
XXX - This is problematic, if we don't have at least a row,
we cannot determine the right columns types and names
as all column_type are SQLITE_NULL
*/
std::ostringstream s;
s << "select * from " << table_ << " limit 1";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
for (int i = 0; i < rs->column_count (); ++i)
{
const int type_oid = rs->column_type (i);
const char* fld_name = rs->column_name (i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
break;
case SQLITE_FLOAT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
break;
case SQLITE_TEXT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
case SQLITE_NULL:
case SQLITE_BLOB:
break;
default:
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
sqlite_datasource::~sqlite_datasource()
{
delete dataset_;
}
std::string const sqlite_datasource::name_="sqlite";
std::string sqlite_datasource::name()
{
return name_;
}
int sqlite_datasource::type() const
{
return type_;
}
Envelope<double> sqlite_datasource::envelope() const
{
return extent_;
}
layer_descriptor sqlite_datasource::get_descriptor() const
{
return desc_;
}
featureset_ptr sqlite_datasource::features(query const& q) const
{
if (dataset_)
{
mapnik::Envelope<double> const& e = q.get_bbox();
std::ostringstream s;
s << "select " << geometry_field_ << "," << key_field_;
std::set<std::string> const& props = q.property_names();
std::set<std::string>::const_iterator pos = props.begin();
std::set<std::string>::const_iterator end = props.end();
while (pos != end)
{
s << "," << *pos << "";
++pos;
}
s << " from " << table_;
if (use_spatial_index_)
{
s << std::setprecision(16);
s << " where rowid in (select pkid from idx_" << table_ << "_" << geometry_field_;
s << " where xmax>=" << e.minx() << " and xmin<=" << e.maxx() ;
s << " and ymax>=" << e.miny() << " and ymin<=" << e.maxy() << ")";
}
#ifdef MAPNIK_DEBUG
std::cerr << "executing sql: " << s.str() << "\n";
#endif
boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), multiple_geometries_));
}
return featureset_ptr();
}
featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const
{
#if 0
if (dataset_ && layer_)
{
OGRPoint point;
point.setX (pt.x);
point.setY (pt.y);
layer_->SetSpatialFilter (&point);
return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_));
}
#endif
return featureset_ptr();
}
<commit_msg>+ corrected SQL <commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2007 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// $Id$
#include "sqlite_datasource.hpp"
#include "sqlite_featureset.hpp"
// mapnik
#include <mapnik/ptree_helpers.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(sqlite_datasource)
using mapnik::Envelope;
using mapnik::coord2d;
using mapnik::query;
using mapnik::featureset_ptr;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
using mapnik::datasource_exception;
sqlite_datasource::sqlite_datasource(parameters const& params)
: datasource(params),
extent_(),
extent_initialized_(false),
type_(datasource::Vector),
table_(*params.get<std::string>("table","")),
metadata_(*params.get<std::string>("metadata","")),
geometry_field_(*params.get<std::string>("geometry_field","geom")),
key_field_(*params.get<std::string>("key_field","PK_UID")),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> paramater");
multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false);
use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true);
dataset_ = new sqlite_connection (*file);
boost::optional<std::string> ext = params_.get<std::string>("extent");
if (ext)
{
boost::char_separator<char> sep(",");
boost::tokenizer<boost::char_separator<char> > tok(*ext,sep);
unsigned i = 0;
bool success = false;
double d[4];
for (boost::tokenizer<boost::char_separator<char> >::iterator beg=tok.begin();
beg!=tok.end();++beg)
{
try
{
d[i] = boost::lexical_cast<double>(*beg);
}
catch (boost::bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
break;
}
if (i==3)
{
success = true;
break;
}
++i;
}
if (success)
{
extent_.init(d[0],d[1],d[2],d[3]);
extent_initialized_ = true;
}
}
if (metadata_ != "" && ! extent_initialized_)
{
std::ostringstream s;
s << "select xmin, ymin, xmax, ymax from " << metadata_;
s << " where lower(f_table_name) = lower('" << table_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
if (use_spatial_index_)
{
std::ostringstream s;
s << "select count (*) from sqlite_master";
s << " where name = 'idx_" << table_ << "_" << geometry_field_ << "'";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
if (rs->column_integer (0) == 0)
{
#ifdef MAPNIK_DEBUG
clog << "cannot use the spatial index " << endl;
#endif
use_spatial_index_ = false;
}
}
}
{
/*
XXX - This is problematic, if we don't have at least a row,
we cannot determine the right columns types and names
as all column_type are SQLITE_NULL
*/
std::ostringstream s;
s << "select * from " << table_ << " limit 1";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
for (int i = 0; i < rs->column_count (); ++i)
{
const int type_oid = rs->column_type (i);
const char* fld_name = rs->column_name (i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
break;
case SQLITE_FLOAT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
break;
case SQLITE_TEXT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
case SQLITE_NULL:
case SQLITE_BLOB:
break;
default:
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
sqlite_datasource::~sqlite_datasource()
{
delete dataset_;
}
std::string const sqlite_datasource::name_="sqlite";
std::string sqlite_datasource::name()
{
return name_;
}
int sqlite_datasource::type() const
{
return type_;
}
Envelope<double> sqlite_datasource::envelope() const
{
return extent_;
}
layer_descriptor sqlite_datasource::get_descriptor() const
{
return desc_;
}
featureset_ptr sqlite_datasource::features(query const& q) const
{
if (dataset_)
{
mapnik::Envelope<double> const& e = q.get_bbox();
std::ostringstream s;
s << "select " << geometry_field_ << "," << key_field_;
std::set<std::string> const& props = q.property_names();
std::set<std::string>::const_iterator pos = props.begin();
std::set<std::string>::const_iterator end = props.end();
while (pos != end)
{
s << "," << *pos << "";
++pos;
}
s << " from " << table_;
if (use_spatial_index_)
{
s << std::setprecision(16);
s << " where rowid in (select pkid from idx_" << table_ << "_" << geometry_field_;
s << " where xmax>=" << e.minx() << " and xmin<=" << e.maxx() ;
s << " and ymax>=" << e.miny() << " and ymin<=" << e.maxy() << ")";
}
#ifdef MAPNIK_DEBUG
std::cerr << "executing sql: " << s.str() << "\n";
#endif
boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), multiple_geometries_));
}
return featureset_ptr();
}
featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const
{
#if 0
if (dataset_ && layer_)
{
OGRPoint point;
point.setX (pt.x);
point.setY (pt.y);
layer_->SetSpatialFilter (&point);
return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_));
}
#endif
return featureset_ptr();
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef CIRCULAR_BUFFER_HH_
#define CIRCULAR_BUFFER_HH_
#include "transfer.hh"
#include "bitops.hh"
#include <memory>
#include <algorithm>
namespace seastar {
/// A growable double-ended queue container that can be efficiently
/// extended (and shrunk) from both ends. Implementation is a single
/// storage vector.
///
/// Similar to libstdc++'s std::deque, except that it uses a single
/// level store, and so is more efficient for simple stored items.
/// Similar to boost::circular_buffer_space_optimized, except it uses
/// uninitialized storage for unoccupied elements (and thus move/copy
/// constructors instead of move/copy assignments, which are less
/// efficient).
///
/// The storage of the circular_buffer is expanded automatically in
/// exponential increments.
/// When adding new elements:
/// * if size + 1 > capacity: all iterators and references are
/// invalidated,
/// * otherwise only the begin() or end() iterator is invalidated:
/// * push_front() and emplace_front() will invalidate begin() and
/// * push_back() and emplace_back() will invalidate end().
/// Removing elements never invalidates any references and only
/// invalidates begin() or end() iterators:
/// * pop_front() will invalidate begin() and
/// * pop_back() will invalidate end().
/// reserve() may also invalidate all iterators and references.
template <typename T, typename Alloc = std::allocator<T>>
class circular_buffer {
struct impl : Alloc {
T* storage = nullptr;
// begin, end interpreted (mod capacity)
size_t begin = 0;
size_t end = 0;
size_t capacity = 0;
};
impl _impl;
public:
using value_type = T;
using size_type = size_t;
using reference = T&;
using pointer = T*;
using const_reference = const T&;
using const_pointer = const T*;
public:
circular_buffer() = default;
circular_buffer(circular_buffer&& X) noexcept;
circular_buffer(const circular_buffer& X) = delete;
~circular_buffer();
circular_buffer& operator=(const circular_buffer&) = delete;
circular_buffer& operator=(circular_buffer&& b) noexcept;
void push_front(const T& data);
void push_front(T&& data);
template <typename... A>
void emplace_front(A&&... args);
void push_back(const T& data);
void push_back(T&& data);
template <typename... A>
void emplace_back(A&&... args);
T& front();
T& back();
void pop_front();
void pop_back();
bool empty() const;
size_t size() const;
size_t capacity() const;
void reserve(size_t);
T& operator[](size_t idx);
template <typename Func>
void for_each(Func func);
// access an element, may return wrong or destroyed element
// only useful if you do not rely on data accuracy (e.g. prefetch)
T& access_element_unsafe(size_t idx);
private:
void expand();
void expand(size_t);
void maybe_expand(size_t nr = 1);
size_t mask(size_t idx) const;
template<typename CB, typename ValueType>
struct cbiterator : std::iterator<std::random_access_iterator_tag, ValueType> {
typedef std::iterator<std::random_access_iterator_tag, ValueType> super_t;
ValueType& operator*() const { return cb->_impl.storage[cb->mask(idx)]; }
ValueType* operator->() const { return &cb->_impl.storage[cb->mask(idx)]; }
// prefix
cbiterator<CB, ValueType>& operator++() {
idx++;
return *this;
}
// postfix
cbiterator<CB, ValueType> operator++(int unused) {
auto v = *this;
idx++;
return v;
}
// prefix
cbiterator<CB, ValueType>& operator--() {
idx--;
return *this;
}
// postfix
cbiterator<CB, ValueType> operator--(int unused) {
auto v = *this;
idx--;
return v;
}
cbiterator<CB, ValueType> operator+(typename super_t::difference_type n) const {
return cbiterator<CB, ValueType>(cb, idx + n);
}
cbiterator<CB, ValueType> operator-(typename super_t::difference_type n) const {
return cbiterator<CB, ValueType>(cb, idx - n);
}
cbiterator<CB, ValueType>& operator+=(typename super_t::difference_type n) {
idx += n;
return *this;
}
cbiterator<CB, ValueType>& operator-=(typename super_t::difference_type n) {
idx -= n;
return *this;
}
bool operator==(const cbiterator<CB, ValueType>& rhs) const {
return idx == rhs.idx;
}
bool operator!=(const cbiterator<CB, ValueType>& rhs) const {
return idx != rhs.idx;
}
bool operator<(const cbiterator<CB, ValueType>& rhs) const {
return idx < rhs.idx;
}
bool operator>(const cbiterator<CB, ValueType>& rhs) const {
return idx > rhs.idx;
}
bool operator>=(const cbiterator<CB, ValueType>& rhs) const {
return idx >= rhs.idx;
}
bool operator<=(const cbiterator<CB, ValueType>& rhs) const {
return idx <= rhs.idx;
}
typename super_t::difference_type operator-(const cbiterator<CB, ValueType>& rhs) const {
return idx - rhs.idx;
}
private:
CB* cb;
size_t idx;
cbiterator<CB, ValueType>(CB* b, size_t i) : cb(b), idx(i) {}
friend class circular_buffer;
};
friend class iterator;
public:
typedef cbiterator<circular_buffer, T> iterator;
typedef cbiterator<const circular_buffer, const T> const_iterator;
iterator begin() {
return iterator(this, _impl.begin);
}
const_iterator begin() const {
return const_iterator(this, _impl.begin);
}
iterator end() {
return iterator(this, _impl.end);
}
const_iterator end() const {
return const_iterator(this, _impl.end);
}
const_iterator cbegin() const {
return const_iterator(this, _impl.begin);
}
const_iterator cend() const {
return const_iterator(this, _impl.end);
}
iterator erase(iterator first, iterator last);
};
template <typename T, typename Alloc>
inline
size_t
circular_buffer<T, Alloc>::mask(size_t idx) const {
return idx & (_impl.capacity - 1);
}
template <typename T, typename Alloc>
inline
bool
circular_buffer<T, Alloc>::empty() const {
return _impl.begin == _impl.end;
}
template <typename T, typename Alloc>
inline
size_t
circular_buffer<T, Alloc>::size() const {
return _impl.end - _impl.begin;
}
template <typename T, typename Alloc>
inline
size_t
circular_buffer<T, Alloc>::capacity() const {
return _impl.capacity;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::reserve(size_t size) {
if (capacity() < size) {
// Make sure that the new capacity is a power of two.
expand(size_t(1) << log2ceil(size));
}
}
template <typename T, typename Alloc>
inline
circular_buffer<T, Alloc>::circular_buffer(circular_buffer&& x) noexcept
: _impl(std::move(x._impl)) {
x._impl = {};
}
template <typename T, typename Alloc>
inline
circular_buffer<T, Alloc>& circular_buffer<T, Alloc>::operator=(circular_buffer&& x) noexcept {
if (this != &x) {
this->~circular_buffer();
new (this) circular_buffer(std::move(x));
}
return *this;
}
template <typename T, typename Alloc>
template <typename Func>
inline
void
circular_buffer<T, Alloc>::for_each(Func func) {
auto s = _impl.storage;
auto m = _impl.capacity - 1;
for (auto i = _impl.begin; i != _impl.end; ++i) {
func(s[i & m]);
}
}
template <typename T, typename Alloc>
inline
circular_buffer<T, Alloc>::~circular_buffer() {
for_each([this] (T& obj) {
_impl.destroy(&obj);
});
_impl.deallocate(_impl.storage, _impl.capacity);
}
template <typename T, typename Alloc>
void
circular_buffer<T, Alloc>::expand() {
expand(std::max<size_t>(_impl.capacity * 2, 1));
}
template <typename T, typename Alloc>
void
circular_buffer<T, Alloc>::expand(size_t new_cap) {
auto new_storage = _impl.allocate(new_cap);
auto p = new_storage;
try {
for_each([this, &p] (T& obj) {
transfer_pass1(_impl, &obj, p);
p++;
});
} catch (...) {
while (p != new_storage) {
_impl.destroy(--p);
}
_impl.deallocate(new_storage, new_cap);
throw;
}
p = new_storage;
for_each([this, &p] (T& obj) {
transfer_pass2(_impl, &obj, p++);
});
std::swap(_impl.storage, new_storage);
std::swap(_impl.capacity, new_cap);
_impl.begin = 0;
_impl.end = p - _impl.storage;
_impl.deallocate(new_storage, new_cap);
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::maybe_expand(size_t nr) {
if (_impl.end - _impl.begin + nr > _impl.capacity) {
expand();
}
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_front(const T& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.begin - 1)];
_impl.construct(p, data);
--_impl.begin;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_front(T&& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.begin - 1)];
_impl.construct(p, std::move(data));
--_impl.begin;
}
template <typename T, typename Alloc>
template <typename... Args>
inline
void
circular_buffer<T, Alloc>::emplace_front(Args&&... args) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.begin - 1)];
_impl.construct(p, std::forward<Args>(args)...);
--_impl.begin;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_back(const T& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.end)];
_impl.construct(p, data);
++_impl.end;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_back(T&& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.end)];
_impl.construct(p, std::move(data));
++_impl.end;
}
template <typename T, typename Alloc>
template <typename... Args>
inline
void
circular_buffer<T, Alloc>::emplace_back(Args&&... args) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.end)];
_impl.construct(p, std::forward<Args>(args)...);
++_impl.end;
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::front() {
return _impl.storage[mask(_impl.begin)];
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::back() {
return _impl.storage[mask(_impl.end - 1)];
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::pop_front() {
_impl.destroy(&front());
++_impl.begin;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::pop_back() {
_impl.destroy(&back());
--_impl.end;
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::operator[](size_t idx) {
return _impl.storage[mask(_impl.begin + idx)];
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::access_element_unsafe(size_t idx) {
return _impl.storage[mask(_impl.begin + idx)];
}
template <typename T, typename Alloc>
inline
typename circular_buffer<T, Alloc>::iterator
circular_buffer<T, Alloc>::erase(iterator first, iterator last) {
static_assert(std::is_nothrow_move_assignable<T>::value, "erase() assumes move assignment does not throw");
if (first == last) {
return last;
}
// Move to the left or right depending on which would result in least amount of moves.
// This also guarantees that iterators will be stable when removing from either front or back.
if (std::distance(begin(), first) < std::distance(last, end())) {
auto new_start = std::move_backward(begin(), first, last);
auto i = begin();
while (i < new_start) {
_impl.destroy(&*i++);
}
_impl.begin = new_start.idx;
return last;
} else {
auto new_end = std::move(last, end(), first);
auto i = new_end;
auto e = end();
while (i < e) {
_impl.destroy(&*i++);
}
_impl.end = new_end.idx;
return first;
}
}
}
#endif /* CIRCULAR_BUFFER_HH_ */
<commit_msg>Add const version of subscript operator to circular_buffer<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef CIRCULAR_BUFFER_HH_
#define CIRCULAR_BUFFER_HH_
#include "transfer.hh"
#include "bitops.hh"
#include <memory>
#include <algorithm>
namespace seastar {
/// A growable double-ended queue container that can be efficiently
/// extended (and shrunk) from both ends. Implementation is a single
/// storage vector.
///
/// Similar to libstdc++'s std::deque, except that it uses a single
/// level store, and so is more efficient for simple stored items.
/// Similar to boost::circular_buffer_space_optimized, except it uses
/// uninitialized storage for unoccupied elements (and thus move/copy
/// constructors instead of move/copy assignments, which are less
/// efficient).
///
/// The storage of the circular_buffer is expanded automatically in
/// exponential increments.
/// When adding new elements:
/// * if size + 1 > capacity: all iterators and references are
/// invalidated,
/// * otherwise only the begin() or end() iterator is invalidated:
/// * push_front() and emplace_front() will invalidate begin() and
/// * push_back() and emplace_back() will invalidate end().
/// Removing elements never invalidates any references and only
/// invalidates begin() or end() iterators:
/// * pop_front() will invalidate begin() and
/// * pop_back() will invalidate end().
/// reserve() may also invalidate all iterators and references.
template <typename T, typename Alloc = std::allocator<T>>
class circular_buffer {
struct impl : Alloc {
T* storage = nullptr;
// begin, end interpreted (mod capacity)
size_t begin = 0;
size_t end = 0;
size_t capacity = 0;
};
impl _impl;
public:
using value_type = T;
using size_type = size_t;
using reference = T&;
using pointer = T*;
using const_reference = const T&;
using const_pointer = const T*;
public:
circular_buffer() = default;
circular_buffer(circular_buffer&& X) noexcept;
circular_buffer(const circular_buffer& X) = delete;
~circular_buffer();
circular_buffer& operator=(const circular_buffer&) = delete;
circular_buffer& operator=(circular_buffer&& b) noexcept;
void push_front(const T& data);
void push_front(T&& data);
template <typename... A>
void emplace_front(A&&... args);
void push_back(const T& data);
void push_back(T&& data);
template <typename... A>
void emplace_back(A&&... args);
T& front();
T& back();
void pop_front();
void pop_back();
bool empty() const;
size_t size() const;
size_t capacity() const;
void reserve(size_t);
T& operator[](size_t idx);
const T& operator[](size_t idx) const;
template <typename Func>
void for_each(Func func);
// access an element, may return wrong or destroyed element
// only useful if you do not rely on data accuracy (e.g. prefetch)
T& access_element_unsafe(size_t idx);
private:
void expand();
void expand(size_t);
void maybe_expand(size_t nr = 1);
size_t mask(size_t idx) const;
template<typename CB, typename ValueType>
struct cbiterator : std::iterator<std::random_access_iterator_tag, ValueType> {
typedef std::iterator<std::random_access_iterator_tag, ValueType> super_t;
ValueType& operator*() const { return cb->_impl.storage[cb->mask(idx)]; }
ValueType* operator->() const { return &cb->_impl.storage[cb->mask(idx)]; }
// prefix
cbiterator<CB, ValueType>& operator++() {
idx++;
return *this;
}
// postfix
cbiterator<CB, ValueType> operator++(int unused) {
auto v = *this;
idx++;
return v;
}
// prefix
cbiterator<CB, ValueType>& operator--() {
idx--;
return *this;
}
// postfix
cbiterator<CB, ValueType> operator--(int unused) {
auto v = *this;
idx--;
return v;
}
cbiterator<CB, ValueType> operator+(typename super_t::difference_type n) const {
return cbiterator<CB, ValueType>(cb, idx + n);
}
cbiterator<CB, ValueType> operator-(typename super_t::difference_type n) const {
return cbiterator<CB, ValueType>(cb, idx - n);
}
cbiterator<CB, ValueType>& operator+=(typename super_t::difference_type n) {
idx += n;
return *this;
}
cbiterator<CB, ValueType>& operator-=(typename super_t::difference_type n) {
idx -= n;
return *this;
}
bool operator==(const cbiterator<CB, ValueType>& rhs) const {
return idx == rhs.idx;
}
bool operator!=(const cbiterator<CB, ValueType>& rhs) const {
return idx != rhs.idx;
}
bool operator<(const cbiterator<CB, ValueType>& rhs) const {
return idx < rhs.idx;
}
bool operator>(const cbiterator<CB, ValueType>& rhs) const {
return idx > rhs.idx;
}
bool operator>=(const cbiterator<CB, ValueType>& rhs) const {
return idx >= rhs.idx;
}
bool operator<=(const cbiterator<CB, ValueType>& rhs) const {
return idx <= rhs.idx;
}
typename super_t::difference_type operator-(const cbiterator<CB, ValueType>& rhs) const {
return idx - rhs.idx;
}
private:
CB* cb;
size_t idx;
cbiterator<CB, ValueType>(CB* b, size_t i) : cb(b), idx(i) {}
friend class circular_buffer;
};
friend class iterator;
public:
typedef cbiterator<circular_buffer, T> iterator;
typedef cbiterator<const circular_buffer, const T> const_iterator;
iterator begin() {
return iterator(this, _impl.begin);
}
const_iterator begin() const {
return const_iterator(this, _impl.begin);
}
iterator end() {
return iterator(this, _impl.end);
}
const_iterator end() const {
return const_iterator(this, _impl.end);
}
const_iterator cbegin() const {
return const_iterator(this, _impl.begin);
}
const_iterator cend() const {
return const_iterator(this, _impl.end);
}
iterator erase(iterator first, iterator last);
};
template <typename T, typename Alloc>
inline
size_t
circular_buffer<T, Alloc>::mask(size_t idx) const {
return idx & (_impl.capacity - 1);
}
template <typename T, typename Alloc>
inline
bool
circular_buffer<T, Alloc>::empty() const {
return _impl.begin == _impl.end;
}
template <typename T, typename Alloc>
inline
size_t
circular_buffer<T, Alloc>::size() const {
return _impl.end - _impl.begin;
}
template <typename T, typename Alloc>
inline
size_t
circular_buffer<T, Alloc>::capacity() const {
return _impl.capacity;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::reserve(size_t size) {
if (capacity() < size) {
// Make sure that the new capacity is a power of two.
expand(size_t(1) << log2ceil(size));
}
}
template <typename T, typename Alloc>
inline
circular_buffer<T, Alloc>::circular_buffer(circular_buffer&& x) noexcept
: _impl(std::move(x._impl)) {
x._impl = {};
}
template <typename T, typename Alloc>
inline
circular_buffer<T, Alloc>& circular_buffer<T, Alloc>::operator=(circular_buffer&& x) noexcept {
if (this != &x) {
this->~circular_buffer();
new (this) circular_buffer(std::move(x));
}
return *this;
}
template <typename T, typename Alloc>
template <typename Func>
inline
void
circular_buffer<T, Alloc>::for_each(Func func) {
auto s = _impl.storage;
auto m = _impl.capacity - 1;
for (auto i = _impl.begin; i != _impl.end; ++i) {
func(s[i & m]);
}
}
template <typename T, typename Alloc>
inline
circular_buffer<T, Alloc>::~circular_buffer() {
for_each([this] (T& obj) {
_impl.destroy(&obj);
});
_impl.deallocate(_impl.storage, _impl.capacity);
}
template <typename T, typename Alloc>
void
circular_buffer<T, Alloc>::expand() {
expand(std::max<size_t>(_impl.capacity * 2, 1));
}
template <typename T, typename Alloc>
void
circular_buffer<T, Alloc>::expand(size_t new_cap) {
auto new_storage = _impl.allocate(new_cap);
auto p = new_storage;
try {
for_each([this, &p] (T& obj) {
transfer_pass1(_impl, &obj, p);
p++;
});
} catch (...) {
while (p != new_storage) {
_impl.destroy(--p);
}
_impl.deallocate(new_storage, new_cap);
throw;
}
p = new_storage;
for_each([this, &p] (T& obj) {
transfer_pass2(_impl, &obj, p++);
});
std::swap(_impl.storage, new_storage);
std::swap(_impl.capacity, new_cap);
_impl.begin = 0;
_impl.end = p - _impl.storage;
_impl.deallocate(new_storage, new_cap);
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::maybe_expand(size_t nr) {
if (_impl.end - _impl.begin + nr > _impl.capacity) {
expand();
}
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_front(const T& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.begin - 1)];
_impl.construct(p, data);
--_impl.begin;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_front(T&& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.begin - 1)];
_impl.construct(p, std::move(data));
--_impl.begin;
}
template <typename T, typename Alloc>
template <typename... Args>
inline
void
circular_buffer<T, Alloc>::emplace_front(Args&&... args) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.begin - 1)];
_impl.construct(p, std::forward<Args>(args)...);
--_impl.begin;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_back(const T& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.end)];
_impl.construct(p, data);
++_impl.end;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::push_back(T&& data) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.end)];
_impl.construct(p, std::move(data));
++_impl.end;
}
template <typename T, typename Alloc>
template <typename... Args>
inline
void
circular_buffer<T, Alloc>::emplace_back(Args&&... args) {
maybe_expand();
auto p = &_impl.storage[mask(_impl.end)];
_impl.construct(p, std::forward<Args>(args)...);
++_impl.end;
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::front() {
return _impl.storage[mask(_impl.begin)];
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::back() {
return _impl.storage[mask(_impl.end - 1)];
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::pop_front() {
_impl.destroy(&front());
++_impl.begin;
}
template <typename T, typename Alloc>
inline
void
circular_buffer<T, Alloc>::pop_back() {
_impl.destroy(&back());
--_impl.end;
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::operator[](size_t idx) {
return _impl.storage[mask(_impl.begin + idx)];
}
template <typename T, typename Alloc>
inline
const T&
circular_buffer<T, Alloc>::operator[](size_t idx) const {
return _impl.storage[mask(_impl.begin + idx)];
}
template <typename T, typename Alloc>
inline
T&
circular_buffer<T, Alloc>::access_element_unsafe(size_t idx) {
return _impl.storage[mask(_impl.begin + idx)];
}
template <typename T, typename Alloc>
inline
typename circular_buffer<T, Alloc>::iterator
circular_buffer<T, Alloc>::erase(iterator first, iterator last) {
static_assert(std::is_nothrow_move_assignable<T>::value, "erase() assumes move assignment does not throw");
if (first == last) {
return last;
}
// Move to the left or right depending on which would result in least amount of moves.
// This also guarantees that iterators will be stable when removing from either front or back.
if (std::distance(begin(), first) < std::distance(last, end())) {
auto new_start = std::move_backward(begin(), first, last);
auto i = begin();
while (i < new_start) {
_impl.destroy(&*i++);
}
_impl.begin = new_start.idx;
return last;
} else {
auto new_end = std::move(last, end(), first);
auto i = new_end;
auto e = end();
while (i < e) {
_impl.destroy(&*i++);
}
_impl.end = new_end.idx;
return first;
}
}
}
#endif /* CIRCULAR_BUFFER_HH_ */
<|endoftext|> |
<commit_before>//===- ScriptParser.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the base parser class for linker script and dynamic
// list.
//
//===----------------------------------------------------------------------===//
#include "ScriptParser.h"
#include "Error.h"
using namespace llvm;
using namespace lld;
using namespace lld::elf;
// Returns the line that the character S[Pos] is in.
static StringRef getLine(StringRef S, size_t Pos) {
size_t Begin = S.rfind('\n', Pos);
size_t End = S.find('\n', Pos);
Begin = (Begin == StringRef::npos) ? 0 : Begin + 1;
if (End == StringRef::npos)
End = S.size();
// rtrim for DOS-style newlines.
return S.substr(Begin, End - Begin).rtrim();
}
void ScriptParserBase::printErrorPos() {
StringRef Tok = Tokens[Pos == 0 ? 0 : Pos - 1];
StringRef Line = getLine(Input, Tok.data() - Input.data());
size_t Col = Tok.data() - Line.data();
error(Line);
error(std::string(Col, ' ') + "^");
}
// We don't want to record cascading errors. Keep only the first one.
void ScriptParserBase::setError(const Twine &Msg) {
if (Error)
return;
error("line " + Twine(getPos()) + ": " + Msg);
printErrorPos();
Error = true;
}
// Split S into linker script tokens.
std::vector<StringRef> ScriptParserBase::tokenize(StringRef S) {
std::vector<StringRef> Ret;
for (;;) {
S = skipSpace(S);
if (S.empty())
return Ret;
// Quoted token
if (S.startswith("\"")) {
size_t E = S.find("\"", 1);
if (E == StringRef::npos) {
error("unclosed quote");
return {};
}
Ret.push_back(S.substr(1, E - 1));
S = S.substr(E + 1);
continue;
}
// Unquoted token
size_t Pos = S.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
"0123456789_.$/\\~=+[]*?-:");
// A character that cannot start a word (which is usually a
// punctuation) forms a single character token.
if (Pos == 0)
Pos = 1;
Ret.push_back(S.substr(0, Pos));
S = S.substr(Pos);
}
}
// Skip leading whitespace characters or /**/-style comments.
StringRef ScriptParserBase::skipSpace(StringRef S) {
for (;;) {
if (S.startswith("/*")) {
size_t E = S.find("*/", 2);
if (E == StringRef::npos) {
error("unclosed comment in a linker script");
return "";
}
S = S.substr(E + 2);
continue;
}
size_t Size = S.size();
S = S.ltrim();
if (S.size() == Size)
return S;
}
}
// An erroneous token is handled as if it were the last token before EOF.
bool ScriptParserBase::atEOF() { return Error || Tokens.size() == Pos; }
StringRef ScriptParserBase::next() {
if (Error)
return "";
if (atEOF()) {
setError("unexpected EOF");
return "";
}
return Tokens[Pos++];
}
StringRef ScriptParserBase::peek() {
StringRef Tok = next();
if (Error)
return "";
--Pos;
return Tok;
}
bool ScriptParserBase::skip(StringRef Tok) {
if (Error)
return false;
if (atEOF()) {
setError("unexpected EOF");
return false;
}
if (Tokens[Pos] != Tok)
return false;
++Pos;
return true;
}
void ScriptParserBase::expect(StringRef Expect) {
if (Error)
return;
StringRef Tok = next();
if (Tok != Expect)
setError(Expect + " expected, but got " + Tok);
}
// Returns the current line number.
size_t ScriptParserBase::getPos() {
if (Pos == 0)
return 1;
const char *Begin = Input.data();
const char *Tok = Tokens[Pos - 1].data();
return StringRef(Begin, Tok - Begin).count('\n') + 1;
}
std::vector<uint8_t> ScriptParserBase::parseHex(StringRef S) {
std::vector<uint8_t> Hex;
while (!S.empty()) {
StringRef B = S.substr(0, 2);
S = S.substr(2);
uint8_t H;
if (B.getAsInteger(16, H)) {
setError("not a hexadecimal value: " + B);
return {};
}
Hex.push_back(H);
}
return Hex;
}
<commit_msg>[ELF] Include Twine.h header to restore LLD build after r266524. NFC<commit_after>//===- ScriptParser.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the base parser class for linker script and dynamic
// list.
//
//===----------------------------------------------------------------------===//
#include "ScriptParser.h"
#include "Error.h"
#include "llvm/ADT/Twine.h"
using namespace llvm;
using namespace lld;
using namespace lld::elf;
// Returns the line that the character S[Pos] is in.
static StringRef getLine(StringRef S, size_t Pos) {
size_t Begin = S.rfind('\n', Pos);
size_t End = S.find('\n', Pos);
Begin = (Begin == StringRef::npos) ? 0 : Begin + 1;
if (End == StringRef::npos)
End = S.size();
// rtrim for DOS-style newlines.
return S.substr(Begin, End - Begin).rtrim();
}
void ScriptParserBase::printErrorPos() {
StringRef Tok = Tokens[Pos == 0 ? 0 : Pos - 1];
StringRef Line = getLine(Input, Tok.data() - Input.data());
size_t Col = Tok.data() - Line.data();
error(Line);
error(std::string(Col, ' ') + "^");
}
// We don't want to record cascading errors. Keep only the first one.
void ScriptParserBase::setError(const Twine &Msg) {
if (Error)
return;
error("line " + Twine(getPos()) + ": " + Msg);
printErrorPos();
Error = true;
}
// Split S into linker script tokens.
std::vector<StringRef> ScriptParserBase::tokenize(StringRef S) {
std::vector<StringRef> Ret;
for (;;) {
S = skipSpace(S);
if (S.empty())
return Ret;
// Quoted token
if (S.startswith("\"")) {
size_t E = S.find("\"", 1);
if (E == StringRef::npos) {
error("unclosed quote");
return {};
}
Ret.push_back(S.substr(1, E - 1));
S = S.substr(E + 1);
continue;
}
// Unquoted token
size_t Pos = S.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
"0123456789_.$/\\~=+[]*?-:");
// A character that cannot start a word (which is usually a
// punctuation) forms a single character token.
if (Pos == 0)
Pos = 1;
Ret.push_back(S.substr(0, Pos));
S = S.substr(Pos);
}
}
// Skip leading whitespace characters or /**/-style comments.
StringRef ScriptParserBase::skipSpace(StringRef S) {
for (;;) {
if (S.startswith("/*")) {
size_t E = S.find("*/", 2);
if (E == StringRef::npos) {
error("unclosed comment in a linker script");
return "";
}
S = S.substr(E + 2);
continue;
}
size_t Size = S.size();
S = S.ltrim();
if (S.size() == Size)
return S;
}
}
// An erroneous token is handled as if it were the last token before EOF.
bool ScriptParserBase::atEOF() { return Error || Tokens.size() == Pos; }
StringRef ScriptParserBase::next() {
if (Error)
return "";
if (atEOF()) {
setError("unexpected EOF");
return "";
}
return Tokens[Pos++];
}
StringRef ScriptParserBase::peek() {
StringRef Tok = next();
if (Error)
return "";
--Pos;
return Tok;
}
bool ScriptParserBase::skip(StringRef Tok) {
if (Error)
return false;
if (atEOF()) {
setError("unexpected EOF");
return false;
}
if (Tokens[Pos] != Tok)
return false;
++Pos;
return true;
}
void ScriptParserBase::expect(StringRef Expect) {
if (Error)
return;
StringRef Tok = next();
if (Tok != Expect)
setError(Expect + " expected, but got " + Tok);
}
// Returns the current line number.
size_t ScriptParserBase::getPos() {
if (Pos == 0)
return 1;
const char *Begin = Input.data();
const char *Tok = Tokens[Pos - 1].data();
return StringRef(Begin, Tok - Begin).count('\n') + 1;
}
std::vector<uint8_t> ScriptParserBase::parseHex(StringRef S) {
std::vector<uint8_t> Hex;
while (!S.empty()) {
StringRef B = S.substr(0, 2);
S = S.substr(2);
uint8_t H;
if (B.getAsInteger(16, H)) {
setError("not a hexadecimal value: " + B);
return {};
}
Hex.push_back(H);
}
return Hex;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "file/nifti_utils.h"
#include "formats/list.h"
namespace MR
{
namespace Formats
{
std::unique_ptr<ImageIO::Base> NIfTI2::read (Header& H) const
{
return File::NIfTI::read<2> (H);
}
bool NIfTI2::check (Header& H, size_t num_axes) const
{
const vector<std::string> suffixes { ".nii" };
return File::NIfTI::check (H, num_axes, false, suffixes, 2, "NIfTI-2");
}
std::unique_ptr<ImageIO::Base> NIfTI2::create (Header& H) const
{
return File::NIfTI::create<2> (H);
}
}
}
<commit_msg>NIfTI-2: reinstate .img in list of suffixes<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "file/nifti_utils.h"
#include "formats/list.h"
namespace MR
{
namespace Formats
{
std::unique_ptr<ImageIO::Base> NIfTI2::read (Header& H) const
{
return File::NIfTI::read<2> (H);
}
bool NIfTI2::check (Header& H, size_t num_axes) const
{
const vector<std::string> suffixes { ".nii", ".img" };
return File::NIfTI::check (H, num_axes, false, suffixes, 2, "NIfTI-2");
}
std::unique_ptr<ImageIO::Base> NIfTI2::create (Header& H) const
{
return File::NIfTI::create<2> (H);
}
}
}
<|endoftext|> |
<commit_before>#include "core/hashgen_sprator.h"
#include <vector>
#include "core/image.h"
#include "core/rgb.h"
#include "core/assert.h"
#include "core/rng.h"
#include "core/numeric.h"
#include "core/image_draw.h"
#include "core/cint.h"
#include "core/table_bool.h"
#include "core/generator_cell.h"
namespace
{
using namespace euphoria::core;
Rgbai
CalculateBorderColor(Rgbai base)
{
auto h = hsl(rgb(base));
h.h -= Angle::FromDegrees(15);
h.l *= 0.4;
return {rgbi(rgb(h)), base.a};
}
void
ApplySpratorAlgorithm(BoolTable* half_side, int number_of_steps)
{
generator::Rules rules;
generator::AddComplexRules
(
&rules,
number_of_steps,
[](bool current, const Wallcounter& wc) -> std::optional<bool>
{
const auto c = wc.Count
(
1,
false,
NeighborhoodAlgorithm::Plus
);
if(current)
{
if(c == 2 || c == 3 ) { return true; }
else { return false; }
}
else
{
if(c <= 1) { return true; }
else { return false; }
}
}
);
auto cell = generator::CellularAutomata
(
&rules,
half_side,
Fourway<OutsideRule>{OutsideRule::Empty}
);
while(cell.HasMoreWork()) { cell.Work(); }
}
BoolTable
Mirror(const BoolTable& half_side)
{
const auto height = half_side.GetHeight();
const auto half_width = half_side.GetWidth();
const auto width = half_width * 2;
// offset everything by 1 to get a nice border
constexpr auto offset = 1;
constexpr auto extra_size = 2;
auto result_table = BoolTable::FromWidthHeight
(
width + extra_size,
height + extra_size,
false
);
for(int y=0; y<height; y+=1)
for(int x=0; x<half_width; x+=1)
{
const auto src = half_side(x, y);
const auto x_mirror = width - (x + 1);
result_table(x + offset, y + offset) = src;
result_table(x_mirror + offset, y + offset) = src;
}
return result_table;
}
int
CalculateScale(const Image& image, const BoolTable& table)
{
auto calculate_scale = [](int image_scale, int table_scale) -> int
{
const auto image_scale_float = static_cast<float>(image_scale);
const auto table_scale_float = static_cast<float>(table_scale);
const auto scale_factor = image_scale_float / table_scale_float;
return std::max(1, Floori(scale_factor));
};
const auto scale = std::min
(
calculate_scale(image.GetWidth(), table.GetWidth()),
calculate_scale(image.GetHeight(), table.GetHeight())
);
return scale;
}
void
DrawImageWithBorder
(
Image* image,
const BoolTable& result_table,
const Rgbai& background_color,
const Rgbai& foreground_color,
const Rgbai& border_color
)
{
Clear(image, background_color);
auto img = Draw
(
result_table,
foreground_color,
background_color,
CalculateScale(*image, result_table),
BorderSettings{border_color}
);
PasteImage(image, vec2i{0, 0}, img);
}
template
<
typename TGenerator
>
void
RandomizeWorld(BoolTable* half_side, TGenerator* generator)
{
SetWhiteNoise
(
half_side,
Fourway<BorderSetupRule>{BorderSetupRule::Random},
[&]() -> bool { return generator->Next() < 0.5f; }
);
}
template
<
typename TGenerator,
typename I
>
void
RenderSpratorImpl
(
Image* image,
I code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
constexpr int half_width = 4;
constexpr int height = 8;
const int number_of_steps = 3;
// todo(Gustav): figure out color (randomly?)
const Rgbai border_color = border_color_arg.value_or
(
CalculateBorderColor(foreground_color)
);
auto half_side = BoolTable::FromWidthHeight(half_width, height);
auto generator = TGenerator{code};
// randomize world
RandomizeWorld<TGenerator>(&half_side, &generator);
// apply sprator algorithm
ApplySpratorAlgorithm(&half_side, number_of_steps);
// flip and copy from small table to big table
const auto result_table = Mirror(half_side);
// draw image with border
DrawImageWithBorder(image, result_table, background_color, foreground_color, border_color);
}
template
<
typename TGenerator,
typename I
>
void
RenderSpratorImpl
(
std::vector<Image>* images,
I code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
constexpr int half_width = 4;
constexpr int height = 8;
const int number_of_steps = 3;
// todo(Gustav): figure out color (randomly?)
const Rgbai border_color = border_color_arg.value_or
(
CalculateBorderColor(foreground_color)
);
auto half_side = BoolTable::FromWidthHeight(half_width, height);
auto generator = TGenerator{code};
// randomize world
RandomizeWorld<TGenerator>(&half_side, &generator);
// apply sprator algorithm
ApplySpratorAlgorithm(&half_side, number_of_steps);
bool first = true;
auto orig_half_side = half_side;
for(auto& image: *images)
{
if(first) { first = false; }
else
{
half_side = orig_half_side;
// animate...
auto hit = BoolTable::FromWidthHeight(half_side.GetWidth(), half_side.GetHeight(), false);
for(int i=0; i<2; i+=1)
{
int x = 0;
int y = 0;
do
{
x = Floori(generator.Next() * half_side.GetWidth());
y = Floori(generator.Next() * half_side.GetHeight());
} while(hit(x, y));
hit(x, y) = true;
half_side(x, y) = !half_side(x, y);
}
}
// flip and copy from small table to big table
const auto result_table = Mirror(half_side);
// draw image with border
DrawImageWithBorder(&image, result_table, background_color, foreground_color, border_color);
}
}
}
namespace euphoria::core
{
void
RenderSprator
(
Image* image,
int code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
RenderSpratorImpl<xorshift32>
(
image,
Cbit_signed_to_unsigned(code),
foreground_color,
border_color_arg,
background_color
);
}
void
RenderSprator
(
std::vector<Image>* images,
int code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
RenderSpratorImpl<xorshift32>
(
images,
Cbit_signed_to_unsigned(code),
foreground_color,
border_color_arg,
background_color
);
}
}
<commit_msg>sprator step after animation<commit_after>#include "core/hashgen_sprator.h"
#include <vector>
#include "core/image.h"
#include "core/rgb.h"
#include "core/assert.h"
#include "core/rng.h"
#include "core/numeric.h"
#include "core/image_draw.h"
#include "core/cint.h"
#include "core/table_bool.h"
#include "core/generator_cell.h"
namespace
{
using namespace euphoria::core;
Rgbai
CalculateBorderColor(Rgbai base)
{
auto h = hsl(rgb(base));
h.h -= Angle::FromDegrees(15);
h.l *= 0.4;
return {rgbi(rgb(h)), base.a};
}
void
ApplySpratorAlgorithm(BoolTable* half_side, int number_of_steps)
{
generator::Rules rules;
generator::AddComplexRules
(
&rules,
number_of_steps,
[](bool current, const Wallcounter& wc) -> std::optional<bool>
{
const auto c = wc.Count
(
1,
false,
NeighborhoodAlgorithm::Plus
);
if(current)
{
if(c == 2 || c == 3 ) { return true; }
else { return false; }
}
else
{
if(c <= 1) { return true; }
else { return false; }
}
}
);
auto cell = generator::CellularAutomata
(
&rules,
half_side,
Fourway<OutsideRule>{OutsideRule::Empty}
);
while(cell.HasMoreWork()) { cell.Work(); }
}
BoolTable
Mirror(const BoolTable& half_side)
{
const auto height = half_side.GetHeight();
const auto half_width = half_side.GetWidth();
const auto width = half_width * 2;
// offset everything by 1 to get a nice border
constexpr auto offset = 1;
constexpr auto extra_size = 2;
auto result_table = BoolTable::FromWidthHeight
(
width + extra_size,
height + extra_size,
false
);
for(int y=0; y<height; y+=1)
for(int x=0; x<half_width; x+=1)
{
const auto src = half_side(x, y);
const auto x_mirror = width - (x + 1);
result_table(x + offset, y + offset) = src;
result_table(x_mirror + offset, y + offset) = src;
}
return result_table;
}
int
CalculateScale(const Image& image, const BoolTable& table)
{
auto calculate_scale = [](int image_scale, int table_scale) -> int
{
const auto image_scale_float = static_cast<float>(image_scale);
const auto table_scale_float = static_cast<float>(table_scale);
const auto scale_factor = image_scale_float / table_scale_float;
return std::max(1, Floori(scale_factor));
};
const auto scale = std::min
(
calculate_scale(image.GetWidth(), table.GetWidth()),
calculate_scale(image.GetHeight(), table.GetHeight())
);
return scale;
}
void
DrawImageWithBorder
(
Image* image,
const BoolTable& result_table,
const Rgbai& background_color,
const Rgbai& foreground_color,
const Rgbai& border_color
)
{
Clear(image, background_color);
auto img = Draw
(
result_table,
foreground_color,
background_color,
CalculateScale(*image, result_table),
BorderSettings{border_color}
);
PasteImage(image, vec2i{0, 0}, img);
}
template
<
typename TGenerator
>
void
RandomizeWorld(BoolTable* half_side, TGenerator* generator)
{
SetWhiteNoise
(
half_side,
Fourway<BorderSetupRule>{BorderSetupRule::Random},
[&]() -> bool { return generator->Next() < 0.5f; }
);
}
template
<
typename TGenerator,
typename I
>
void
RenderSpratorImpl
(
Image* image,
I code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
constexpr int half_width = 4;
constexpr int height = 8;
const int number_of_steps = 3;
// todo(Gustav): figure out color (randomly?)
const Rgbai border_color = border_color_arg.value_or
(
CalculateBorderColor(foreground_color)
);
auto half_side = BoolTable::FromWidthHeight(half_width, height);
auto generator = TGenerator{code};
// randomize world
RandomizeWorld<TGenerator>(&half_side, &generator);
// apply sprator algorithm
ApplySpratorAlgorithm(&half_side, number_of_steps);
// flip and copy from small table to big table
const auto result_table = Mirror(half_side);
// draw image with border
DrawImageWithBorder(image, result_table, background_color, foreground_color, border_color);
}
template
<
typename TGenerator,
typename I
>
void
RenderSpratorImpl
(
std::vector<Image>* images,
I code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
constexpr int half_width = 4;
constexpr int height = 8;
const int number_of_steps = 3;
// todo(Gustav): figure out color (randomly?)
const Rgbai border_color = border_color_arg.value_or
(
CalculateBorderColor(foreground_color)
);
auto half_side = BoolTable::FromWidthHeight(half_width, height);
auto generator = TGenerator{code};
// randomize world
RandomizeWorld<TGenerator>(&half_side, &generator);
// apply sprator algorithm
ApplySpratorAlgorithm(&half_side, number_of_steps - 1);
bool first = true;
auto orig_half_side = half_side;
for(auto& image: *images)
{
if(first) { first = false; }
else
{
half_side = orig_half_side;
// animate...
auto hit = BoolTable::FromWidthHeight(half_side.GetWidth(), half_side.GetHeight(), false);
for(int i=0; i<2; i+=1)
{
int x = 0;
int y = 0;
do
{
x = Floori(generator.Next() * half_side.GetWidth());
y = Floori(generator.Next() * half_side.GetHeight());
} while(hit(x, y));
hit(x, y) = true;
half_side(x, y) = !half_side(x, y);
}
}
ApplySpratorAlgorithm(&half_side, 1);
// flip and copy from small table to big table
const auto result_table = Mirror(half_side);
// draw image with border
DrawImageWithBorder(&image, result_table, background_color, foreground_color, border_color);
}
}
}
namespace euphoria::core
{
void
RenderSprator
(
Image* image,
int code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
RenderSpratorImpl<xorshift32>
(
image,
Cbit_signed_to_unsigned(code),
foreground_color,
border_color_arg,
background_color
);
}
void
RenderSprator
(
std::vector<Image>* images,
int code,
const Rgbai& foreground_color,
const std::optional<Rgbai> border_color_arg,
const Rgbai& background_color
)
{
RenderSpratorImpl<xorshift32>
(
images,
Cbit_signed_to_unsigned(code),
foreground_color,
border_color_arg,
background_color
);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkTool.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkOrganTypeProperty.h"
#include "mitkProperties.h"
#include "mitkLevelWindowProperty.h"
#include "mitkVtkResliceInterpolationProperty.h"
#include <itkObjectFactory.h>
mitk::Tool::Tool(const char* type)
: StateMachine(type),
// for working image
m_IsSegmentationPredicate(NodePredicateProperty::New("segmentation", BoolProperty::New(true))),
// for reference images
m_PredicateImages(NodePredicateDataType::New("Image")),
m_PredicateDim3(NodePredicateDimension::New(3, 1)),
m_PredicateDim4(NodePredicateDimension::New(4, 1)),
m_PredicateDimension( mitk::NodePredicateOR::New(m_PredicateDim3, m_PredicateDim4) ),
m_PredicateImage3D( NodePredicateAND::New(m_PredicateImages, m_PredicateDimension) ),
m_PredicateBinary(NodePredicateProperty::New("binary", BoolProperty::New(true))),
m_PredicateNotBinary( NodePredicateNOT::New(m_PredicateBinary) ),
m_PredicateSegmentation(NodePredicateProperty::New("segmentation", BoolProperty::New(true))),
m_PredicateNotSegmentation( NodePredicateNOT::New(m_PredicateSegmentation) ),
m_PredicateHelper(NodePredicateProperty::New("helper object", BoolProperty::New(true))),
m_PredicateNotHelper( NodePredicateNOT::New(m_PredicateHelper) ),
m_PredicateImageColorful( NodePredicateAND::New(m_PredicateNotBinary, m_PredicateNotSegmentation) ),
m_PredicateImageColorfulNotHelper( NodePredicateAND::New(m_PredicateImageColorful, m_PredicateNotHelper) ),
m_PredicateReference( NodePredicateAND::New(m_PredicateImage3D, m_PredicateImageColorfulNotHelper) )
{
}
mitk::Tool::~Tool()
{
}
const char* mitk::Tool::GetGroup() const
{
return "default";
}
void mitk::Tool::SetToolManager(ToolManager* manager)
{
m_ToolManager = manager;
}
void mitk::Tool::Activated()
{
}
void mitk::Tool::Deactivated()
{
StateMachine::ResetStatemachineToStartState(); // forget about the past
}
itk::Object::Pointer mitk::Tool::GetGUI(const std::string& toolkitPrefix, const std::string& toolkitPostfix)
{
itk::Object::Pointer object;
std::string classname = this->GetNameOfClass();
std::string guiClassname = toolkitPrefix + classname + toolkitPostfix;
std::list<itk::LightObject::Pointer> allGUIs = itk::ObjectFactoryBase::CreateAllInstance(guiClassname.c_str());
for( std::list<itk::LightObject::Pointer>::iterator iter = allGUIs.begin();
iter != allGUIs.end();
++iter )
{
if (object.IsNull())
{
object = dynamic_cast<itk::Object*>( iter->GetPointer() );
}
else
{
LOG_ERROR << "There is more than one GUI for " << classname << " (several factories claim ability to produce a " << guiClassname << " ) " << std::endl;
return NULL; // people should see and fix this error
}
}
return object;
}
mitk::NodePredicateBase::ConstPointer mitk::Tool::GetReferenceDataPreference() const
{
return m_PredicateReference.GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::Tool::GetWorkingDataPreference() const
{
return m_IsSegmentationPredicate.GetPointer();
}
mitk::DataTreeNode::Pointer mitk::Tool::CreateEmptySegmentationNode( Image* original, const std::string& organType, const std::string& organName )
{
// we NEED a reference image for size etc.
if (!original) return NULL;
// actually create a new empty segmentation
PixelType pixelType( typeid(DefaultSegmentationDataType) );
Image::Pointer segmentation = Image::New();
segmentation->SetProperty( "organ type", OrganTypeProperty::New( organType ) );
segmentation->Initialize( pixelType, original->GetDimension(), original->GetDimensions() );
unsigned int byteSize = sizeof(DefaultSegmentationDataType);
for (unsigned int dim = 0; dim < segmentation->GetDimension(); ++dim)
{
byteSize *= segmentation->GetDimension(dim);
}
memset( segmentation->GetData(), 0, byteSize );
if (original->GetTimeSlicedGeometry() )
{
AffineGeometryFrame3D::Pointer originalGeometryAGF = original->GetTimeSlicedGeometry()->Clone();
TimeSlicedGeometry::Pointer originalGeometry = dynamic_cast<TimeSlicedGeometry*>( originalGeometryAGF.GetPointer() );
segmentation->SetGeometry( originalGeometry );
}
else
{
Tool::ErrorMessage("Original image does not have a 'Time sliced geometry'! Cannot create a segmentation.");
return NULL;
}
return CreateSegmentationNode( segmentation, organType, organName );
}
mitk::DataTreeNode::Pointer mitk::Tool::CreateSegmentationNode( Image* image, const std::string& organType, const std::string& organName )
{
if (!image) return NULL;
// decorate the datatreenode with some properties
DataTreeNode::Pointer segmentationNode = DataTreeNode::New();
segmentationNode->SetData( image );
// name
segmentationNode->SetProperty( "name", StringProperty::New( organName ) );
// organ type
OrganTypeProperty::Pointer organTypeProperty = OrganTypeProperty::New( organType );
if ( !organTypeProperty->IsValidEnumerationValue( organType ) )
{
organTypeProperty->AddEnum( organType, organTypeProperty->Size() ); // add a new organ type
organTypeProperty->SetValue( organType );
}
// visualization properties
segmentationNode->SetProperty( "binary", BoolProperty::New(true) );
segmentationNode->SetProperty( "color", DataTreeNodeFactory::DefaultColorForOrgan( organType ) );
segmentationNode->SetProperty( "texture interpolation", BoolProperty::New(false) );
segmentationNode->SetProperty( "layer", IntProperty::New(10) );
segmentationNode->SetProperty( "levelwindow", LevelWindowProperty::New( LevelWindow(0.5, 1) ) );
segmentationNode->SetProperty( "opacity", FloatProperty::New(0.3) );
segmentationNode->SetProperty( "segmentation", BoolProperty::New(true) );
segmentationNode->SetProperty( "reslice interpolation", VtkResliceInterpolationProperty::New() ); // otherwise -> segmentation appears in 2 slices sometimes (only visual effect, not different data)
return segmentationNode;
}
<commit_msg>CHG (#273): Readded property "showVolume" on segmentation images to let the ImageMapper2D show the volume annotation.<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkTool.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkOrganTypeProperty.h"
#include "mitkProperties.h"
#include "mitkLevelWindowProperty.h"
#include "mitkVtkResliceInterpolationProperty.h"
#include <itkObjectFactory.h>
mitk::Tool::Tool(const char* type)
: StateMachine(type),
// for working image
m_IsSegmentationPredicate(NodePredicateProperty::New("segmentation", BoolProperty::New(true))),
// for reference images
m_PredicateImages(NodePredicateDataType::New("Image")),
m_PredicateDim3(NodePredicateDimension::New(3, 1)),
m_PredicateDim4(NodePredicateDimension::New(4, 1)),
m_PredicateDimension( mitk::NodePredicateOR::New(m_PredicateDim3, m_PredicateDim4) ),
m_PredicateImage3D( NodePredicateAND::New(m_PredicateImages, m_PredicateDimension) ),
m_PredicateBinary(NodePredicateProperty::New("binary", BoolProperty::New(true))),
m_PredicateNotBinary( NodePredicateNOT::New(m_PredicateBinary) ),
m_PredicateSegmentation(NodePredicateProperty::New("segmentation", BoolProperty::New(true))),
m_PredicateNotSegmentation( NodePredicateNOT::New(m_PredicateSegmentation) ),
m_PredicateHelper(NodePredicateProperty::New("helper object", BoolProperty::New(true))),
m_PredicateNotHelper( NodePredicateNOT::New(m_PredicateHelper) ),
m_PredicateImageColorful( NodePredicateAND::New(m_PredicateNotBinary, m_PredicateNotSegmentation) ),
m_PredicateImageColorfulNotHelper( NodePredicateAND::New(m_PredicateImageColorful, m_PredicateNotHelper) ),
m_PredicateReference( NodePredicateAND::New(m_PredicateImage3D, m_PredicateImageColorfulNotHelper) )
{
}
mitk::Tool::~Tool()
{
}
const char* mitk::Tool::GetGroup() const
{
return "default";
}
void mitk::Tool::SetToolManager(ToolManager* manager)
{
m_ToolManager = manager;
}
void mitk::Tool::Activated()
{
}
void mitk::Tool::Deactivated()
{
StateMachine::ResetStatemachineToStartState(); // forget about the past
}
itk::Object::Pointer mitk::Tool::GetGUI(const std::string& toolkitPrefix, const std::string& toolkitPostfix)
{
itk::Object::Pointer object;
std::string classname = this->GetNameOfClass();
std::string guiClassname = toolkitPrefix + classname + toolkitPostfix;
std::list<itk::LightObject::Pointer> allGUIs = itk::ObjectFactoryBase::CreateAllInstance(guiClassname.c_str());
for( std::list<itk::LightObject::Pointer>::iterator iter = allGUIs.begin();
iter != allGUIs.end();
++iter )
{
if (object.IsNull())
{
object = dynamic_cast<itk::Object*>( iter->GetPointer() );
}
else
{
LOG_ERROR << "There is more than one GUI for " << classname << " (several factories claim ability to produce a " << guiClassname << " ) " << std::endl;
return NULL; // people should see and fix this error
}
}
return object;
}
mitk::NodePredicateBase::ConstPointer mitk::Tool::GetReferenceDataPreference() const
{
return m_PredicateReference.GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::Tool::GetWorkingDataPreference() const
{
return m_IsSegmentationPredicate.GetPointer();
}
mitk::DataTreeNode::Pointer mitk::Tool::CreateEmptySegmentationNode( Image* original, const std::string& organType, const std::string& organName )
{
// we NEED a reference image for size etc.
if (!original) return NULL;
// actually create a new empty segmentation
PixelType pixelType( typeid(DefaultSegmentationDataType) );
Image::Pointer segmentation = Image::New();
segmentation->SetProperty( "organ type", OrganTypeProperty::New( organType ) );
segmentation->Initialize( pixelType, original->GetDimension(), original->GetDimensions() );
unsigned int byteSize = sizeof(DefaultSegmentationDataType);
for (unsigned int dim = 0; dim < segmentation->GetDimension(); ++dim)
{
byteSize *= segmentation->GetDimension(dim);
}
memset( segmentation->GetData(), 0, byteSize );
if (original->GetTimeSlicedGeometry() )
{
AffineGeometryFrame3D::Pointer originalGeometryAGF = original->GetTimeSlicedGeometry()->Clone();
TimeSlicedGeometry::Pointer originalGeometry = dynamic_cast<TimeSlicedGeometry*>( originalGeometryAGF.GetPointer() );
segmentation->SetGeometry( originalGeometry );
}
else
{
Tool::ErrorMessage("Original image does not have a 'Time sliced geometry'! Cannot create a segmentation.");
return NULL;
}
return CreateSegmentationNode( segmentation, organType, organName );
}
mitk::DataTreeNode::Pointer mitk::Tool::CreateSegmentationNode( Image* image, const std::string& organType, const std::string& organName )
{
if (!image) return NULL;
// decorate the datatreenode with some properties
DataTreeNode::Pointer segmentationNode = DataTreeNode::New();
segmentationNode->SetData( image );
// name
segmentationNode->SetProperty( "name", StringProperty::New( organName ) );
// organ type
OrganTypeProperty::Pointer organTypeProperty = OrganTypeProperty::New( organType );
if ( !organTypeProperty->IsValidEnumerationValue( organType ) )
{
organTypeProperty->AddEnum( organType, organTypeProperty->Size() ); // add a new organ type
organTypeProperty->SetValue( organType );
}
// visualization properties
segmentationNode->SetProperty( "binary", BoolProperty::New(true) );
segmentationNode->SetProperty( "color", DataTreeNodeFactory::DefaultColorForOrgan( organType ) );
segmentationNode->SetProperty( "texture interpolation", BoolProperty::New(false) );
segmentationNode->SetProperty( "layer", IntProperty::New(10) );
segmentationNode->SetProperty( "levelwindow", LevelWindowProperty::New( LevelWindow(0.5, 1) ) );
segmentationNode->SetProperty( "opacity", FloatProperty::New(0.3) );
segmentationNode->SetProperty( "segmentation", BoolProperty::New(true) );
segmentationNode->SetProperty( "reslice interpolation", VtkResliceInterpolationProperty::New() ); // otherwise -> segmentation appears in 2 slices sometimes (only visual effect, not different data)
segmentationNode->SetProperty( "showVolume", BoolProperty::New( false ) );
return segmentationNode;
}
<|endoftext|> |
<commit_before>// stdafx.cpp : source file that includes just the standard includes
// thrededMatrixMult.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
<commit_msg>removed vs dependecy<commit_after><|endoftext|> |
<commit_before>Bool_t ProcessOutputCheb(TString filesToProcess, Int_t startRun, Int_t endRun, const char* ocdbStorage, Bool_t corr=kTRUE) {
// macro that process a list of files (xml or txt) to produce then the
// OCDB entry for the TPC SP Distortion calibration; inspired by
// AliAnalysisAlien::MergeOutput for simplicity
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/TPC/CalibMacros/CreateCorrMapObj.C");
//gROOT->LoadMacro("CreateCorrMapObj.C");
Bool_t isGrid = kTRUE;
TObjArray *listoffiles = new TObjArray();
if (filesToProcess.Contains(".xml")) {
// Merge files pointed by the xml
TGridCollection *coll = (TGridCollection*)gROOT->ProcessLine(Form("TAlienCollection::Open(\"%s\");", filesToProcess.Data()));
if (!coll) {
::Error("ProcessOutput", "Input XML collection empty.");
return kFALSE;
}
coll->Print();
// Iterate grid collection
while (coll->Next()) {
TString fname = coll->GetTURL();
Printf("fname = %s", fname.Data());
listoffiles->Add(new TNamed(fname.Data(),""));
}
}
else if (filesToProcess.Contains(".txt")) {
TString line;
ifstream in;
in.open(filesToProcess);
if (in.fail()) {
::Error("ProcessOutput", "File %s cannot be opened. Processing stopped." ,filesToProcess.Data());
return kTRUE;
}
Int_t nfiles = 0;
while (in.good()) {
in >> line;
if (line.IsNull()) continue;
if (!line.Contains("alien:")) isGrid = kFALSE;
nfiles++;
listoffiles->Add(new TNamed(line.Data(),""));
}
in.close();
if (!nfiles) {
::Error("ProcessOutput","Input file %s contains no files to be processed\n", filesToProcess.Data());
delete listoffiles;
return kFALSE;
}
}
if (!listoffiles->GetEntries()) {
::Error("ProcessOutput","No files to process\n");
delete listoffiles;
return kFALSE;
}
if (startRun != endRun) {
Printf("The processing now is only run-level, please check again!");
return kFALSE;
}
Int_t run = startRun;
TObject *nextfile;
TString snextfile;
TIter next(listoffiles);
TObjArray* a = new TObjArray();
a->SetOwner(kTRUE);
Int_t lowStatJobs = 0;
Int_t nJobs = 0;
while (nextfile=next()) {
snextfile = nextfile->GetName();
Printf("opening file %s", snextfile.Data());
if (isGrid) TGrid::Connect("alien://");
AliTPCDcalibRes* dcalibRes = AliTPCDcalibRes::Load(snextfile.Data());
if (!dcalibRes) {
::Error("ProcessOutput","Did not find calib object in %s, job Killed",snextfile.Data());
exit(1);
}
int ntrUse = dcalibRes->GetNTracksUsed();
int ntrMin = dcalibRes->GetMinTrackToUse();
if (ntrUse<ntrMin) {
::Error("ProcessOutput","Low stat:%d tracks used (min: %d) in %s",ntrUse,ntrMin,snextfile.Data());
lowStatJobs++;
}
else {
::Info("ProcessOutput","stat is OK :%d tracks used (min: %d) in %s",ntrUse,ntrMin,snextfile.Data());
}
AliTPCChebCorr* c = corr ? dcalibRes->GetChebCorrObject() : dcalibRes->GetChebDistObject();
if (!c) {
::Error("ProcessOutput","Did not find %s Cheb.parm in %s",corr ? "Correction":"Distortion" ,snextfile.Data());
exit(1);
}
a->Add(c);
nJobs++;
}
if (lowStatJobs) {
::Error("ProcessOutput","%d out of %d timebins have low stat, will not update OCDB",lowStatJobs,nJobs);
}
else {
a->Print();
CreateCorrMapObjTime(a, startRun, endRun, ocdbStorage);
}
delete a;
delete listoffiles;
return kTRUE;
}
<commit_msg>Min tracks to allow ocdb object creation can be overridden by env.var.<commit_after>Bool_t ProcessOutputCheb(TString filesToProcess, Int_t startRun, Int_t endRun, const char* ocdbStorage, Bool_t corr=kTRUE) {
// macro that process a list of files (xml or txt) to produce then the
// OCDB entry for the TPC SP Distortion calibration; inspired by
// AliAnalysisAlien::MergeOutput for simplicity
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/TPC/CalibMacros/CreateCorrMapObj.C");
//gROOT->LoadMacro("CreateCorrMapObj.C");
Bool_t isGrid = kTRUE;
TObjArray *listoffiles = new TObjArray();
int ntrminUser = -1;
TString ntrminUserS = gSystem->Getenv("distMinTracks");
if (!ntrminUserS.IsNull() && (ntrminUser=ntrminUserS.Atoi())>0) {
::Info("ProcessOutput","User provided min tracks to validate object: %d",ntrminUser);
}
if (filesToProcess.Contains(".xml")) {
// Merge files pointed by the xml
TGridCollection *coll = (TGridCollection*)gROOT->ProcessLine(Form("TAlienCollection::Open(\"%s\");", filesToProcess.Data()));
if (!coll) {
::Error("ProcessOutput", "Input XML collection empty.");
return kFALSE;
}
coll->Print();
// Iterate grid collection
while (coll->Next()) {
TString fname = coll->GetTURL();
Printf("fname = %s", fname.Data());
listoffiles->Add(new TNamed(fname.Data(),""));
}
}
else if (filesToProcess.Contains(".txt")) {
TString line;
ifstream in;
in.open(filesToProcess);
if (in.fail()) {
::Error("ProcessOutput", "File %s cannot be opened. Processing stopped." ,filesToProcess.Data());
return kTRUE;
}
Int_t nfiles = 0;
while (in.good()) {
in >> line;
if (line.IsNull()) continue;
if (!line.Contains("alien:")) isGrid = kFALSE;
nfiles++;
listoffiles->Add(new TNamed(line.Data(),""));
}
in.close();
if (!nfiles) {
::Error("ProcessOutput","Input file %s contains no files to be processed\n", filesToProcess.Data());
delete listoffiles;
return kFALSE;
}
}
if (!listoffiles->GetEntries()) {
::Error("ProcessOutput","No files to process\n");
delete listoffiles;
return kFALSE;
}
if (startRun != endRun) {
Printf("The processing now is only run-level, please check again!");
return kFALSE;
}
Int_t run = startRun;
TObject *nextfile;
TString snextfile;
TIter next(listoffiles);
TObjArray* a = new TObjArray();
a->SetOwner(kTRUE);
Int_t lowStatJobs = 0;
Int_t nJobs = 0;
while (nextfile=next()) {
snextfile = nextfile->GetName();
Printf("opening file %s", snextfile.Data());
if (isGrid) TGrid::Connect("alien://");
AliTPCDcalibRes* dcalibRes = AliTPCDcalibRes::Load(snextfile.Data());
if (!dcalibRes) {
::Error("ProcessOutput","Did not find calib object in %s, job Killed",snextfile.Data());
exit(1);
}
int ntrUse = dcalibRes->GetNTracksUsed();
int ntrMin = dcalibRes->GetMinTrackToUse();
if (ntrminUser>0) ntrMin = ntrminUser;
if (ntrUse<ntrMin) {
::Error("ProcessOutput","Low stat:%d tracks used (min: %d) in %s",ntrUse,ntrMin,snextfile.Data());
lowStatJobs++;
}
else {
::Info("ProcessOutput","stat is OK :%d tracks used (min: %d) in %s",ntrUse,ntrMin,snextfile.Data());
}
AliTPCChebCorr* c = corr ? dcalibRes->GetChebCorrObject() : dcalibRes->GetChebDistObject();
if (!c) {
::Error("ProcessOutput","Did not find %s Cheb.parm in %s",corr ? "Correction":"Distortion" ,snextfile.Data());
exit(1);
}
a->Add(c);
nJobs++;
}
if (lowStatJobs) {
::Error("ProcessOutput","%d out of %d timebins have low stat, will not update OCDB",lowStatJobs,nJobs);
}
else {
a->Print();
CreateCorrMapObjTime(a, startRun, endRun, ocdbStorage);
}
delete a;
delete listoffiles;
return kTRUE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: kdevcllayer.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 01:38:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"
#ifndef KDEVCLLAYER_HXX_
#include "kdevcllayer.hxx"
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_PROPERTYINFO_HPP_
#include <com/sun/star/configuration/backend/PropertyInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERCONTENTDESCIBER_HPP_
#include <com/sun/star/configuration/backend/XLayerContentDescriber.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef INCLUDED_VCL_KDE_HEADERS_H
#include <vcl/kde_headers.h>
#endif
//==============================================================================
KDEVCLLayer::KDEVCLLayer(const uno::Reference<uno::XComponentContext>& xContext)
{
//Create instance of LayerContentDescriber Service
rtl::OUString const k_sLayerDescriberService(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.comp.configuration.backend.LayerDescriber"));
typedef uno::Reference<backend::XLayerContentDescriber> LayerDescriber;
uno::Reference< lang::XMultiComponentFactory > xServiceManager = xContext->getServiceManager();
if( xServiceManager.is() )
{
m_xLayerContentDescriber = LayerDescriber::query(
xServiceManager->createInstanceWithContext(k_sLayerDescriberService, xContext));
}
else
{
OSL_TRACE("Could not retrieve ServiceManager");
}
}
//------------------------------------------------------------------------------
void SAL_CALL KDEVCLLayer::readData( const uno::Reference<backend::XLayerHandler>& xHandler)
throw ( backend::MalformedDataException, lang::NullPointerException,
lang::WrappedTargetException, uno::RuntimeException)
{
if( ! m_xLayerContentDescriber.is() )
{
throw uno::RuntimeException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
"Could not create com.sun.star.configuration.backend.LayerContentDescriber Service"
) ), static_cast < backend::XLayer * > (this) );
}
uno::Sequence<backend::PropertyInfo> aPropInfoList(1);
/*
Commenting out, does not make much sense without an accessibility bridge
===========================================================================
#if defined(QT_ACCESSIBILITY_SUPPORT)
// Accessibility tools under Qt for UNIX are available starting with Qt 4.0
int nVersionMajor = 0;
const char *q = qVersion(); // "3.1.0" for example
while ('0' <= *q && *q <= '9')
nVersionMajor = nVersionMajor * 10 + *q++ - '0';
sal_Bool ATToolSupport = (sal_Bool) (nVersionMajor >= 4);
#else
sal_Bool ATToolSupport = sal_False;
#endif
===========================================================================
End of commented out section
*/ sal_Bool ATToolSupport = sal_False;
aPropInfoList[0].Name = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.VCL/Settings/Accessibility/EnableATToolSupport") );
aPropInfoList[0].Type = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "string" ) );
aPropInfoList[0].Protected = sal_False;
aPropInfoList[0].Value = uno::makeAny( rtl::OUString::valueOf( ATToolSupport ) );
m_xLayerContentDescriber->describeLayer(xHandler, aPropInfoList);
}
//------------------------------------------------------------------------------
rtl::OUString SAL_CALL KDEVCLLayer::getTimestamp(void)
throw (uno::RuntimeException)
{
// Return the value as timestamp to avoid regenerating the binary cache
// on each office launch.
::rtl::OUString sTimeStamp(
RTL_CONSTASCII_USTRINGPARAM( "FALSE" ) );
return sTimeStamp;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.122); FILE MERGED 2008/04/01 15:40:12 thb 1.4.122.3: #i85898# Stripping all external header guards 2008/04/01 12:41:10 thb 1.4.122.2: #i85898# Stripping all external header guards 2008/03/31 13:17:07 rt 1.4.122.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: kdevcllayer.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"
#include "kdevcllayer.hxx"
#include <com/sun/star/configuration/backend/PropertyInfo.hpp>
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERCONTENTDESCIBER_HPP_
#include <com/sun/star/configuration/backend/XLayerContentDescriber.hpp>
#endif
#include <com/sun/star/uno/Sequence.hxx>
#include <vcl/kde_headers.h>
//==============================================================================
KDEVCLLayer::KDEVCLLayer(const uno::Reference<uno::XComponentContext>& xContext)
{
//Create instance of LayerContentDescriber Service
rtl::OUString const k_sLayerDescriberService(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.comp.configuration.backend.LayerDescriber"));
typedef uno::Reference<backend::XLayerContentDescriber> LayerDescriber;
uno::Reference< lang::XMultiComponentFactory > xServiceManager = xContext->getServiceManager();
if( xServiceManager.is() )
{
m_xLayerContentDescriber = LayerDescriber::query(
xServiceManager->createInstanceWithContext(k_sLayerDescriberService, xContext));
}
else
{
OSL_TRACE("Could not retrieve ServiceManager");
}
}
//------------------------------------------------------------------------------
void SAL_CALL KDEVCLLayer::readData( const uno::Reference<backend::XLayerHandler>& xHandler)
throw ( backend::MalformedDataException, lang::NullPointerException,
lang::WrappedTargetException, uno::RuntimeException)
{
if( ! m_xLayerContentDescriber.is() )
{
throw uno::RuntimeException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
"Could not create com.sun.star.configuration.backend.LayerContentDescriber Service"
) ), static_cast < backend::XLayer * > (this) );
}
uno::Sequence<backend::PropertyInfo> aPropInfoList(1);
/*
Commenting out, does not make much sense without an accessibility bridge
===========================================================================
#if defined(QT_ACCESSIBILITY_SUPPORT)
// Accessibility tools under Qt for UNIX are available starting with Qt 4.0
int nVersionMajor = 0;
const char *q = qVersion(); // "3.1.0" for example
while ('0' <= *q && *q <= '9')
nVersionMajor = nVersionMajor * 10 + *q++ - '0';
sal_Bool ATToolSupport = (sal_Bool) (nVersionMajor >= 4);
#else
sal_Bool ATToolSupport = sal_False;
#endif
===========================================================================
End of commented out section
*/ sal_Bool ATToolSupport = sal_False;
aPropInfoList[0].Name = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.VCL/Settings/Accessibility/EnableATToolSupport") );
aPropInfoList[0].Type = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "string" ) );
aPropInfoList[0].Protected = sal_False;
aPropInfoList[0].Value = uno::makeAny( rtl::OUString::valueOf( ATToolSupport ) );
m_xLayerContentDescriber->describeLayer(xHandler, aPropInfoList);
}
//------------------------------------------------------------------------------
rtl::OUString SAL_CALL KDEVCLLayer::getTimestamp(void)
throw (uno::RuntimeException)
{
// Return the value as timestamp to avoid regenerating the binary cache
// on each office launch.
::rtl::OUString sTimeStamp(
RTL_CONSTASCII_USTRINGPARAM( "FALSE" ) );
return sTimeStamp;
}
<|endoftext|> |
<commit_before>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation ([email protected])
*
* If you have questions regarding the use of this file, please contact
* Nokia at [email protected].
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettingswidget.h"
#include <MButton>
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MContentItem>
#include <MAbstractCellCreator>
#include <MList>
#include <MDialog>
#include <MBanner>
#include <QObject>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTimer>
#include <QDebug>
namespace
{
//!object name for settings' widgets
const QString ObjectNameSelectedKeyboardsItem("SelectedKeyboardsItem");
const QString ObjectNameErrorCorrectionButton("KeyboardErrorCorrectionButton");
const QString ObjectNameCorrectionSpaceButton("KeyboardCorrectionSpaceButton");
const int MKeyboardLayoutRole = Qt::UserRole + 1;
};
class MKeyboardCellCreator: public MAbstractCellCreator<MContentItem>
{
public:
/*! \reimp */
virtual MWidget *createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const;
virtual void updateCell(const QModelIndex &index, MWidget *cell) const;
/*! \reimp_end */
private:
void updateContentItemMode(const QModelIndex &index, MContentItem *contentItem) const;
};
MWidget *MKeyboardCellCreator::createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const
{
MContentItem *cell = qobject_cast<MContentItem *>(recycler.take("MContentItem"));
if (!cell) {
cell = new MContentItem(MContentItem::SingleTextLabel);
}
updateCell(index, cell);
return cell;
}
void MKeyboardCellCreator::updateCell(const QModelIndex &index, MWidget *cell) const
{
MContentItem *contentItem = qobject_cast<MContentItem *>(cell);
QString layoutTile = index.data(Qt::DisplayRole).toString();
contentItem->setTitle(layoutTile);
}
void MKeyboardCellCreator::updateContentItemMode(const QModelIndex &index,
MContentItem *contentItem) const
{
const int row = index.row();
bool thereIsNextRow = index.sibling(row + 1, 0).isValid();
if (row == 0) {
contentItem->setItemMode(MContentItem::SingleColumnTop);
} else if (thereIsNextRow) {
contentItem->setItemMode(MContentItem::SingleColumnCenter);
} else {
contentItem->setItemMode(MContentItem::SingleColumnBottom);
}
}
MKeyboardSettingsWidget::MKeyboardSettingsWidget(MKeyboardSettings *settings, QGraphicsItem *parent)
: MWidget(parent),
settingsObject(settings),
keyboardDialog(0),
keyboardList(0)
{
MLayout *layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
//To make sure that both columns have the same width, give them the same preferred width.
landscapePolicy->setColumnPreferredWidth(0, 800);
landscapePolicy->setColumnPreferredWidth(1, 800);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
layout->setLandscapePolicy(landscapePolicy);
layout->setPortraitPolicy(portraitPolicy);
buildUi();
syncErrorCorrectionState();
syncCorrectionSpaceState();
retranslateUi();
connectSlots();
}
MKeyboardSettingsWidget::~MKeyboardSettingsWidget()
{
delete keyboardDialog;
keyboardDialog = 0;
}
void MKeyboardSettingsWidget::buildUi()
{
selectedKeyboardsItem = new MContentItem(MContentItem::TwoTextLabels, this);
selectedKeyboardsItem->setObjectName(ObjectNameSelectedKeyboardsItem);
connect(selectedKeyboardsItem, SIGNAL(clicked()), this, SLOT(showKeyboardList()));
// Put to first row, first column on the grid
addItem(selectedKeyboardsItem, 0, 0);
// Error correction settings
errorCorrectionSwitch = new MButton(this);
errorCorrectionSwitch->setObjectName(ObjectNameErrorCorrectionButton);
errorCorrectionSwitch->setViewType(MButton::switchType);
errorCorrectionSwitch->setCheckable(true);
errorCorrectionContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Error correction description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
QGraphicsLinearLayout *eCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
eCLayout->addItem(errorCorrectionContentItem);
eCLayout->addItem(errorCorrectionSwitch);
eCLayout->setAlignment(errorCorrectionSwitch, Qt::AlignCenter);
// Put to first row, second column on the grid
addItem(eCLayout, 0, 1);
// "Space selects the correction candidate" settings
correctionSpaceSwitch = new MButton(this);
correctionSpaceSwitch->setObjectName(ObjectNameCorrectionSpaceButton);
correctionSpaceSwitch->setViewType(MButton::switchType);
correctionSpaceSwitch->setCheckable(true);
correctionSpaceContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Select with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
//% "Select with space description"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_error_select_with_space_description"));
QGraphicsLinearLayout *wCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
wCLayout->addItem(correctionSpaceContentItem);
wCLayout->addItem(correctionSpaceSwitch);
wCLayout->setAlignment(correctionSpaceSwitch, Qt::AlignCenter);
// Put to second row, second column on the grid
addItem(wCLayout, 1, 1);
}
void MKeyboardSettingsWidget::addItem(QGraphicsLayoutItem *item, int row, int column)
{
landscapePolicy->addItem(item, row, column);
portraitPolicy->addItem(item);
}
void MKeyboardSettingsWidget::retranslateUi()
{
updateTitle();
MWidget::retranslateUi();
}
void MKeyboardSettingsWidget::updateTitle()
{
if (!errorCorrectionContentItem || !correctionSpaceContentItem
|| !settingsObject || !selectedKeyboardsItem)
return;
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Select with space description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
//% "Select with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
//% "Select with space description"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_error_select_with_space_description"));
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
selectedKeyboardsItem->setTitle(title);
QString brief;
if (keyboards.count() > 0) {
foreach(const QString &keyboard, keyboards) {
if (!brief.isEmpty())
brief += QString(", ");
brief += keyboard;
}
} else {
//% "No keyboards installed"
brief = qtTrId("qtn_txts_no_keyboards");
}
selectedKeyboardsItem->setSubtitle(brief);
if (keyboardDialog) {
keyboardDialog->setTitle(title);
}
}
void MKeyboardSettingsWidget::connectSlots()
{
connect(this, SIGNAL(visibleChanged()),
this, SLOT(handleVisibilityChanged()));
if (!settingsObject || !errorCorrectionSwitch || !correctionSpaceSwitch)
return;
connect(errorCorrectionSwitch, SIGNAL(toggled(bool)),
this, SLOT(setErrorCorrectionState(bool)));
connect(settingsObject, SIGNAL(errorCorrectionChanged()),
this, SLOT(syncErrorCorrectionState()));
connect(correctionSpaceSwitch, SIGNAL(toggled(bool)),
this, SLOT(setCorrectionSpaceState(bool)));
connect(settingsObject, SIGNAL(correctionSpaceChanged()),
this, SLOT(syncCorrectionSpaceState()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateTitle()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateKeyboardSelectionModel()));
}
void MKeyboardSettingsWidget::showKeyboardList()
{
if (!settingsObject || !keyboardDialog) {
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString keyboardTitle = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
keyboardDialog = new MDialog(keyboardTitle, M::NoStandardButton);
keyboardList = new MList(keyboardDialog);
MKeyboardCellCreator *cellCreator = new MKeyboardCellCreator;
keyboardList->setCellCreator(cellCreator);
QStandardItemModel *model = new QStandardItemModel;
model->sort(0);
keyboardList->setItemModel(model);
keyboardList->setSelectionMode(MList::MultiSelection);
keyboardList->setSelectionModel(new QItemSelectionModel(model, this));
keyboardDialog->setCentralWidget(keyboardList);
connect(keyboardList, SIGNAL(itemClicked(const QModelIndex &)),
this, SLOT(updateSelectedKeyboards(const QModelIndex &)));
}
updateKeyboardModel();
keyboardDialog->exec();
}
void MKeyboardSettingsWidget::updateKeyboardModel()
{
if (!settingsObject || !keyboardList)
return;
//always reload available layouts in case user install/remove some layouts
settingsObject->readAvailableKeyboards();
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
model->clear();
QMap<QString, QString> availableKeyboards = settingsObject->availableKeyboards();
QMap<QString, QString>::const_iterator i = availableKeyboards.constBegin();
while (i != availableKeyboards.constEnd()) {
QStandardItem *item = new QStandardItem(i.value());
item->setData(i.value(), Qt::DisplayRole);
item->setData(i.key(), MKeyboardLayoutRole);
model->appendRow(item);
++i;
}
updateKeyboardSelectionModel();
}
void MKeyboardSettingsWidget::updateKeyboardSelectionModel()
{
if (!settingsObject || !keyboardList)
return;
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
foreach (const QString &keyboard, settingsObject->selectedKeyboards().values()) {
QList<QStandardItem *> items = model->findItems(keyboard);
foreach (const QStandardItem *item, items) {
keyboardList->selectionModel()->select(item->index(), QItemSelectionModel::Select);
}
}
}
void MKeyboardSettingsWidget::updateSelectedKeyboards(const QModelIndex &index)
{
if (!settingsObject || !index.isValid() || !keyboardList
|| !keyboardList->selectionModel())
return;
QStringList updatedKeyboardLayouts;
foreach (const QModelIndex &i, keyboardList->selectionModel()->selectedIndexes()) {
updatedKeyboardLayouts << i.data(MKeyboardLayoutRole).toString();
}
if (updatedKeyboardLayouts.isEmpty()) {
notifyNoKeyboards();
}
settingsObject->setSelectedKeyboards(updatedKeyboardLayouts);
//update titles
retranslateUi();
}
void MKeyboardSettingsWidget::setErrorCorrectionState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->errorCorrection() != enabled) {
settingsObject->setErrorCorrection(enabled);
if (!enabled) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::syncErrorCorrectionState()
{
if (!settingsObject)
return;
const bool errorCorrectionState = settingsObject->errorCorrection();
if (errorCorrectionSwitch
&& errorCorrectionSwitch->isChecked() != errorCorrectionState) {
errorCorrectionSwitch->setChecked(errorCorrectionState);
if (!errorCorrectionState) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::setCorrectionSpaceState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->correctionSpace() != enabled)
settingsObject->setCorrectionSpace(enabled);
}
void MKeyboardSettingsWidget::syncCorrectionSpaceState()
{
if (!settingsObject)
return;
const bool correctionSpaceState = settingsObject->correctionSpace();
if (correctionSpaceSwitch
&& correctionSpaceSwitch->isChecked() != correctionSpaceState) {
correctionSpaceSwitch->setChecked(correctionSpaceState);
}
}
void MKeyboardSettingsWidget::notifyNoKeyboards()
{
MBanner *noKeyboardsNotification = new MBanner;
//% "Note: you have uninstalled all virtual keyboards"
noKeyboardsNotification->setTitle(qtTrId("qtn_txts_no_keyboards_notification"));
noKeyboardsNotification->appear(MSceneWindow::DestroyWhenDone);
}
void MKeyboardSettingsWidget::handleVisibilityChanged()
{
// This is a workaround to hide settings dialog when keyboard is hidden.
// And it could be removed when NB#177922 is fixed.
if (!isVisible() && keyboardDialog) {
// reject settings dialog if the visibility of settings widget
// is changed from shown to hidden.
keyboardDialog->reject();
}
}
<commit_msg>Changes: Remove UI string duplications<commit_after>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation ([email protected])
*
* If you have questions regarding the use of this file, please contact
* Nokia at [email protected].
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettingswidget.h"
#include <MButton>
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MContentItem>
#include <MAbstractCellCreator>
#include <MList>
#include <MDialog>
#include <MBanner>
#include <QObject>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTimer>
#include <QDebug>
namespace
{
//!object name for settings' widgets
const QString ObjectNameSelectedKeyboardsItem("SelectedKeyboardsItem");
const QString ObjectNameErrorCorrectionButton("KeyboardErrorCorrectionButton");
const QString ObjectNameCorrectionSpaceButton("KeyboardCorrectionSpaceButton");
const int MKeyboardLayoutRole = Qt::UserRole + 1;
};
class MKeyboardCellCreator: public MAbstractCellCreator<MContentItem>
{
public:
/*! \reimp */
virtual MWidget *createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const;
virtual void updateCell(const QModelIndex &index, MWidget *cell) const;
/*! \reimp_end */
private:
void updateContentItemMode(const QModelIndex &index, MContentItem *contentItem) const;
};
MWidget *MKeyboardCellCreator::createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const
{
MContentItem *cell = qobject_cast<MContentItem *>(recycler.take("MContentItem"));
if (!cell) {
cell = new MContentItem(MContentItem::SingleTextLabel);
}
updateCell(index, cell);
return cell;
}
void MKeyboardCellCreator::updateCell(const QModelIndex &index, MWidget *cell) const
{
MContentItem *contentItem = qobject_cast<MContentItem *>(cell);
QString layoutTile = index.data(Qt::DisplayRole).toString();
contentItem->setTitle(layoutTile);
}
void MKeyboardCellCreator::updateContentItemMode(const QModelIndex &index,
MContentItem *contentItem) const
{
const int row = index.row();
bool thereIsNextRow = index.sibling(row + 1, 0).isValid();
if (row == 0) {
contentItem->setItemMode(MContentItem::SingleColumnTop);
} else if (thereIsNextRow) {
contentItem->setItemMode(MContentItem::SingleColumnCenter);
} else {
contentItem->setItemMode(MContentItem::SingleColumnBottom);
}
}
MKeyboardSettingsWidget::MKeyboardSettingsWidget(MKeyboardSettings *settings, QGraphicsItem *parent)
: MWidget(parent),
settingsObject(settings),
keyboardDialog(0),
keyboardList(0)
{
MLayout *layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
//To make sure that both columns have the same width, give them the same preferred width.
landscapePolicy->setColumnPreferredWidth(0, 800);
landscapePolicy->setColumnPreferredWidth(1, 800);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
layout->setLandscapePolicy(landscapePolicy);
layout->setPortraitPolicy(portraitPolicy);
buildUi();
syncErrorCorrectionState();
syncCorrectionSpaceState();
retranslateUi();
connectSlots();
}
MKeyboardSettingsWidget::~MKeyboardSettingsWidget()
{
delete keyboardDialog;
keyboardDialog = 0;
}
void MKeyboardSettingsWidget::buildUi()
{
selectedKeyboardsItem = new MContentItem(MContentItem::TwoTextLabels, this);
selectedKeyboardsItem->setObjectName(ObjectNameSelectedKeyboardsItem);
connect(selectedKeyboardsItem, SIGNAL(clicked()), this, SLOT(showKeyboardList()));
// Put to first row, first column on the grid
addItem(selectedKeyboardsItem, 0, 0);
// Error correction settings
errorCorrectionSwitch = new MButton(this);
errorCorrectionSwitch->setObjectName(ObjectNameErrorCorrectionButton);
errorCorrectionSwitch->setViewType(MButton::switchType);
errorCorrectionSwitch->setCheckable(true);
errorCorrectionContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Error correction description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
QGraphicsLinearLayout *eCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
eCLayout->addItem(errorCorrectionContentItem);
eCLayout->addItem(errorCorrectionSwitch);
eCLayout->setAlignment(errorCorrectionSwitch, Qt::AlignCenter);
// Put to first row, second column on the grid
addItem(eCLayout, 0, 1);
// "Space selects the correction candidate" settings
correctionSpaceSwitch = new MButton(this);
correctionSpaceSwitch->setObjectName(ObjectNameCorrectionSpaceButton);
correctionSpaceSwitch->setViewType(MButton::switchType);
correctionSpaceSwitch->setCheckable(true);
correctionSpaceContentItem = new MContentItem(MContentItem::TwoTextLabels, this);
//% "Select with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
//% "Select with space description"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_error_select_with_space_description"));
QGraphicsLinearLayout *wCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
wCLayout->addItem(correctionSpaceContentItem);
wCLayout->addItem(correctionSpaceSwitch);
wCLayout->setAlignment(correctionSpaceSwitch, Qt::AlignCenter);
// Put to second row, second column on the grid
addItem(wCLayout, 1, 1);
}
void MKeyboardSettingsWidget::addItem(QGraphicsLayoutItem *item, int row, int column)
{
landscapePolicy->addItem(item, row, column);
portraitPolicy->addItem(item);
}
void MKeyboardSettingsWidget::retranslateUi()
{
updateTitle();
MWidget::retranslateUi();
}
void MKeyboardSettingsWidget::updateTitle()
{
if (!errorCorrectionContentItem || !correctionSpaceContentItem
|| !settingsObject || !selectedKeyboardsItem)
return;
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_select_with_space"));
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_error_select_with_space_description"));
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
selectedKeyboardsItem->setTitle(title);
QString brief;
if (keyboards.count() > 0) {
foreach(const QString &keyboard, keyboards) {
if (!brief.isEmpty())
brief += QString(", ");
brief += keyboard;
}
} else {
//% "No keyboards installed"
brief = qtTrId("qtn_txts_no_keyboards");
}
selectedKeyboardsItem->setSubtitle(brief);
if (keyboardDialog) {
keyboardDialog->setTitle(title);
}
}
void MKeyboardSettingsWidget::connectSlots()
{
connect(this, SIGNAL(visibleChanged()),
this, SLOT(handleVisibilityChanged()));
if (!settingsObject || !errorCorrectionSwitch || !correctionSpaceSwitch)
return;
connect(errorCorrectionSwitch, SIGNAL(toggled(bool)),
this, SLOT(setErrorCorrectionState(bool)));
connect(settingsObject, SIGNAL(errorCorrectionChanged()),
this, SLOT(syncErrorCorrectionState()));
connect(correctionSpaceSwitch, SIGNAL(toggled(bool)),
this, SLOT(setCorrectionSpaceState(bool)));
connect(settingsObject, SIGNAL(correctionSpaceChanged()),
this, SLOT(syncCorrectionSpaceState()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateTitle()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateKeyboardSelectionModel()));
}
void MKeyboardSettingsWidget::showKeyboardList()
{
if (!settingsObject || !keyboardDialog) {
QStringList keyboards = settingsObject->selectedKeyboards().values();
QString keyboardTitle = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
keyboardDialog = new MDialog(keyboardTitle, M::NoStandardButton);
keyboardList = new MList(keyboardDialog);
MKeyboardCellCreator *cellCreator = new MKeyboardCellCreator;
keyboardList->setCellCreator(cellCreator);
QStandardItemModel *model = new QStandardItemModel;
model->sort(0);
keyboardList->setItemModel(model);
keyboardList->setSelectionMode(MList::MultiSelection);
keyboardList->setSelectionModel(new QItemSelectionModel(model, this));
keyboardDialog->setCentralWidget(keyboardList);
connect(keyboardList, SIGNAL(itemClicked(const QModelIndex &)),
this, SLOT(updateSelectedKeyboards(const QModelIndex &)));
}
updateKeyboardModel();
keyboardDialog->exec();
}
void MKeyboardSettingsWidget::updateKeyboardModel()
{
if (!settingsObject || !keyboardList)
return;
//always reload available layouts in case user install/remove some layouts
settingsObject->readAvailableKeyboards();
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
model->clear();
QMap<QString, QString> availableKeyboards = settingsObject->availableKeyboards();
QMap<QString, QString>::const_iterator i = availableKeyboards.constBegin();
while (i != availableKeyboards.constEnd()) {
QStandardItem *item = new QStandardItem(i.value());
item->setData(i.value(), Qt::DisplayRole);
item->setData(i.key(), MKeyboardLayoutRole);
model->appendRow(item);
++i;
}
updateKeyboardSelectionModel();
}
void MKeyboardSettingsWidget::updateKeyboardSelectionModel()
{
if (!settingsObject || !keyboardList)
return;
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
foreach (const QString &keyboard, settingsObject->selectedKeyboards().values()) {
QList<QStandardItem *> items = model->findItems(keyboard);
foreach (const QStandardItem *item, items) {
keyboardList->selectionModel()->select(item->index(), QItemSelectionModel::Select);
}
}
}
void MKeyboardSettingsWidget::updateSelectedKeyboards(const QModelIndex &index)
{
if (!settingsObject || !index.isValid() || !keyboardList
|| !keyboardList->selectionModel())
return;
QStringList updatedKeyboardLayouts;
foreach (const QModelIndex &i, keyboardList->selectionModel()->selectedIndexes()) {
updatedKeyboardLayouts << i.data(MKeyboardLayoutRole).toString();
}
if (updatedKeyboardLayouts.isEmpty()) {
notifyNoKeyboards();
}
settingsObject->setSelectedKeyboards(updatedKeyboardLayouts);
//update titles
retranslateUi();
}
void MKeyboardSettingsWidget::setErrorCorrectionState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->errorCorrection() != enabled) {
settingsObject->setErrorCorrection(enabled);
if (!enabled) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::syncErrorCorrectionState()
{
if (!settingsObject)
return;
const bool errorCorrectionState = settingsObject->errorCorrection();
if (errorCorrectionSwitch
&& errorCorrectionSwitch->isChecked() != errorCorrectionState) {
errorCorrectionSwitch->setChecked(errorCorrectionState);
if (!errorCorrectionState) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::setCorrectionSpaceState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->correctionSpace() != enabled)
settingsObject->setCorrectionSpace(enabled);
}
void MKeyboardSettingsWidget::syncCorrectionSpaceState()
{
if (!settingsObject)
return;
const bool correctionSpaceState = settingsObject->correctionSpace();
if (correctionSpaceSwitch
&& correctionSpaceSwitch->isChecked() != correctionSpaceState) {
correctionSpaceSwitch->setChecked(correctionSpaceState);
}
}
void MKeyboardSettingsWidget::notifyNoKeyboards()
{
MBanner *noKeyboardsNotification = new MBanner;
//% "Note: you have uninstalled all virtual keyboards"
noKeyboardsNotification->setTitle(qtTrId("qtn_txts_no_keyboards_notification"));
noKeyboardsNotification->appear(MSceneWindow::DestroyWhenDone);
}
void MKeyboardSettingsWidget::handleVisibilityChanged()
{
// This is a workaround to hide settings dialog when keyboard is hidden.
// And it could be removed when NB#177922 is fixed.
if (!isVisible() && keyboardDialog) {
// reject settings dialog if the visibility of settings widget
// is changed from shown to hidden.
keyboardDialog->reject();
}
}
<|endoftext|> |
<commit_before>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation ([email protected])
*
* If you have questions regarding the use of this file, please contact
* Nokia at [email protected].
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettingswidget.h"
#include <MButton>
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MContentItem>
#include <MAbstractCellCreator>
#include <MList>
#include <MDialog>
#include <MBanner>
#include <MBasicListItem>
#include <QObject>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTimer>
#include <QDebug>
namespace
{
//!object name for settings' widgets
const QString ObjectNameSelectedKeyboardsItem("SelectedKeyboardsItem");
const QString ObjectNameErrorCorrectionButton("KeyboardErrorCorrectionButton");
const QString ObjectNameCorrectionSpaceButton("KeyboardCorrectionSpaceButton");
const int MKeyboardLayoutRole = Qt::UserRole + 1;
};
class MKeyboardCellCreator: public MAbstractCellCreator<MContentItem>
{
public:
/*! \reimp */
virtual MWidget *createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const;
virtual void updateCell(const QModelIndex &index, MWidget *cell) const;
/*! \reimp_end */
private:
void updateContentItemMode(const QModelIndex &index, MContentItem *contentItem) const;
};
MWidget *MKeyboardCellCreator::createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const
{
MContentItem *cell = qobject_cast<MContentItem *>(recycler.take("MContentItem"));
if (!cell) {
cell = new MContentItem(MContentItem::SingleTextLabel);
}
updateCell(index, cell);
return cell;
}
void MKeyboardCellCreator::updateCell(const QModelIndex &index, MWidget *cell) const
{
MContentItem *contentItem = qobject_cast<MContentItem *>(cell);
QString layoutTile = index.data(Qt::DisplayRole).toString();
contentItem->setTitle(layoutTile);
}
void MKeyboardCellCreator::updateContentItemMode(const QModelIndex &index,
MContentItem *contentItem) const
{
const int row = index.row();
bool thereIsNextRow = index.sibling(row + 1, 0).isValid();
if (row == 0) {
contentItem->setItemMode(MContentItem::SingleColumnTop);
} else if (thereIsNextRow) {
contentItem->setItemMode(MContentItem::SingleColumnCenter);
} else {
contentItem->setItemMode(MContentItem::SingleColumnBottom);
}
}
MKeyboardSettingsWidget::MKeyboardSettingsWidget(MKeyboardSettings *settings, QGraphicsItem *parent)
: MWidget(parent),
settingsObject(settings),
keyboardDialog(0),
keyboardList(0)
{
MLayout *layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
//To make sure that both columns have the same width, give them the same preferred width.
landscapePolicy->setColumnPreferredWidth(0, 800);
landscapePolicy->setColumnPreferredWidth(1, 800);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
layout->setLandscapePolicy(landscapePolicy);
layout->setPortraitPolicy(portraitPolicy);
buildUi();
syncErrorCorrectionState();
syncCorrectionSpaceState();
retranslateUi();
connectSlots();
}
MKeyboardSettingsWidget::~MKeyboardSettingsWidget()
{
delete keyboardDialog;
keyboardDialog = 0;
}
void MKeyboardSettingsWidget::buildUi()
{
// We are using MBasicListItem instead of MContentItem because
// the latter is not supported by theme
selectedKeyboardsItem = new MBasicListItem(MBasicListItem::TitleWithSubtitle, this);
selectedKeyboardsItem->setObjectName(ObjectNameSelectedKeyboardsItem);
connect(selectedKeyboardsItem, SIGNAL(clicked()), this, SLOT(showKeyboardList()));
selectedKeyboardsItem->setStyleName("CommonBasicListItemInverted");
// Put to first row, first column on the grid
addItem(selectedKeyboardsItem, 0, 0);
// Error correction settings
errorCorrectionSwitch = new MButton(this);
errorCorrectionSwitch->setObjectName(ObjectNameErrorCorrectionButton);
errorCorrectionSwitch->setViewType(MButton::switchType);
errorCorrectionSwitch->setCheckable(true);
errorCorrectionContentItem = new MBasicListItem(MBasicListItem::TitleWithSubtitle, this);
errorCorrectionContentItem->setStyleName("CommonBasicListItemInverted");
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Error correction description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
QGraphicsLinearLayout *eCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
eCLayout->addItem(errorCorrectionContentItem);
eCLayout->addItem(errorCorrectionSwitch);
eCLayout->setAlignment(errorCorrectionSwitch, Qt::AlignCenter);
// Put to first row, second column on the grid
addItem(eCLayout, 0, 1);
// "Space selects the correction candidate" settings
correctionSpaceSwitch = new MButton(this);
correctionSpaceSwitch->setObjectName(ObjectNameCorrectionSpaceButton);
correctionSpaceSwitch->setViewType(MButton::switchType);
correctionSpaceSwitch->setCheckable(true);
correctionSpaceContentItem = new MBasicListItem(MBasicListItem::TitleWithSubtitle, this);
correctionSpaceContentItem->setStyleName("CommonBasicListItemInverted");
//% "Insert with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_insert_with_space"));
//% "Space key inserts the suggested word"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_insert_with_space_description"));
QGraphicsLinearLayout *wCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
wCLayout->addItem(correctionSpaceContentItem);
wCLayout->addItem(correctionSpaceSwitch);
wCLayout->setAlignment(correctionSpaceSwitch, Qt::AlignCenter);
// Put to second row, second column on the grid
addItem(wCLayout, 1, 1);
}
void MKeyboardSettingsWidget::addItem(QGraphicsLayoutItem *item, int row, int column)
{
landscapePolicy->addItem(item, row, column);
portraitPolicy->addItem(item);
}
void MKeyboardSettingsWidget::retranslateUi()
{
updateTitle();
MWidget::retranslateUi();
}
void MKeyboardSettingsWidget::updateTitle()
{
if (!errorCorrectionContentItem || !correctionSpaceContentItem
|| !settingsObject || !selectedKeyboardsItem)
return;
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_insert_with_space"));
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_insert_with_space_description"));
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
selectedKeyboardsItem->setTitle(title);
QString brief;
if (keyboards.count() > 0) {
foreach(const QString &keyboard, keyboards) {
if (!brief.isEmpty())
brief += QString(", ");
brief += keyboard;
}
} else {
//% "No keyboards installed"
brief = qtTrId("qtn_txts_no_keyboards");
}
selectedKeyboardsItem->setSubtitle(brief);
if (keyboardDialog) {
keyboardDialog->setTitle(title);
}
}
void MKeyboardSettingsWidget::connectSlots()
{
connect(this, SIGNAL(visibleChanged()),
this, SLOT(handleVisibilityChanged()));
if (!settingsObject || !errorCorrectionSwitch || !correctionSpaceSwitch)
return;
connect(errorCorrectionSwitch, SIGNAL(toggled(bool)),
this, SLOT(setErrorCorrectionState(bool)));
connect(settingsObject, SIGNAL(errorCorrectionChanged()),
this, SLOT(syncErrorCorrectionState()));
connect(correctionSpaceSwitch, SIGNAL(toggled(bool)),
this, SLOT(setCorrectionSpaceState(bool)));
connect(settingsObject, SIGNAL(correctionSpaceChanged()),
this, SLOT(syncCorrectionSpaceState()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateKeyboardSelectionModel()));
}
void MKeyboardSettingsWidget::showKeyboardList()
{
if (!settingsObject)
return;
QStringList keyboards = settingsObject->selectedKeyboards().values();
if (!keyboardDialog) {
keyboardDialog = new MDialog();
keyboardList = new MList(keyboardDialog);
MKeyboardCellCreator *cellCreator = new MKeyboardCellCreator;
keyboardList->setCellCreator(cellCreator);
keyboardList->setSelectionMode(MList::MultiSelection);
createKeyboardModel();
keyboardDialog->setCentralWidget(keyboardList);
keyboardDialog->addButton(M::DoneButton);
connect(keyboardList, SIGNAL(itemClicked(const QModelIndex &)),
this, SLOT(updateSelectedKeyboards(const QModelIndex &)));
connect(keyboardDialog, SIGNAL(accepted()),
this, SLOT(selectKeyboards()));
}
// We need to update the title every time because probably the dialog was
// cancelled/closed without tapping on the Done button.
QString keyboardTitle = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
keyboardDialog->setTitle(keyboardTitle);
keyboardDialog->exec();
}
void MKeyboardSettingsWidget::createKeyboardModel()
{
if (!settingsObject || !keyboardList)
return;
QMap<QString, QString> availableKeyboards = settingsObject->availableKeyboards();
QStandardItemModel *model = new QStandardItemModel(availableKeyboards.size(), 1, keyboardList);
QMap<QString, QString>::const_iterator i = availableKeyboards.constBegin();
for (int j = 0; i != availableKeyboards.constEnd(); ++i, ++j) {
QStandardItem *item = new QStandardItem(i.value());
item->setData(i.value(), Qt::DisplayRole);
item->setData(i.key(), MKeyboardLayoutRole);
model->setItem(j, item);
}
model->sort(0);
keyboardList->setItemModel(model);
keyboardList->setSelectionModel(new QItemSelectionModel(model, keyboardList));
updateKeyboardSelectionModel();
}
void MKeyboardSettingsWidget::updateKeyboardSelectionModel()
{
if (!settingsObject || !keyboardList)
return;
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
foreach (const QString &keyboard, settingsObject->selectedKeyboards().values()) {
QList<QStandardItem *> items = model->findItems(keyboard);
foreach (const QStandardItem *item, items) {
keyboardList->selectionModel()->select(item->index(), QItemSelectionModel::Select);
}
}
}
void MKeyboardSettingsWidget::updateSelectedKeyboards(const QModelIndex &index)
{
if (!index.isValid() || !keyboardDialog || !keyboardList
|| !keyboardList->selectionModel())
return;
QModelIndexList indexList = keyboardList->selectionModel()->selectedIndexes();
// Update the dialog title
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(indexList.size());
keyboardDialog->setTitle(title);
}
void MKeyboardSettingsWidget::selectKeyboards()
{
if (!settingsObject || !keyboardDialog)
return;
QStringList updatedKeyboardLayouts;
QModelIndexList indexList = keyboardList->selectionModel()->selectedIndexes();
foreach (const QModelIndex &i, indexList) {
updatedKeyboardLayouts << i.data(MKeyboardLayoutRole).toString();
}
settingsObject->setSelectedKeyboards(updatedKeyboardLayouts);
// "No keyboard is selected" notification
if (indexList.isEmpty()) {
notifyNoKeyboards();
}
//update titles
retranslateUi();
}
void MKeyboardSettingsWidget::setErrorCorrectionState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->errorCorrection() != enabled) {
settingsObject->setErrorCorrection(enabled);
if (!enabled) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::syncErrorCorrectionState()
{
if (!settingsObject)
return;
const bool errorCorrectionState = settingsObject->errorCorrection();
if (errorCorrectionSwitch
&& errorCorrectionSwitch->isChecked() != errorCorrectionState) {
errorCorrectionSwitch->setChecked(errorCorrectionState);
if (!errorCorrectionState) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::setCorrectionSpaceState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->correctionSpace() != enabled)
settingsObject->setCorrectionSpace(enabled);
}
void MKeyboardSettingsWidget::syncCorrectionSpaceState()
{
if (!settingsObject)
return;
const bool correctionSpaceState = settingsObject->correctionSpace();
if (correctionSpaceSwitch
&& correctionSpaceSwitch->isChecked() != correctionSpaceState) {
correctionSpaceSwitch->setChecked(correctionSpaceState);
}
}
void MKeyboardSettingsWidget::notifyNoKeyboards()
{
MBanner *noKeyboardsNotification = new MBanner;
// It is needed to set the proper style name to have properly wrapped, multiple lines
// with too much content. The MBanner documentation also emphasises to specify the
// style name for the banners explicitly in the code.
noKeyboardsNotification->setStyleName("InformationBanner");
//% "Note: you have uninstalled all virtual keyboards"
noKeyboardsNotification->setTitle(qtTrId("qtn_txts_no_keyboards_notification"));
noKeyboardsNotification->appear(MSceneWindow::DestroyWhenDone);
}
void MKeyboardSettingsWidget::handleVisibilityChanged()
{
// This is a workaround to hide settings dialog when keyboard is hidden.
// And it could be removed when NB#177922 is fixed.
if (!isVisible() && keyboardDialog) {
// reject settings dialog if the visibility of settings widget
// is changed from shown to hidden.
keyboardDialog->reject();
}
}
<commit_msg>Fixes: Update selected keyboards properly.<commit_after>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation ([email protected])
*
* If you have questions regarding the use of this file, please contact
* Nokia at [email protected].
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettingswidget.h"
#include <MButton>
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MContentItem>
#include <MAbstractCellCreator>
#include <MList>
#include <MDialog>
#include <MBanner>
#include <MBasicListItem>
#include <QObject>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTimer>
#include <QDebug>
namespace
{
//!object name for settings' widgets
const QString ObjectNameSelectedKeyboardsItem("SelectedKeyboardsItem");
const QString ObjectNameErrorCorrectionButton("KeyboardErrorCorrectionButton");
const QString ObjectNameCorrectionSpaceButton("KeyboardCorrectionSpaceButton");
const int MKeyboardLayoutRole = Qt::UserRole + 1;
};
class MKeyboardCellCreator: public MAbstractCellCreator<MContentItem>
{
public:
/*! \reimp */
virtual MWidget *createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const;
virtual void updateCell(const QModelIndex &index, MWidget *cell) const;
/*! \reimp_end */
private:
void updateContentItemMode(const QModelIndex &index, MContentItem *contentItem) const;
};
MWidget *MKeyboardCellCreator::createCell (const QModelIndex &index,
MWidgetRecycler &recycler) const
{
MContentItem *cell = qobject_cast<MContentItem *>(recycler.take("MContentItem"));
if (!cell) {
cell = new MContentItem(MContentItem::SingleTextLabel);
}
updateCell(index, cell);
return cell;
}
void MKeyboardCellCreator::updateCell(const QModelIndex &index, MWidget *cell) const
{
MContentItem *contentItem = qobject_cast<MContentItem *>(cell);
QString layoutTile = index.data(Qt::DisplayRole).toString();
contentItem->setTitle(layoutTile);
}
void MKeyboardCellCreator::updateContentItemMode(const QModelIndex &index,
MContentItem *contentItem) const
{
const int row = index.row();
bool thereIsNextRow = index.sibling(row + 1, 0).isValid();
if (row == 0) {
contentItem->setItemMode(MContentItem::SingleColumnTop);
} else if (thereIsNextRow) {
contentItem->setItemMode(MContentItem::SingleColumnCenter);
} else {
contentItem->setItemMode(MContentItem::SingleColumnBottom);
}
}
MKeyboardSettingsWidget::MKeyboardSettingsWidget(MKeyboardSettings *settings, QGraphicsItem *parent)
: MWidget(parent),
settingsObject(settings),
keyboardDialog(0),
keyboardList(0)
{
MLayout *layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
//To make sure that both columns have the same width, give them the same preferred width.
landscapePolicy->setColumnPreferredWidth(0, 800);
landscapePolicy->setColumnPreferredWidth(1, 800);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
layout->setLandscapePolicy(landscapePolicy);
layout->setPortraitPolicy(portraitPolicy);
buildUi();
syncErrorCorrectionState();
syncCorrectionSpaceState();
retranslateUi();
connectSlots();
}
MKeyboardSettingsWidget::~MKeyboardSettingsWidget()
{
delete keyboardDialog;
keyboardDialog = 0;
}
void MKeyboardSettingsWidget::buildUi()
{
// We are using MBasicListItem instead of MContentItem because
// the latter is not supported by theme
selectedKeyboardsItem = new MBasicListItem(MBasicListItem::TitleWithSubtitle, this);
selectedKeyboardsItem->setObjectName(ObjectNameSelectedKeyboardsItem);
connect(selectedKeyboardsItem, SIGNAL(clicked()), this, SLOT(showKeyboardList()));
selectedKeyboardsItem->setStyleName("CommonBasicListItemInverted");
// Put to first row, first column on the grid
addItem(selectedKeyboardsItem, 0, 0);
// Error correction settings
errorCorrectionSwitch = new MButton(this);
errorCorrectionSwitch->setObjectName(ObjectNameErrorCorrectionButton);
errorCorrectionSwitch->setViewType(MButton::switchType);
errorCorrectionSwitch->setCheckable(true);
errorCorrectionContentItem = new MBasicListItem(MBasicListItem::TitleWithSubtitle, this);
errorCorrectionContentItem->setStyleName("CommonBasicListItemInverted");
//% "Error correction"
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
//% "Error correction description"
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
QGraphicsLinearLayout *eCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
eCLayout->addItem(errorCorrectionContentItem);
eCLayout->addItem(errorCorrectionSwitch);
eCLayout->setAlignment(errorCorrectionSwitch, Qt::AlignCenter);
// Put to first row, second column on the grid
addItem(eCLayout, 0, 1);
// "Space selects the correction candidate" settings
correctionSpaceSwitch = new MButton(this);
correctionSpaceSwitch->setObjectName(ObjectNameCorrectionSpaceButton);
correctionSpaceSwitch->setViewType(MButton::switchType);
correctionSpaceSwitch->setCheckable(true);
correctionSpaceContentItem = new MBasicListItem(MBasicListItem::TitleWithSubtitle, this);
correctionSpaceContentItem->setStyleName("CommonBasicListItemInverted");
//% "Insert with space"
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_insert_with_space"));
//% "Space key inserts the suggested word"
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_insert_with_space_description"));
QGraphicsLinearLayout *wCLayout = new QGraphicsLinearLayout(Qt::Horizontal);
wCLayout->addItem(correctionSpaceContentItem);
wCLayout->addItem(correctionSpaceSwitch);
wCLayout->setAlignment(correctionSpaceSwitch, Qt::AlignCenter);
// Put to second row, second column on the grid
addItem(wCLayout, 1, 1);
}
void MKeyboardSettingsWidget::addItem(QGraphicsLayoutItem *item, int row, int column)
{
landscapePolicy->addItem(item, row, column);
portraitPolicy->addItem(item);
}
void MKeyboardSettingsWidget::retranslateUi()
{
updateTitle();
MWidget::retranslateUi();
}
void MKeyboardSettingsWidget::updateTitle()
{
if (!errorCorrectionContentItem || !correctionSpaceContentItem
|| !settingsObject || !selectedKeyboardsItem)
return;
errorCorrectionContentItem->setTitle(qtTrId("qtn_txts_error_correction"));
errorCorrectionContentItem->setSubtitle(qtTrId("qtn_txts_error_correction_description"));
correctionSpaceContentItem->setTitle(qtTrId("qtn_txts_insert_with_space"));
correctionSpaceContentItem->setSubtitle(qtTrId("qtn_txts_insert_with_space_description"));
QStringList keyboards = settingsObject->selectedKeyboards().values();
//% "Installed keyboards (%1)"
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
selectedKeyboardsItem->setTitle(title);
QString brief;
if (keyboards.count() > 0) {
foreach(const QString &keyboard, keyboards) {
if (!brief.isEmpty())
brief += QString(", ");
brief += keyboard;
}
} else {
//% "No keyboards installed"
brief = qtTrId("qtn_txts_no_keyboards");
}
selectedKeyboardsItem->setSubtitle(brief);
if (keyboardDialog) {
keyboardDialog->setTitle(title);
}
}
void MKeyboardSettingsWidget::connectSlots()
{
connect(this, SIGNAL(visibleChanged()),
this, SLOT(handleVisibilityChanged()));
if (!settingsObject || !errorCorrectionSwitch || !correctionSpaceSwitch)
return;
connect(errorCorrectionSwitch, SIGNAL(toggled(bool)),
this, SLOT(setErrorCorrectionState(bool)));
connect(settingsObject, SIGNAL(errorCorrectionChanged()),
this, SLOT(syncErrorCorrectionState()));
connect(correctionSpaceSwitch, SIGNAL(toggled(bool)),
this, SLOT(setCorrectionSpaceState(bool)));
connect(settingsObject, SIGNAL(correctionSpaceChanged()),
this, SLOT(syncCorrectionSpaceState()));
connect(settingsObject, SIGNAL(selectedKeyboardsChanged()),
this, SLOT(updateKeyboardSelectionModel()));
}
void MKeyboardSettingsWidget::showKeyboardList()
{
if (!settingsObject)
return;
QStringList keyboards = settingsObject->selectedKeyboards().values();
if (!keyboardDialog) {
keyboardDialog = new MDialog();
keyboardList = new MList(keyboardDialog);
MKeyboardCellCreator *cellCreator = new MKeyboardCellCreator;
keyboardList->setCellCreator(cellCreator);
keyboardList->setSelectionMode(MList::MultiSelection);
createKeyboardModel();
keyboardDialog->setCentralWidget(keyboardList);
keyboardDialog->addButton(M::DoneButton);
connect(keyboardList, SIGNAL(itemClicked(const QModelIndex &)),
this, SLOT(updateSelectedKeyboards(const QModelIndex &)));
connect(keyboardDialog, SIGNAL(accepted()),
this, SLOT(selectKeyboards()));
}
updateKeyboardSelectionModel();
// We need to update the title every time because probably the dialog was
// cancelled/closed without tapping on the Done button.
QString keyboardTitle = qtTrId("qtn_txts_installed_keyboards")
.arg(keyboards.count());
keyboardDialog->setTitle(keyboardTitle);
keyboardDialog->exec();
}
void MKeyboardSettingsWidget::createKeyboardModel()
{
if (!settingsObject || !keyboardList)
return;
QMap<QString, QString> availableKeyboards = settingsObject->availableKeyboards();
QStandardItemModel *model = new QStandardItemModel(availableKeyboards.size(), 1, keyboardList);
QMap<QString, QString>::const_iterator i = availableKeyboards.constBegin();
for (int j = 0; i != availableKeyboards.constEnd(); ++i, ++j) {
QStandardItem *item = new QStandardItem(i.value());
item->setData(i.value(), Qt::DisplayRole);
item->setData(i.key(), MKeyboardLayoutRole);
model->setItem(j, item);
}
model->sort(0);
keyboardList->setItemModel(model);
keyboardList->setSelectionModel(new QItemSelectionModel(model, keyboardList));
updateKeyboardSelectionModel();
}
void MKeyboardSettingsWidget::updateKeyboardSelectionModel()
{
if (!settingsObject || !keyboardList)
return;
// First clear current selection
keyboardList->selectionModel()->clearSelection();
// Select all selected keyboards
QStandardItemModel *model = static_cast<QStandardItemModel*> (keyboardList->itemModel());
foreach (const QString &keyboard, settingsObject->selectedKeyboards().values()) {
QList<QStandardItem *> items = model->findItems(keyboard);
foreach (const QStandardItem *item, items) {
keyboardList->selectionModel()->select(item->index(), QItemSelectionModel::Select);
}
}
}
void MKeyboardSettingsWidget::updateSelectedKeyboards(const QModelIndex &index)
{
if (!index.isValid() || !keyboardDialog || !keyboardList
|| !keyboardList->selectionModel())
return;
QModelIndexList indexList = keyboardList->selectionModel()->selectedIndexes();
// Update the dialog title
QString title = qtTrId("qtn_txts_installed_keyboards")
.arg(indexList.size());
keyboardDialog->setTitle(title);
}
void MKeyboardSettingsWidget::selectKeyboards()
{
if (!settingsObject || !keyboardDialog)
return;
QStringList updatedKeyboardLayouts;
QModelIndexList indexList = keyboardList->selectionModel()->selectedIndexes();
foreach (const QModelIndex &i, indexList) {
updatedKeyboardLayouts << i.data(MKeyboardLayoutRole).toString();
}
settingsObject->setSelectedKeyboards(updatedKeyboardLayouts);
// "No keyboard is selected" notification
if (indexList.isEmpty()) {
notifyNoKeyboards();
}
//update titles
retranslateUi();
}
void MKeyboardSettingsWidget::setErrorCorrectionState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->errorCorrection() != enabled) {
settingsObject->setErrorCorrection(enabled);
if (!enabled) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::syncErrorCorrectionState()
{
if (!settingsObject)
return;
const bool errorCorrectionState = settingsObject->errorCorrection();
if (errorCorrectionSwitch
&& errorCorrectionSwitch->isChecked() != errorCorrectionState) {
errorCorrectionSwitch->setChecked(errorCorrectionState);
if (!errorCorrectionState) {
// Disable the "Select with Space" option if the error correction is disabled
setCorrectionSpaceState(false);
correctionSpaceSwitch->setEnabled(false);
} else {
// Enable the "Select with Space" switch again
correctionSpaceSwitch->setEnabled(true);
}
}
}
void MKeyboardSettingsWidget::setCorrectionSpaceState(bool enabled)
{
if (!settingsObject)
return;
if (settingsObject->correctionSpace() != enabled)
settingsObject->setCorrectionSpace(enabled);
}
void MKeyboardSettingsWidget::syncCorrectionSpaceState()
{
if (!settingsObject)
return;
const bool correctionSpaceState = settingsObject->correctionSpace();
if (correctionSpaceSwitch
&& correctionSpaceSwitch->isChecked() != correctionSpaceState) {
correctionSpaceSwitch->setChecked(correctionSpaceState);
}
}
void MKeyboardSettingsWidget::notifyNoKeyboards()
{
MBanner *noKeyboardsNotification = new MBanner;
// It is needed to set the proper style name to have properly wrapped, multiple lines
// with too much content. The MBanner documentation also emphasises to specify the
// style name for the banners explicitly in the code.
noKeyboardsNotification->setStyleName("InformationBanner");
//% "Note: you have uninstalled all virtual keyboards"
noKeyboardsNotification->setTitle(qtTrId("qtn_txts_no_keyboards_notification"));
noKeyboardsNotification->appear(MSceneWindow::DestroyWhenDone);
}
void MKeyboardSettingsWidget::handleVisibilityChanged()
{
// This is a workaround to hide settings dialog when keyboard is hidden.
// And it could be removed when NB#177922 is fixed.
if (!isVisible() && keyboardDialog) {
// reject settings dialog if the visibility of settings widget
// is changed from shown to hidden.
keyboardDialog->reject();
}
}
<|endoftext|> |
<commit_before>/* $Id$
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
/*
* Description : This test will check the mamaPrice type to ensure that the
* setting the precision will not cause the price value to be
* truncated.
*/
/* ************************************************************************* */
/* Includes */
/* ************************************************************************* */
#include "MamaPriceTest.h"
/* ************************************************************************* */
/* Defines */
/* ************************************************************************* */
#ifdef WIN32
#define WMPRICE_LARGE_INT32_FORMAT_SPECIFIER "%I32d"
#define WMPRICE_LARGE_INT64_FORMAT_SPECIFIER "%I64d"
#else
#define WMPRICE_LARGE_INT32_FORMAT_SPECIFIER "%ld"
#define WMPRICE_LARGE_INT64_FORMAT_SPECIFIER "%lld"
#endif
/* ************************************************************************* */
/* Construction and Destruction */
/* ************************************************************************* */
MamaPriceTest::MamaPriceTest(void)
{
}
MamaPriceTest::~MamaPriceTest(void)
{
}
/* ************************************************************************* */
/* Setup and Teardown */
/* ************************************************************************* */
void MamaPriceTest::SetUp(void)
{
// Create a new mama price
//ASSERT_EQ(mamaPrice_create(&m_price), MAMA_STATUS_OK);
m_price = new MamaPrice();
// Set the value of the price
//ASSERT_EQ(mamaPrice_setValue(m_price, 4000000000), MAMA_STATUS_OK);
m_price->setValue(4000000000);
}
void MamaPriceTest::TearDown(void)
{
// Delete the price
if(m_price != NULL)
{
//ASSERT_EQ(mamaPrice_destroy(m_price), MAMA_STATUS_OK);
delete m_price;
}
ASSERT_TRUE(m_price == NULL);
}
/* ************************************************************************* */
/* Test Functions */
/* ************************************************************************* +*/
TEST_F(MamaPriceTest, SetPrecisionInt)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_INT), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_INT);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv2)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_2), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_2);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv4)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_4), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_4);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv8)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_8), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_8);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv16)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_16), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_16);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv32)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_32), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_32);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv64)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_64), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_64);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv128)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_128), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_128);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv256)
{
// Set the precision
ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_256), MAMA_STATUS_OK);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv512)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_512), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_512);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
<commit_msg>UNIT-TEST: Fix for an issue with the price unit tests.<commit_after>/* $Id$
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
/*
* Description : This test will check the mamaPrice type to ensure that the
* setting the precision will not cause the price value to be
* truncated.
*/
/* ************************************************************************* */
/* Includes */
/* ************************************************************************* */
#include "MamaPriceTest.h"
/* ************************************************************************* */
/* Defines */
/* ************************************************************************* */
#ifdef WIN32
#define WMPRICE_LARGE_INT32_FORMAT_SPECIFIER "%I32d"
#define WMPRICE_LARGE_INT64_FORMAT_SPECIFIER "%I64d"
#else
#define WMPRICE_LARGE_INT32_FORMAT_SPECIFIER "%ld"
#define WMPRICE_LARGE_INT64_FORMAT_SPECIFIER "%lld"
#endif
/* ************************************************************************* */
/* Construction and Destruction */
/* ************************************************************************* */
MamaPriceTest::MamaPriceTest(void)
{
}
MamaPriceTest::~MamaPriceTest(void)
{
}
/* ************************************************************************* */
/* Setup and Teardown */
/* ************************************************************************* */
void MamaPriceTest::SetUp(void)
{
// Create a new mama price
//ASSERT_EQ(mamaPrice_create(&m_price), MAMA_STATUS_OK);
m_price = new MamaPrice();
// Set the value of the price
//ASSERT_EQ(mamaPrice_setValue(m_price, 4000000000), MAMA_STATUS_OK);
m_price->setValue(4000000000);
}
void MamaPriceTest::TearDown(void)
{
// Delete the price
if(m_price != NULL)
{
//ASSERT_EQ(mamaPrice_destroy(m_price), MAMA_STATUS_OK);
delete m_price;
}
ASSERT_TRUE(m_price == NULL);
}
/* ************************************************************************* */
/* Test Functions */
/* ************************************************************************* +*/
TEST_F(MamaPriceTest, SetPrecisionInt)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_INT), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_INT);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv2)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_2), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_2);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv4)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_4), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_4);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv8)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_8), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_8);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv16)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_16), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_16);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv32)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_32), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_32);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv64)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_64), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_64);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv128)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_128), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_128);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv256)
{
// Set the precision
// ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_256), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_256);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
TEST_F(MamaPriceTest, SetPrecisionDiv512)
{
// Set the precision
//ASSERT_EQ(mamaPrice_setPrecision(m_price, MAMA_PRICE_PREC_DIV_512), MAMA_STATUS_OK);
m_price->setPrecision(MAMA_PRICE_PREC_DIV_512);
// Get the value as a double
double doubleValue = 0;
//ASSERT_EQ(mamaPrice_getValue(m_price, &doubleValue), MAMA_STATUS_OK);
doubleValue = m_price->getValue();
// Format the double value as a string using an integer flag
char doubleString[20] = "";
sprintf(doubleString, WMPRICE_LARGE_INT64_FORMAT_SPECIFIER, (int64_t)doubleValue);
// Get the value as a string
char stringValue[20] = "";
//ASSERT_EQ(mamaPrice_getAsString(m_price, stringValue, 19), MAMA_STATUS_OK);
m_price->getAsString(stringValue, 19);
// Compare the strings
ASSERT_STREQ(stringValue, doubleString);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: intercept.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBA_INTERCEPT_HXX
#define DBA_INTERCEPT_HXX
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_
#include <com/sun/star/document/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#include "documentdefinition.hxx"
#endif
namespace dbaccess
{
class OInterceptor : public ::cppu::WeakImplHelper4< ::com::sun::star::frame::XDispatchProviderInterceptor,
::com::sun::star::frame::XInterceptorInfo,
::com::sun::star::frame::XDispatch,
::com::sun::star::document::XEventListener>
{
protected:
virtual ~OInterceptor();
public:
OInterceptor( ODocumentDefinition* _pContentHolder,sal_Bool _bAllowEditDoc );
void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);
//XDispatch
virtual void SAL_CALL
dispatch(
const ::com::sun::star::util::URL& URL,
const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue >& Arguments )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
addStatusListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XStatusListener >& Control,
const ::com::sun::star::util::URL& URL )
throw (
::com::sun::star::uno::RuntimeException
);
virtual void SAL_CALL
removeStatusListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XStatusListener >& Control,
const ::com::sun::star::util::URL& URL )
throw (
::com::sun::star::uno::RuntimeException
);
//XInterceptorInfo
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
SAL_CALL getInterceptedURLs( )
throw (
::com::sun::star::uno::RuntimeException
);
//XDispatchProvider ( inherited by XDispatchProviderInterceptor )
virtual ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatch > SAL_CALL
queryDispatch(
const ::com::sun::star::util::URL& URL,
const ::rtl::OUString& TargetFrameName,
sal_Int32 SearchFlags )
throw (
::com::sun::star::uno::RuntimeException
);
virtual ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatch > > SAL_CALL
queryDispatches(
const ::com::sun::star::uno::Sequence<
::com::sun::star::frame::DispatchDescriptor >& Requests )
throw (
::com::sun::star::uno::RuntimeException
);
//XDispatchProviderInterceptor
virtual ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider > SAL_CALL
getSlaveDispatchProvider( )
throw (
::com::sun::star::uno::RuntimeException
);
virtual void SAL_CALL
setSlaveDispatchProvider(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider >& NewDispatchProvider )
throw (
::com::sun::star::uno::RuntimeException
);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider > SAL_CALL
getMasterDispatchProvider( )
throw (
::com::sun::star::uno::RuntimeException
);
virtual void SAL_CALL
setMasterDispatchProvider(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider >& NewSupplier )
throw (
::com::sun::star::uno::RuntimeException
);
// XEventListener
virtual void SAL_CALL notifyEvent( const ::com::sun::star::document::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
private:
osl::Mutex m_aMutex;
ODocumentDefinition* m_pContentHolder;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatchProvider;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatchProvider;
::com::sun::star::uno::Sequence< ::rtl::OUString > m_aInterceptedURL;
cppu::OInterfaceContainerHelper* m_pDisposeEventListeners;
PropertyChangeListenerContainer* m_pStatCL;
sal_Bool m_bAllowEditDoc;
};
//........................................................................
} // namespace dbaccess
//........................................................................
#endif //DBA_INTERCEPT_HXX
<commit_msg>INTEGRATION: CWS dba30d (1.5.30); FILE MERGED 2008/05/29 11:11:03 oj 1.5.30.1: #i89835# dispatch asyncron<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: intercept.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBA_INTERCEPT_HXX
#define DBA_INTERCEPT_HXX
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_
#include <com/sun/star/document/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#include "documentdefinition.hxx"
#endif
#include <vcl/svapp.hxx>
namespace dbaccess
{
class OInterceptor : public ::cppu::WeakImplHelper4< ::com::sun::star::frame::XDispatchProviderInterceptor,
::com::sun::star::frame::XInterceptorInfo,
::com::sun::star::frame::XDispatch,
::com::sun::star::document::XEventListener>
{
DECL_LINK( OnDispatch, void* _aURL );
protected:
virtual ~OInterceptor();
public:
OInterceptor( ODocumentDefinition* _pContentHolder,sal_Bool _bAllowEditDoc );
void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);
//XDispatch
virtual void SAL_CALL
dispatch(
const ::com::sun::star::util::URL& URL,
const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue >& Arguments )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
addStatusListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XStatusListener >& Control,
const ::com::sun::star::util::URL& URL )
throw (
::com::sun::star::uno::RuntimeException
);
virtual void SAL_CALL
removeStatusListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XStatusListener >& Control,
const ::com::sun::star::util::URL& URL )
throw (
::com::sun::star::uno::RuntimeException
);
//XInterceptorInfo
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
SAL_CALL getInterceptedURLs( )
throw (
::com::sun::star::uno::RuntimeException
);
//XDispatchProvider ( inherited by XDispatchProviderInterceptor )
virtual ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatch > SAL_CALL
queryDispatch(
const ::com::sun::star::util::URL& URL,
const ::rtl::OUString& TargetFrameName,
sal_Int32 SearchFlags )
throw (
::com::sun::star::uno::RuntimeException
);
virtual ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatch > > SAL_CALL
queryDispatches(
const ::com::sun::star::uno::Sequence<
::com::sun::star::frame::DispatchDescriptor >& Requests )
throw (
::com::sun::star::uno::RuntimeException
);
//XDispatchProviderInterceptor
virtual ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider > SAL_CALL
getSlaveDispatchProvider( )
throw (
::com::sun::star::uno::RuntimeException
);
virtual void SAL_CALL
setSlaveDispatchProvider(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider >& NewDispatchProvider )
throw (
::com::sun::star::uno::RuntimeException
);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider > SAL_CALL
getMasterDispatchProvider( )
throw (
::com::sun::star::uno::RuntimeException
);
virtual void SAL_CALL
setMasterDispatchProvider(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XDispatchProvider >& NewSupplier )
throw (
::com::sun::star::uno::RuntimeException
);
// XEventListener
virtual void SAL_CALL notifyEvent( const ::com::sun::star::document::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
private:
osl::Mutex m_aMutex;
ODocumentDefinition* m_pContentHolder;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatchProvider;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatchProvider;
::com::sun::star::uno::Sequence< ::rtl::OUString > m_aInterceptedURL;
cppu::OInterfaceContainerHelper* m_pDisposeEventListeners;
PropertyChangeListenerContainer* m_pStatCL;
sal_Bool m_bAllowEditDoc;
};
//........................................................................
} // namespace dbaccess
//........................................................................
#endif //DBA_INTERCEPT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: RelationDesignView.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBAUI_RELATIONDESIGNVIEW_HXX
#define DBAUI_RELATIONDESIGNVIEW_HXX
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef DBAUI_RELATION_TABLEVIEW_HXX
#include "RelationTableView.hxx"
#endif
namespace dbaui
{
class OAddTableDlg;
class OTableConnection;
class ORelationTableConnectionData;
class OConnectionLineData;
class ORelationController;
class ORelationDesignView : public OJoinDesignView
{
public:
ORelationDesignView(Window* pParent, ORelationController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
virtual ~ORelationDesignView();
// set the statement for representation
/// late construction
virtual void Construct();
virtual void initialize();
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void GetFocus();
};
}
#endif // DBAUI_RELATIONDESIGNVIEW_HXX
<commit_msg>INTEGRATION: CWS dba30d (1.6.30); FILE MERGED 2008/05/29 11:25:58 fs 1.6.30.1: during #i80943#: refactoring: IController now passed around as reference, not as pointer<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: RelationDesignView.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBAUI_RELATIONDESIGNVIEW_HXX
#define DBAUI_RELATIONDESIGNVIEW_HXX
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef DBAUI_RELATION_TABLEVIEW_HXX
#include "RelationTableView.hxx"
#endif
namespace dbaui
{
class OAddTableDlg;
class OTableConnection;
class ORelationTableConnectionData;
class OConnectionLineData;
class ORelationController;
class ORelationDesignView : public OJoinDesignView
{
public:
ORelationDesignView(Window* pParent, ORelationController& _rController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
virtual ~ORelationDesignView();
// set the statement for representation
/// late construction
virtual void Construct();
virtual void initialize();
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void GetFocus();
};
}
#endif // DBAUI_RELATIONDESIGNVIEW_HXX
<|endoftext|> |
<commit_before>/*=========================================================================
*
* 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 itkPyBuffer_hxx
#define itkPyBuffer_hxx
#include "itkPyBuffer.h"
#include "itkImportImageContainer.h"
namespace itk
{
template <class TImage>
PyObject *
PyBuffer<TImage>::_GetArrayViewFromImage(ImageType * image)
{
PyObject * memoryView = NULL;
Py_buffer pyBuffer;
memset(&pyBuffer, 0, sizeof(Py_buffer));
Py_ssize_t len = 1;
size_t pixelSize = sizeof(ComponentType);
int res = 0;
if (!image)
{
throw std::runtime_error("Input image is null");
}
image->Update();
ComponentType * buffer =
const_cast<ComponentType *>(reinterpret_cast<const ComponentType *>(image->GetBufferPointer()));
void * itkImageBuffer = (void *)(buffer);
// Computing the length of data
const int numberOfComponents = image->GetNumberOfComponentsPerPixel();
SizeType size = image->GetBufferedRegion().GetSize();
for (unsigned int dim = 0; dim < ImageDimension; ++dim)
{
len *= size[dim];
}
len *= numberOfComponents;
len *= pixelSize;
res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)itkImageBuffer, len, 0, PyBUF_CONTIG);
memoryView = PyMemoryView_FromBuffer(&pyBuffer);
PyBuffer_Release(&pyBuffer);
return memoryView;
}
template <class TImage>
const typename PyBuffer<TImage>::OutputImagePointer
PyBuffer<TImage>::_GetImageViewFromArray(PyObject * arr, PyObject * shape, PyObject * numOfComponent)
{
PyObject * shapeseq = NULL;
PyObject * item = NULL;
Py_ssize_t bufferLength;
Py_buffer pyBuffer;
memset(&pyBuffer, 0, sizeof(Py_buffer));
SizeType size;
SizeType sizeFortran;
SizeValueType numberOfPixels = 1;
const void * buffer;
long numberOfComponents = 1;
unsigned int dimension = 0;
size_t pixelSize = sizeof(ComponentType);
size_t len = 1;
if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_ND | PyBUF_ANY_CONTIGUOUS) == -1)
{
PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array.");
PyBuffer_Release(&pyBuffer);
return nullptr;
}
else
{
bufferLength = pyBuffer.len;
buffer = pyBuffer.buf;
}
PyBuffer_Release(&pyBuffer);
shapeseq = PySequence_Fast(shape, "expected sequence");
dimension = PySequence_Size(shape);
numberOfComponents = PyInt_AsLong(numOfComponent);
for (unsigned int i = 0; i < dimension; ++i)
{
item = PySequence_Fast_GET_ITEM(shapeseq, i);
size[i] = (SizeValueType)PyInt_AsLong(item);
sizeFortran[dimension - 1 - i] = (SizeValueType)PyInt_AsLong(item);
numberOfPixels *= size[i];
}
bool isFortranContiguous = false;
if (pyBuffer.strides != NULL && pyBuffer.itemsize == pyBuffer.strides[0])
{
isFortranContiguous = true;
}
len = numberOfPixels * numberOfComponents * pixelSize;
if (bufferLength != len)
{
PyErr_SetString(PyExc_RuntimeError, "Size mismatch of image and Buffer.");
PyBuffer_Release(&pyBuffer);
Py_DECREF(shapeseq);
return nullptr;
}
IndexType start;
start.Fill(0);
RegionType region;
region.SetIndex(start);
region.SetSize(size);
if (isFortranContiguous)
{
region.SetSize(sizeFortran);
}
else
{
region.SetSize(size);
}
PointType origin;
origin.Fill(0.0);
SpacingType spacing;
spacing.Fill(1.0);
using InternalPixelType = typename TImage::InternalPixelType;
using ImporterType = ImportImageContainer<SizeValueType, InternalPixelType>;
typename ImporterType::Pointer importer = ImporterType::New();
const bool importImageFilterWillOwnTheBuffer = false;
InternalPixelType * data = (InternalPixelType *)buffer;
importer->SetImportPointer(data, numberOfPixels, importImageFilterWillOwnTheBuffer);
OutputImagePointer output = TImage::New();
output->SetRegions(region);
output->SetOrigin(origin);
output->SetSpacing(spacing);
output->SetPixelContainer(importer);
output->SetNumberOfComponentsPerPixel(numberOfComponents);
Py_DECREF(shapeseq);
PyBuffer_Release(&pyBuffer);
return output;
}
} // namespace itk
#endif
<commit_msg>PERF: PyBuffer importImageFilterWillOwnTheBuffer is constexpr<commit_after>/*=========================================================================
*
* 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 itkPyBuffer_hxx
#define itkPyBuffer_hxx
#include "itkPyBuffer.h"
#include "itkImportImageContainer.h"
namespace itk
{
template <class TImage>
PyObject *
PyBuffer<TImage>::_GetArrayViewFromImage(ImageType * image)
{
PyObject * memoryView = NULL;
Py_buffer pyBuffer;
memset(&pyBuffer, 0, sizeof(Py_buffer));
Py_ssize_t len = 1;
size_t pixelSize = sizeof(ComponentType);
int res = 0;
if (!image)
{
throw std::runtime_error("Input image is null");
}
image->Update();
ComponentType * buffer =
const_cast<ComponentType *>(reinterpret_cast<const ComponentType *>(image->GetBufferPointer()));
void * itkImageBuffer = (void *)(buffer);
// Computing the length of data
const int numberOfComponents = image->GetNumberOfComponentsPerPixel();
SizeType size = image->GetBufferedRegion().GetSize();
for (unsigned int dim = 0; dim < ImageDimension; ++dim)
{
len *= size[dim];
}
len *= numberOfComponents;
len *= pixelSize;
res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)itkImageBuffer, len, 0, PyBUF_CONTIG);
memoryView = PyMemoryView_FromBuffer(&pyBuffer);
PyBuffer_Release(&pyBuffer);
return memoryView;
}
template <class TImage>
const typename PyBuffer<TImage>::OutputImagePointer
PyBuffer<TImage>::_GetImageViewFromArray(PyObject * arr, PyObject * shape, PyObject * numOfComponent)
{
PyObject * shapeseq = NULL;
PyObject * item = NULL;
Py_ssize_t bufferLength;
Py_buffer pyBuffer;
memset(&pyBuffer, 0, sizeof(Py_buffer));
SizeType size;
SizeType sizeFortran;
SizeValueType numberOfPixels = 1;
const void * buffer;
long numberOfComponents = 1;
unsigned int dimension = 0;
size_t pixelSize = sizeof(ComponentType);
size_t len = 1;
if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_ND | PyBUF_ANY_CONTIGUOUS) == -1)
{
PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array.");
PyBuffer_Release(&pyBuffer);
return nullptr;
}
else
{
bufferLength = pyBuffer.len;
buffer = pyBuffer.buf;
}
PyBuffer_Release(&pyBuffer);
shapeseq = PySequence_Fast(shape, "expected sequence");
dimension = PySequence_Size(shape);
numberOfComponents = PyInt_AsLong(numOfComponent);
for (unsigned int i = 0; i < dimension; ++i)
{
item = PySequence_Fast_GET_ITEM(shapeseq, i);
size[i] = (SizeValueType)PyInt_AsLong(item);
sizeFortran[dimension - 1 - i] = (SizeValueType)PyInt_AsLong(item);
numberOfPixels *= size[i];
}
bool isFortranContiguous = false;
if (pyBuffer.strides != NULL && pyBuffer.itemsize == pyBuffer.strides[0])
{
isFortranContiguous = true;
}
len = numberOfPixels * numberOfComponents * pixelSize;
if (bufferLength != len)
{
PyErr_SetString(PyExc_RuntimeError, "Size mismatch of image and Buffer.");
PyBuffer_Release(&pyBuffer);
Py_DECREF(shapeseq);
return nullptr;
}
IndexType start;
start.Fill(0);
RegionType region;
region.SetIndex(start);
region.SetSize(size);
if (isFortranContiguous)
{
region.SetSize(sizeFortran);
}
else
{
region.SetSize(size);
}
PointType origin;
origin.Fill(0.0);
SpacingType spacing;
spacing.Fill(1.0);
using InternalPixelType = typename TImage::InternalPixelType;
using ImporterType = ImportImageContainer<SizeValueType, InternalPixelType>;
typename ImporterType::Pointer importer = ImporterType::New();
constexpr bool importImageFilterWillOwnTheBuffer = false;
InternalPixelType * data = (InternalPixelType *)buffer;
importer->SetImportPointer(data, numberOfPixels, importImageFilterWillOwnTheBuffer);
OutputImagePointer output = TImage::New();
output->SetRegions(region);
output->SetOrigin(origin);
output->SetSpacing(spacing);
output->SetPixelContainer(importer);
output->SetNumberOfComponentsPerPixel(numberOfComponents);
Py_DECREF(shapeseq);
PyBuffer_Release(&pyBuffer);
return output;
}
} // namespace itk
#endif
<|endoftext|> |
<commit_before>/*
* This is the cpp file for the StringFunctions class of cPlusPlusPlusLib
* cPPPLib - A library of functions that should be in the C++ Standard Library
* (C) - Charles Machalow - MIT License
*/
#ifndef StringFunctions_CPP
#define StringFunctions_CPP
#include "StringFunctions.h"
/// <summary>
/// Splits the original_str into a std::vector by delimiter
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="delim">The delimiter.</param>
/// <returns>std::vector<string> where each item is a string that has been delimited</returns>
std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::string &delim)
{
std::string working_str = original_str;
std::vector<std::string> ret_vec;
while (!working_str.empty())
{
unsigned int loc = working_str.find(delim);
// found in string
if (loc != std::string::npos)
{
ret_vec.push_back(working_str.substr(0, loc));
working_str = working_str.substr(loc + 1);
}
else
{
ret_vec.push_back(working_str);
break;
}
}
return ret_vec;
}
/// <summary>
/// Splits the original string into a vector using all delims
/// </summary>
/// <param name="original_str">The original std::string to split.</param>
/// <param name="delims">std::vector<std::string> of delimiters.</param>
/// <returns>std::vector<std::string> of the original_str split by all delims</returns>
std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::vector<std::string> &delims)
{
std::vector<std::string> working_delims = delims;
std::vector<std::string> ret_vec;
if (working_delims.empty())
{
return ret_vec;
}
ret_vec = StringFunctions::splitIntoVector(original_str, working_delims.front());
working_delims.erase(working_delims.begin());
while (!working_delims.empty())
{
std::vector<std::string> tmp_vec;
for (const std::string cur : ret_vec)
{
std::vector<std::string> inner_vec = StringFunctions::splitIntoVector(cur, working_delims.front());
for (const std::string cur_in : inner_vec)
{
tmp_vec.push_back(cur_in);
}
}
working_delims.erase(working_delims.begin());
ret_vec = tmp_vec;
}
return ret_vec;
}
/// <summary>
/// Splits the original_str into a std::vector by whitespace.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>std::vector<string> where each item is a string that has been delimited by whitespace</returns>
std::vector<std::string> StringFunctions::splitIntoVectorByWhitespace(const std::string &original_str)
{
std::string working_str = original_str;
std::vector<std::string> ret_vec;
while (!working_str.empty())
{
unsigned int loc = working_str.find(" ");
// found in string
if (loc != std::string::npos)
{
if (working_str.substr(0, loc) != "")
{
ret_vec.push_back(working_str.substr(0, loc));
}
working_str = working_str.substr(loc + 1);
}
else
{
if (working_str != "")
{
ret_vec.push_back(working_str);
}
break;
}
}
return ret_vec;
}
/// <summary>
/// Returns a copy of the given string in Title Case
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>Copy of original_str in Title Case</returns>
std::string StringFunctions::toTitleCase(const std::string &original_str)
{
char last_char = ' ';
std::string ret_str = "";
for (char c : original_str)
{
if (last_char == ' ')
{
ret_str += toupper(c);
}
else
{
ret_str += c;
}
last_char = c;
}
return ret_str;
}
/// <summary>
/// Returns a copy of the given string in UPPERCASE
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>Copy of original_str in UPPERCASE</returns>
std::string StringFunctions::toUpperCase(const std::string &original_str)
{
std::string ret_str = "";
for (char c : original_str)
{
ret_str += toupper(c);
}
return ret_str;
}
/// <summary>
/// Returns a copy of the given string in lowercase
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>Copy of original_str in lowercase</returns>
std::string StringFunctions::toLowerCase(const std::string &original_str)
{
std::string ret_str = "";
for (char c : original_str)
{
ret_str += tolower(c);
}
return ret_str;
}
/// <summary>
/// Returns a string where all cases are flipped from original_str
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>original_str with flipped case</returns>
std::string StringFunctions::swapCase(const std::string &original_str)
{
std::string ret_str = "";
for (char c : original_str)
{
if (islower(c))
{
ret_str += toupper(c);
}
else
{
ret_str += tolower(c);
}
}
return ret_str;
}
/// <summary>
/// Slices the specified original_str between x and y using a python-style slice
/// </summary>
/// <param name="original_str">The original_str.</param>
/// <param name="slice_str">slicing info as string ex: "[1:3]"</param>
/// <returns>std::string slice from original_str. Returns "" on error</returns>
std::string StringFunctions::slice(const std::string &original_str, const std::string &slice_str)
{
if (slice_str.size() < 3)
{
std::cerr << "ERROR: Improper slice string " << slice_str << ". Good Examples: \"[1]\", \"[1:2]\", \"[-1, 5]\", \"[:]\"" << std::endl;
return "";
}
if (slice_str.front() != '[' || slice_str.back() != ']')
{
std::cerr << "ERROR: Improper slice string " << slice_str << ". Should start with \"[\" and end with \"]\"" << std::endl;
return "";
}
if (slice_str == "[:]")
{
return std::string(original_str);
}
std::string working_slice = slice_str;
//remove []s
working_slice.erase(0, 1);
working_slice.erase(working_slice.size() - 1, 1);
// look for colon
int colon_loc = working_slice.find(":");
// colon not found, try to cast to int
// example [1]
if (colon_loc == std::string::npos)
{
int ret_index = std::stoi(working_slice);
if ((unsigned int)abs(ret_index) > original_str.size())
{
std::cerr << "ERROR: Index " << ret_index << " is out of range" << std::endl;
return "";
}
else if (ret_index < 0)
{
ret_index = original_str.size() - abs(ret_index);
}
return original_str.substr(ret_index, 1);
}
else
{
int l_index = 0;
int r_index = 0;
try
{
l_index = std::stoi(working_slice.substr(0, colon_loc));
}
catch (const std::invalid_argument &ia)
{
ia.what();
//something wrong with l_index
//it might be empty
if (StringFunctions::isOnlyWhitespace(working_slice.substr(0, colon_loc)))
{
l_index = 0;
}
}
try
{
r_index = std::stoi(working_slice.substr(colon_loc + 1));
}
catch (const std::invalid_argument &ia)
{
ia.what();
//something wrong with r_index
//it might be empty
if (StringFunctions::isOnlyWhitespace(working_slice.substr(colon_loc + 1)))
{
r_index = original_str.size();
}
}
if (l_index < 0)
{
l_index = std::max((int)original_str.size() - abs(l_index), (int)0);
}
if (r_index < 0)
{
r_index = original_str.size() - abs(r_index);
}
if (l_index == r_index || l_index >= r_index || (unsigned int) l_index > original_str.size())
{
return "";
}
return original_str.substr(l_index, (r_index - l_index));
}
}
/// <summary>
/// Performs a left and right trim on the specified original_str.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="removal_chars">Chars to be trimmed (Defaults to all whitespace)</param>
/// <returns>A copy of the original std::string without leading and trailing whitespace</returns>
std::string StringFunctions::trim(const std::string & original_str, const std::string &removal_chars)
{
std::string working_str = original_str;
int rtrim_loc = working_str.find_last_not_of(removal_chars) + 1;
int ltrim_loc = working_str.find_first_not_of(removal_chars);
if (ltrim_loc == std::string::npos)
{
return "";
}
else
{
return working_str.erase(rtrim_loc).substr(ltrim_loc);
}
}
/// <summary>
/// Performs a left trim on the specified original_str.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="removal_chars">Chars to be trimmed (Defaults to all whitespace)</param>
/// <returns>A copy of the original std::string without leading whitespace</returns>
std::string StringFunctions::ltrim(const std::string & original_str, const std::string &removal_chars)
{
std::string working_str = original_str;
int ltrim_loc = working_str.find_first_not_of(removal_chars);
if (ltrim_loc == std::string::npos)
{
return "";
}
else
{
return working_str.substr(ltrim_loc);
}
}
/// <summary>
/// Performs a right trim on the specified original_str.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="removal_chars">Chars to be trimmed (Defaults to all whitespace)</param>
/// <returns>A copy of the original std::string without trailing whitespace</returns>
std::string StringFunctions::rtrim(const std::string & original_str, const std::string &removal_chars)
{
std::string working_str = original_str;
int rtrim_loc = working_str.find_last_not_of(removal_chars) + 1;
return working_str.erase(rtrim_loc);
}
/// <summary>
/// Determines if a given std::string only contains whitespace or is empty
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>True if the original_str only contains whitespace</returns>
bool StringFunctions::isOnlyWhitespace(const std::string &original_str)
{
return original_str.find_first_not_of("\t\n\v\f\r ") == std::string::npos;
}
#endif StringFunctions_CPP<commit_msg>Go through vectors by reference in for each.<commit_after>/*
* This is the cpp file for the StringFunctions class of cPlusPlusPlusLib
* cPPPLib - A library of functions that should be in the C++ Standard Library
* (C) - Charles Machalow - MIT License
*/
#ifndef StringFunctions_CPP
#define StringFunctions_CPP
#include "StringFunctions.h"
/// <summary>
/// Splits the original_str into a std::vector by delimiter
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="delim">The delimiter.</param>
/// <returns>std::vector<string> where each item is a string that has been delimited</returns>
std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::string &delim)
{
std::string working_str = original_str;
std::vector<std::string> ret_vec;
while (!working_str.empty())
{
unsigned int loc = working_str.find(delim);
// found in string
if (loc != std::string::npos)
{
ret_vec.push_back(working_str.substr(0, loc));
working_str = working_str.substr(loc + 1);
}
else
{
ret_vec.push_back(working_str);
break;
}
}
return ret_vec;
}
/// <summary>
/// Splits the original string into a vector using all delims
/// </summary>
/// <param name="original_str">The original std::string to split.</param>
/// <param name="delims">std::vector<std::string> of delimiters.</param>
/// <returns>std::vector<std::string> of the original_str split by all delims</returns>
std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::vector<std::string> &delims)
{
std::vector<std::string> working_delims = delims;
std::vector<std::string> ret_vec;
if (working_delims.empty())
{
return ret_vec;
}
ret_vec = StringFunctions::splitIntoVector(original_str, working_delims.front());
working_delims.erase(working_delims.begin());
while (!working_delims.empty())
{
std::vector<std::string> tmp_vec;
for (const std::string &cur : ret_vec)
{
std::vector<std::string> inner_vec = StringFunctions::splitIntoVector(cur, working_delims.front());
for (const std::string &cur_in : inner_vec)
{
tmp_vec.push_back(cur_in);
}
}
working_delims.erase(working_delims.begin());
ret_vec = tmp_vec;
}
return ret_vec;
}
/// <summary>
/// Splits the original_str into a std::vector by whitespace.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>std::vector<string> where each item is a string that has been delimited by whitespace</returns>
std::vector<std::string> StringFunctions::splitIntoVectorByWhitespace(const std::string &original_str)
{
std::string working_str = original_str;
std::vector<std::string> ret_vec;
while (!working_str.empty())
{
unsigned int loc = working_str.find(" ");
// found in string
if (loc != std::string::npos)
{
if (working_str.substr(0, loc) != "")
{
ret_vec.push_back(working_str.substr(0, loc));
}
working_str = working_str.substr(loc + 1);
}
else
{
if (working_str != "")
{
ret_vec.push_back(working_str);
}
break;
}
}
return ret_vec;
}
/// <summary>
/// Returns a copy of the given string in Title Case
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>Copy of original_str in Title Case</returns>
std::string StringFunctions::toTitleCase(const std::string &original_str)
{
char last_char = ' ';
std::string ret_str = "";
for (char c : original_str)
{
if (last_char == ' ')
{
ret_str += toupper(c);
}
else
{
ret_str += c;
}
last_char = c;
}
return ret_str;
}
/// <summary>
/// Returns a copy of the given string in UPPERCASE
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>Copy of original_str in UPPERCASE</returns>
std::string StringFunctions::toUpperCase(const std::string &original_str)
{
std::string ret_str = "";
for (char c : original_str)
{
ret_str += toupper(c);
}
return ret_str;
}
/// <summary>
/// Returns a copy of the given string in lowercase
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>Copy of original_str in lowercase</returns>
std::string StringFunctions::toLowerCase(const std::string &original_str)
{
std::string ret_str = "";
for (char c : original_str)
{
ret_str += tolower(c);
}
return ret_str;
}
/// <summary>
/// Returns a string where all cases are flipped from original_str
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>original_str with flipped case</returns>
std::string StringFunctions::swapCase(const std::string &original_str)
{
std::string ret_str = "";
for (char c : original_str)
{
if (islower(c))
{
ret_str += toupper(c);
}
else
{
ret_str += tolower(c);
}
}
return ret_str;
}
/// <summary>
/// Slices the specified original_str between x and y using a python-style slice
/// </summary>
/// <param name="original_str">The original_str.</param>
/// <param name="slice_str">slicing info as string ex: "[1:3]"</param>
/// <returns>std::string slice from original_str. Returns "" on error</returns>
std::string StringFunctions::slice(const std::string &original_str, const std::string &slice_str)
{
if (slice_str.size() < 3)
{
std::cerr << "ERROR: Improper slice string " << slice_str << ". Good Examples: \"[1]\", \"[1:2]\", \"[-1, 5]\", \"[:]\"" << std::endl;
return "";
}
if (slice_str.front() != '[' || slice_str.back() != ']')
{
std::cerr << "ERROR: Improper slice string " << slice_str << ". Should start with \"[\" and end with \"]\"" << std::endl;
return "";
}
if (slice_str == "[:]")
{
return std::string(original_str);
}
std::string working_slice = slice_str;
//remove []s
working_slice.erase(0, 1);
working_slice.erase(working_slice.size() - 1, 1);
// look for colon
int colon_loc = working_slice.find(":");
// colon not found, try to cast to int
// example [1]
if (colon_loc == std::string::npos)
{
int ret_index = std::stoi(working_slice);
if ((unsigned int)abs(ret_index) > original_str.size())
{
std::cerr << "ERROR: Index " << ret_index << " is out of range" << std::endl;
return "";
}
else if (ret_index < 0)
{
ret_index = original_str.size() - abs(ret_index);
}
return original_str.substr(ret_index, 1);
}
else
{
int l_index = 0;
int r_index = 0;
try
{
l_index = std::stoi(working_slice.substr(0, colon_loc));
}
catch (const std::invalid_argument &ia)
{
ia.what();
//something wrong with l_index
//it might be empty
if (StringFunctions::isOnlyWhitespace(working_slice.substr(0, colon_loc)))
{
l_index = 0;
}
}
try
{
r_index = std::stoi(working_slice.substr(colon_loc + 1));
}
catch (const std::invalid_argument &ia)
{
ia.what();
//something wrong with r_index
//it might be empty
if (StringFunctions::isOnlyWhitespace(working_slice.substr(colon_loc + 1)))
{
r_index = original_str.size();
}
}
if (l_index < 0)
{
l_index = std::max((int)original_str.size() - abs(l_index), (int)0);
}
if (r_index < 0)
{
r_index = original_str.size() - abs(r_index);
}
if (l_index == r_index || l_index >= r_index || (unsigned int) l_index > original_str.size())
{
return "";
}
return original_str.substr(l_index, (r_index - l_index));
}
}
/// <summary>
/// Performs a left and right trim on the specified original_str.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="removal_chars">Chars to be trimmed (Defaults to all whitespace)</param>
/// <returns>A copy of the original std::string without leading and trailing whitespace</returns>
std::string StringFunctions::trim(const std::string & original_str, const std::string &removal_chars)
{
std::string working_str = original_str;
int rtrim_loc = working_str.find_last_not_of(removal_chars) + 1;
int ltrim_loc = working_str.find_first_not_of(removal_chars);
if (ltrim_loc == std::string::npos)
{
return "";
}
else
{
return working_str.erase(rtrim_loc).substr(ltrim_loc);
}
}
/// <summary>
/// Performs a left trim on the specified original_str.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="removal_chars">Chars to be trimmed (Defaults to all whitespace)</param>
/// <returns>A copy of the original std::string without leading whitespace</returns>
std::string StringFunctions::ltrim(const std::string & original_str, const std::string &removal_chars)
{
std::string working_str = original_str;
int ltrim_loc = working_str.find_first_not_of(removal_chars);
if (ltrim_loc == std::string::npos)
{
return "";
}
else
{
return working_str.substr(ltrim_loc);
}
}
/// <summary>
/// Performs a right trim on the specified original_str.
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <param name="removal_chars">Chars to be trimmed (Defaults to all whitespace)</param>
/// <returns>A copy of the original std::string without trailing whitespace</returns>
std::string StringFunctions::rtrim(const std::string & original_str, const std::string &removal_chars)
{
std::string working_str = original_str;
int rtrim_loc = working_str.find_last_not_of(removal_chars) + 1;
return working_str.erase(rtrim_loc);
}
/// <summary>
/// Determines if a given std::string only contains whitespace or is empty
/// </summary>
/// <param name="original_str">The original std::string</param>
/// <returns>True if the original_str only contains whitespace</returns>
bool StringFunctions::isOnlyWhitespace(const std::string &original_str)
{
return original_str.find_first_not_of("\t\n\v\f\r ") == std::string::npos;
}
#endif StringFunctions_CPP<|endoftext|> |
<commit_before><commit_msg>Added test for mitkLabel<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkLabel.h"
#include "mitkStringProperty.h"
#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
class mitkLabelTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkLabelTestSuite);
MITK_TEST(TestSetLock);
MITK_TEST(TestSetVisibility);
MITK_TEST(TestSetOpacity);
MITK_TEST(TestSetName);
MITK_TEST(TestSetCenterOfMassIndex);
MITK_TEST(TestSetCenterOfMassCoordinates);
MITK_TEST(TestSetColor);
MITK_TEST(TestSetValue);
MITK_TEST(TestSetLayer);
MITK_TEST(TestSetProperty);
CPPUNIT_TEST_SUITE_END();
public:
void TestSetLock()
{
mitk::Label::Pointer label = mitk::Label::New();
CPPUNIT_ASSERT_MESSAGE("Initial label not locked", label->GetLocked() == true);
label->SetLocked(false);
CPPUNIT_ASSERT_MESSAGE("Label should not be locked", label->GetLocked() == false);
}
void TestSetVisibility()
{
mitk::Label::Pointer label = mitk::Label::New();
CPPUNIT_ASSERT_MESSAGE("Initial label not visible", label->GetVisible() == true);
label->SetVisible(false);
CPPUNIT_ASSERT_MESSAGE("Label should not be visible", label->GetVisible() == false);
}
void TestSetOpacity()
{
mitk::Label::Pointer label = mitk::Label::New();
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong opacity", mitk::Equal(label->GetOpacity(), 0.6f));
label->SetOpacity(0.32f);
CPPUNIT_ASSERT_MESSAGE("Label has wrong opacity", mitk::Equal(label->GetOpacity(), 0.32f));
}
void TestSetName()
{
mitk::Label::Pointer label = mitk::Label::New();
std::string initialName("noName!");
std::string labelName = label->GetName();
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong name", initialName.compare(labelName) == 0);
label->SetName("AwesomeLabel");
labelName = label->GetName();
CPPUNIT_ASSERT_MESSAGE("Label has wrong name", labelName.compare("AwesomeLabel") == 0);
}
void TestSetCenterOfMassIndex()
{
mitk::Label::Pointer label = mitk::Label::New();
mitk::Point3D currentIndex = label->GetCenterOfMassIndex();
mitk::Point3D indexToBeCompared;
indexToBeCompared.Fill(0);
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong center of mass index", mitk::Equal(currentIndex, indexToBeCompared));
indexToBeCompared.SetElement(1, 234.3f);
indexToBeCompared.SetElement(2, -53);
indexToBeCompared.SetElement(3, 120);
label->SetCenterOfMassIndex(indexToBeCompared);
currentIndex = label->GetCenterOfMassIndex();
CPPUNIT_ASSERT_MESSAGE("Label has wrong center of mass index", mitk::Equal(currentIndex, indexToBeCompared));
}
void TestSetCenterOfMassCoordinates()
{
mitk::Label::Pointer label = mitk::Label::New();
mitk::Point3D currentPoint = label->GetCenterOfMassCoordinates();
mitk::Point3D pointToBeCompared;
pointToBeCompared.Fill(0);
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong center of mass index", mitk::Equal(currentPoint, pointToBeCompared));
pointToBeCompared.SetElement(1, 234.3f);
pointToBeCompared.SetElement(2, -53);
pointToBeCompared.SetElement(3, 120);
label->SetCenterOfMassCoordinates(pointToBeCompared);
currentPoint = label->GetCenterOfMassCoordinates();
CPPUNIT_ASSERT_MESSAGE("Label has wrong center of mass index", mitk::Equal(currentPoint, pointToBeCompared));
}
void TestSetColor()
{
mitk::Label::Pointer label = mitk::Label::New();
mitk::Color currentColor = label->GetColor();
mitk::Color colorToBeCompared;
colorToBeCompared.Set(0,0,0);
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong color", currentColor.GetBlue() == colorToBeCompared.GetBlue());
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong color", currentColor.GetGreen() == colorToBeCompared.GetGreen());
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong color", currentColor.GetRed() == colorToBeCompared.GetRed());
colorToBeCompared.Set(0.4f,0.3f,1.0f);
label->SetColor(colorToBeCompared);
currentColor = label->GetColor();
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong color", currentColor.GetBlue() == colorToBeCompared.GetBlue());
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong color", currentColor.GetGreen() == colorToBeCompared.GetGreen());
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong color", currentColor.GetRed() == colorToBeCompared.GetRed());
}
void TestSetValue()
{
mitk::Label::Pointer label = mitk::Label::New();
int initialValue(-1);
int valueToBeCompared = label->GetValue();
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong value", initialValue == valueToBeCompared);
label->SetValue(12345);
valueToBeCompared = 12345;
initialValue = label->GetValue();
CPPUNIT_ASSERT_MESSAGE("Label has wrong value", initialValue == valueToBeCompared);
}
void TestSetLayer()
{
mitk::Label::Pointer label = mitk::Label::New();
int initialLayer(-1);
int valueToBeCompared = label->GetValue();
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong value", initialLayer == valueToBeCompared);
label->SetLayer(2);
valueToBeCompared = 2;
initialLayer = label->GetLayer();
CPPUNIT_ASSERT_MESSAGE("Label has wrong value", initialLayer == valueToBeCompared);
}
void TestSetProperty()
{
mitk::Label::Pointer label = mitk::Label::New();
mitk::StringProperty::Pointer prop = mitk::StringProperty::New("abc");
label->SetProperty("cba",prop);
std::string propVal("");
label->GetStringProperty("cba", propVal);
CPPUNIT_ASSERT_MESSAGE("Initial label has wrong value", propVal.compare("abc") == 0);
}
};
MITK_TEST_SUITE_REGISTRATION(mitkLabel)
<|endoftext|> |
<commit_before>/*
* lineedit.cpp - Line edit widget with extra drag and drop options
* Program: kalarm
* Copyright (c) 2003 - 2005 by David Jarvie <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <QRegExp>
#include <QMimeData>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFocusEvent>
#include <k3urldrag.h>
#include <kurlcompletion.h>
#include <libkdepim/maillistdrag.h>
#include <libkdepim/kvcarddrag.h>
#include <libkcal/icaldrag.h>
#include "lineedit.moc"
/*=============================================================================
= Class LineEdit
= Line edit which accepts drag and drop of text, URLs and/or email addresses.
* It has an option to prevent its contents being selected when it receives
= focus.
=============================================================================*/
LineEdit::LineEdit(Type type, QWidget* parent)
: KLineEdit(parent),
mType(type),
mNoSelect(false),
mSetCursorAtEnd(false)
{
init();
}
LineEdit::LineEdit(QWidget* parent)
: KLineEdit(parent),
mType(Text),
mNoSelect(false),
mSetCursorAtEnd(false)
{
init();
}
void LineEdit::init()
{
if (mType == Url)
{
setCompletionMode(KGlobalSettings::CompletionShell);
KURLCompletion* comp = new KURLCompletion(KURLCompletion::FileCompletion);
comp->setReplaceHome(true);
setCompletionObject(comp);
setAutoDeleteCompletionObject(true);
}
else
setCompletionMode(KGlobalSettings::CompletionNone);
}
/******************************************************************************
* Called when the line edit receives focus.
* If 'noSelect' is true, prevent the contents being selected.
*/
void LineEdit::focusInEvent(QFocusEvent* e)
{
QFocusEvent newe(QEvent::FocusIn, (mNoSelect ? Qt::OtherFocusReason : e->reason()));
KLineEdit::focusInEvent(&newe);
mNoSelect = false;
}
void LineEdit::setText(const QString& text)
{
KLineEdit::setText(text);
setCursorPosition(mSetCursorAtEnd ? text.length() : 0);
}
void LineEdit::dragEnterEvent(QDragEnterEvent* e)
{
const QMimeData* data = e->mimeData();
bool ok;
if (KCal::ICalDrag::canDecode(e))
ok = false; // don't accept "text/calendar" objects
else
ok = (data->hasText()
|| K3URLDrag::canDecode(e)
|| mType != Url && KPIM::MailListDrag::canDecode(e)
|| mType == Emails && KVCardDrag::canDecode(e));
if (ok)
e->accept(rect());
else
e->ignore(rect());
}
void LineEdit::dropEvent(QDropEvent* e)
{
const QMimeData* data = e->mimeData();
QString newText;
QStringList newEmails;
KPIM::MailList mailList;
KURL::List files;
KABC::Addressee::List addrList;
if (mType != Url
&& data->hasFormat(KPIM::MailListDrag::format())
&& KPIM::MailListDrag::decode(e, mailList))
{
// KMail message(s) - ignore all but the first
if (mailList.count())
{
if (mType == Emails)
newText = mailList.first().from();
else
setText(mailList.first().subject()); // replace any existing text
}
}
// This must come before K3URLDrag
else if (mType == Emails
&& KVCardDrag::canDecode(e) && KVCardDrag::decode(e, addrList))
{
// KAddressBook entries
for (KABC::Addressee::List::Iterator it = addrList.begin(); it != addrList.end(); ++it)
{
QString em((*it).fullEmail());
if (!em.isEmpty())
newEmails.append(em);
}
}
else if (K3URLDrag::decode(e, files) && files.count())
{
// URL(s)
switch (mType)
{
case Url:
// URL entry field - ignore all but the first dropped URL
setText(files.first().prettyURL()); // replace any existing text
break;
case Emails:
{
// Email entry field - ignore all but mailto: URLs
QString mailto = QString::fromLatin1("mailto");
for (KURL::List::Iterator it = files.begin(); it != files.end(); ++it)
{
if ((*it).protocol() == mailto)
newEmails.append((*it).path());
}
break;
}
case Text:
newText = files.first().prettyURL();
break;
}
}
else if (data->hasText())
{
// Plain text
QString txt = data->text();
if (mType == Emails)
{
// Remove newlines from a list of email addresses, and allow an eventual mailto: protocol
QString mailto = QString::fromLatin1("mailto:");
newEmails = txt.split(QRegExp("[\r\n]+"), QString::SkipEmptyParts);
for (QStringList::Iterator it = newEmails.begin(); it != newEmails.end(); ++it)
{
if ((*it).startsWith(mailto))
{
KURL url(*it);
*it = url.path();
}
}
}
else
{
int newline = txt.indexOf(QChar('\n'));
newText = (newline >= 0) ? txt.left(newline) : txt;
}
}
if (newEmails.count())
{
newText = newEmails.join(",");
int c = cursorPosition();
if (c > 0)
newText.prepend(",");
if (c < static_cast<int>(text().length()))
newText.append(",");
}
if (!newText.isEmpty())
insert(newText);
}
<commit_msg>Remove KDE 3 compatibility code<commit_after>/*
* lineedit.cpp - Line edit widget with extra drag and drop options
* Program: kalarm
* Copyright (c) 2003 - 2005 by David Jarvie <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <QRegExp>
#include <QMimeData>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFocusEvent>
#include <kurl.h>
#include <kurlcompletion.h>
#include <libkdepim/maillistdrag.h>
#include <libkdepim/kvcarddrag.h>
#include <libkcal/icaldrag.h>
#include "lineedit.moc"
/*=============================================================================
= Class LineEdit
= Line edit which accepts drag and drop of text, URLs and/or email addresses.
* It has an option to prevent its contents being selected when it receives
= focus.
=============================================================================*/
LineEdit::LineEdit(Type type, QWidget* parent)
: KLineEdit(parent),
mType(type),
mNoSelect(false),
mSetCursorAtEnd(false)
{
init();
}
LineEdit::LineEdit(QWidget* parent)
: KLineEdit(parent),
mType(Text),
mNoSelect(false),
mSetCursorAtEnd(false)
{
init();
}
void LineEdit::init()
{
if (mType == Url)
{
setCompletionMode(KGlobalSettings::CompletionShell);
KURLCompletion* comp = new KURLCompletion(KURLCompletion::FileCompletion);
comp->setReplaceHome(true);
setCompletionObject(comp);
setAutoDeleteCompletionObject(true);
}
else
setCompletionMode(KGlobalSettings::CompletionNone);
}
/******************************************************************************
* Called when the line edit receives focus.
* If 'noSelect' is true, prevent the contents being selected.
*/
void LineEdit::focusInEvent(QFocusEvent* e)
{
QFocusEvent newe(QEvent::FocusIn, (mNoSelect ? Qt::OtherFocusReason : e->reason()));
KLineEdit::focusInEvent(&newe);
mNoSelect = false;
}
void LineEdit::setText(const QString& text)
{
KLineEdit::setText(text);
setCursorPosition(mSetCursorAtEnd ? text.length() : 0);
}
void LineEdit::dragEnterEvent(QDragEnterEvent* e)
{
const QMimeData* data = e->mimeData();
bool ok;
if (KCal::ICalDrag::canDecode(e))
ok = false; // don't accept "text/calendar" objects
else
ok = (data->hasText()
|| KURL::List::canDecode(data)
|| mType != Url && KPIM::MailListDrag::canDecode(e)
|| mType == Emails && KVCardDrag::canDecode(e));
if (ok)
e->accept(rect());
else
e->ignore(rect());
}
void LineEdit::dropEvent(QDropEvent* e)
{
const QMimeData* data = e->mimeData();
QString newText;
QStringList newEmails;
KPIM::MailList mailList;
KURL::List files;
KABC::Addressee::List addrList;
if (mType != Url
&& data->hasFormat(KPIM::MailListDrag::format())
&& KPIM::MailListDrag::decode(e, mailList))
{
// KMail message(s) - ignore all but the first
if (mailList.count())
{
if (mType == Emails)
newText = mailList.first().from();
else
setText(mailList.first().subject()); // replace any existing text
}
}
// This must come before KURL
else if (mType == Emails
&& KVCardDrag::canDecode(e) && KVCardDrag::decode(e, addrList))
{
// KAddressBook entries
for (KABC::Addressee::List::Iterator it = addrList.begin(); it != addrList.end(); ++it)
{
QString em((*it).fullEmail());
if (!em.isEmpty())
newEmails.append(em);
}
}
else if (!(files = KURL::List::fromMimeData(data)).isEmpty())
{
// URL(s)
switch (mType)
{
case Url:
// URL entry field - ignore all but the first dropped URL
setText(files.first().prettyURL()); // replace any existing text
break;
case Emails:
{
// Email entry field - ignore all but mailto: URLs
QString mailto = QString::fromLatin1("mailto");
for (KURL::List::Iterator it = files.begin(); it != files.end(); ++it)
{
if ((*it).protocol() == mailto)
newEmails.append((*it).path());
}
break;
}
case Text:
newText = files.first().prettyURL();
break;
}
}
else if (data->hasText())
{
// Plain text
QString txt = data->text();
if (mType == Emails)
{
// Remove newlines from a list of email addresses, and allow an eventual mailto: protocol
QString mailto = QString::fromLatin1("mailto:");
newEmails = txt.split(QRegExp("[\r\n]+"), QString::SkipEmptyParts);
for (QStringList::Iterator it = newEmails.begin(); it != newEmails.end(); ++it)
{
if ((*it).startsWith(mailto))
{
KURL url(*it);
*it = url.path();
}
}
}
else
{
int newline = txt.indexOf(QChar('\n'));
newText = (newline >= 0) ? txt.left(newline) : txt;
}
}
if (newEmails.count())
{
newText = newEmails.join(",");
int c = cursorPosition();
if (c > 0)
newText.prepend(",");
if (c < static_cast<int>(text().length()))
newText.append(",");
}
if (!newText.isEmpty())
insert(newText);
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2005 Till Adam <[email protected]>
*
* 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; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#include "copyfolderjob.h"
#include "folderstorage.h"
#include "kmacctcachedimap.h"
#include "kmfoldercachedimap.h"
#include "kmfolder.h"
#include "kmfolderdir.h"
#include "kmfoldertype.h"
#include "kmfoldermgr.h"
#include "kmcommands.h"
#include "kmmsgbase.h"
#include "undostack.h"
#include <kconfiggroup.h>
#include <kdebug.h>
#include <klocale.h>
using namespace KMail;
CopyFolderJob::CopyFolderJob( FolderStorage* const storage, KMFolderDir* const newParent )
: FolderJob( 0, tOther, (storage ? storage->folder() : 0) ),
mStorage( storage ), mNewParent( newParent ),
mNewFolder( 0 ), mNextChildFolder( 0 )
{
if ( mStorage->folder()->child() &&
mStorage->folder()->child()->size() > 0 ) {
mHasChildFolders = true;
mChildFolderNodeIterator = mStorage->folder()->child()->begin();
}
else
mHasChildFolders = false;
mStorage->open( "copyfolder" );
}
CopyFolderJob::~CopyFolderJob()
{
kDebug(5006) << k_funcinfo << endl;
if ( mNewFolder )
mNewFolder->setMoveInProgress( false );
if ( mStorage )
mStorage->close( "copyfolder" );
}
/*
* The basic strategy is to first create the target folder, then copy all the mail
* from the source to the target folder, then recurse for each of the folder's children
*/
void CopyFolderJob::execute()
{
if ( createTargetDir() ) {
copyMessagesToTargetDir();
}
}
void CopyFolderJob::copyMessagesToTargetDir()
{
// Hmmmm. Tasty hack. Can I have fries with that?
mStorage->blockSignals( true );
// move all messages to the new folder
QList<KMMsgBase*> msgList;
for ( int i = 0; i < mStorage->count(); i++ )
{
KMMsgBase* msgBase = mStorage->getMsgBase( i );
assert( msgBase );
msgList.append( msgBase );
}
if ( msgList.count() == 0 ) {
slotCopyNextChild(); // no contents, check subfolders
mStorage->blockSignals( false );
} else {
KMCommand *command = new KMCopyCommand( mNewFolder, msgList );
connect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
command->start();
}
}
void CopyFolderJob::slotCopyCompleted( KMCommand* command )
{
kDebug(5006) << k_funcinfo << (command?command->result():0) << endl;
disconnect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
mStorage->blockSignals( false );
if ( command && command->result() != KMCommand::OK ) {
rollback();
return;
}
// if we have children, recurse
if ( mHasChildFolders )
slotCopyNextChild();
else {
emit folderCopyComplete( true );
deleteLater();
}
}
void CopyFolderJob::slotCopyNextChild( bool success )
{
if ( mNextChildFolder )
mNextChildFolder->close( "copyfolder" ); // refcount
// previous sibling failed
if ( !success ) {
kDebug(5006) << "Failed to copy one subfolder, let's not continue: " << mNewFolder->prettyUrl() << endl;
rollback();
emit folderCopyComplete( false );
deleteLater();
}
//Attempt to find the next child folder which is not a directory
KMFolderNode* node = 0;
bool folderFound = false;
if ( mHasChildFolders )
for ( ; mChildFolderNodeIterator != mStorage->folder()->child()->end();
++mChildFolderNodeIterator ) {
node = *mChildFolderNodeIterator;
if ( !node->isDir() ) {
folderFound = true;
break;
}
}
if ( folderFound ) {
mNextChildFolder = static_cast<KMFolder*>(node);
++mChildFolderNodeIterator;
} else {
// no more children, we are done
emit folderCopyComplete( true );
deleteLater();
return;
}
KMFolderDir * const dir = mNewFolder->createChildFolder();
if ( !dir ) {
kDebug(5006) << "Failed to create subfolders of: " << mNewFolder->prettyUrl() << endl;
emit folderCopyComplete( false );
deleteLater();
return;
}
// let it do its thing and report back when we are ready to do the next sibling
mNextChildFolder->open( "copyfolder" ); // refcount
FolderJob* job = new CopyFolderJob( mNextChildFolder->storage(), dir);
connect( job, SIGNAL( folderCopyComplete( bool ) ),
this, SLOT( slotCopyNextChild( bool ) ) );
job->start();
}
// FIXME factor into CreateFolderJob and make async, so it works with online imap
// (create folder code taken from newfolderdialog.cpp)
bool CopyFolderJob::createTargetDir()
{
// get the default mailbox type
KConfig * const config = KMKernel::config();
KConfigGroup saver(config, "General");
int deftype = saver.readEntry("default-mailbox-format", 1);
if ( deftype < 0 || deftype > 1 ) deftype = 1;
// the type of the new folder
KMFolderType typenew =
( deftype == 0 ) ? KMFolderTypeMbox : KMFolderTypeMaildir;
if ( mNewParent->owner() )
typenew = mNewParent->owner()->folderType();
bool success = false, waitForFolderCreation = false;
if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeImap ) {
KMFolderImap* selectedStorage = static_cast<KMFolderImap*>( mNewParent->owner()->storage() );
KMAcctImap *anAccount = selectedStorage->account();
// check if a connection is available BEFORE creating the folder
if (anAccount->makeConnection() == ImapAccountBase::Connected) {
mNewFolder = kmkernel->imapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent );
if ( mNewFolder ) {
QString imapPath;
imapPath = anAccount->createImapPath( selectedStorage->imapPath(), mStorage->folder()->name() );
KMFolderImap* newStorage = static_cast<KMFolderImap*>( mNewFolder->storage() );
connect( selectedStorage, SIGNAL(folderCreationResult(const QString&, bool)),
this, SLOT(folderCreationDone(const QString&, bool)) );
selectedStorage->createFolder( mStorage->folder()->name(), QString() ); // create it on the server
newStorage->initializeFrom( selectedStorage, imapPath, QString() );
static_cast<KMFolderImap*>(mNewParent->owner()->storage())->setAccount( selectedStorage->account() );
waitForFolderCreation = true;
success = true;
}
}
} else if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeCachedImap ) {
mNewFolder = kmkernel->dimapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent );
if ( mNewFolder ) {
KMFolderCachedImap* selectedStorage = static_cast<KMFolderCachedImap*>( mNewParent->owner()->storage() );
KMFolderCachedImap* newStorage = static_cast<KMFolderCachedImap*>( mNewFolder->storage() );
newStorage->initializeFrom( selectedStorage );
success = true;
}
} else {
// local folder
mNewFolder = kmkernel->folderMgr()->createFolder(mStorage->folder()->name(), false, typenew, mNewParent );
if ( mNewFolder )
success = true;
}
if ( !success ) {
kWarning(5006) << k_funcinfo << "could not create folder" << endl;
emit folderCopyComplete( false );
deleteLater();
return false;
}
mNewFolder->setMoveInProgress( true );
// inherit the folder type
// FIXME we should probably copy over most if not all settings
mNewFolder->storage()->setContentsType( mStorage->contentsType(), true /*quiet*/ );
mNewFolder->storage()->writeConfig();
kDebug(5006)<< "CopyJob::createTargetDir - " << mStorage->folder()->idString()
<< " |=> " << mNewFolder->idString() << endl;
return !waitForFolderCreation;
}
void CopyFolderJob::rollback()
{
// copy failed - rollback the last transaction
// kmkernel->undoStack()->undo();
// .. and delete the new folder
if ( mNewFolder ) {
if ( mNewFolder->folderType() == KMFolderTypeImap )
{
kmkernel->imapFolderMgr()->remove( mNewFolder );
} else if ( mNewFolder->folderType() == KMFolderTypeCachedImap )
{
// tell the account (see KMFolderCachedImap::listDirectory2)
KMFolderCachedImap* folder = static_cast<KMFolderCachedImap*>(mNewFolder->storage());
KMAcctCachedImap* acct = folder->account();
if ( acct )
acct->addDeletedFolder( folder->imapPath() );
kmkernel->dimapFolderMgr()->remove( mNewFolder );
} else if ( mNewFolder->folderType() == KMFolderTypeSearch )
{
// invalid
kWarning(5006) << k_funcinfo << "cannot remove a search folder" << endl;
} else {
kmkernel->folderMgr()->remove( mNewFolder );
}
}
emit folderCopyComplete( false );
deleteLater();
}
void CopyFolderJob::folderCreationDone(const QString & name, bool success)
{
if ( mStorage->folder()->name() != name )
return; // not our business
kDebug(5006) << k_funcinfo << success << endl;
if ( !success ) {
rollback();
} else {
copyMessagesToTargetDir();
}
}
#include "copyfolderjob.moc"
<commit_msg>Forwardport SVN commit 687341 by vkrause:<commit_after>/**
* Copyright (c) 2005 Till Adam <[email protected]>
*
* 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; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#include "copyfolderjob.h"
#include "folderstorage.h"
#include "kmacctcachedimap.h"
#include "kmfoldercachedimap.h"
#include "kmfolder.h"
#include "kmfolderdir.h"
#include "kmfoldertype.h"
#include "kmfoldermgr.h"
#include "kmcommands.h"
#include "kmmsgbase.h"
#include "undostack.h"
#include <kconfiggroup.h>
#include <kdebug.h>
#include <klocale.h>
using namespace KMail;
CopyFolderJob::CopyFolderJob( FolderStorage* const storage, KMFolderDir* const newParent )
: FolderJob( 0, tOther, (storage ? storage->folder() : 0) ),
mStorage( storage ), mNewParent( newParent ),
mNewFolder( 0 ), mNextChildFolder( 0 )
{
if ( mStorage->folder()->child() &&
mStorage->folder()->child()->size() > 0 ) {
mHasChildFolders = true;
mChildFolderNodeIterator = mStorage->folder()->child()->begin();
}
else
mHasChildFolders = false;
mStorage->open( "copyfolder" );
}
CopyFolderJob::~CopyFolderJob()
{
kDebug(5006) << k_funcinfo << endl;
if ( mNewFolder )
mNewFolder->setMoveInProgress( false );
if ( mStorage )
mStorage->close( "copyfolder" );
}
/*
* The basic strategy is to first create the target folder, then copy all the mail
* from the source to the target folder, then recurse for each of the folder's children
*/
void CopyFolderJob::execute()
{
if ( createTargetDir() ) {
copyMessagesToTargetDir();
}
}
void CopyFolderJob::copyMessagesToTargetDir()
{
// Hmmmm. Tasty hack. Can I have fries with that?
mStorage->blockSignals( true );
// move all messages to the new folder
QList<KMMsgBase*> msgList;
for ( int i = 0; i < mStorage->count(); i++ )
{
KMMsgBase* msgBase = mStorage->getMsgBase( i );
assert( msgBase );
msgList.append( msgBase );
}
if ( msgList.count() == 0 ) {
mStorage->blockSignals( false );
// ### be careful, after slotCopyNextChild() the source folder
// (including mStorage) might already be deleted!
slotCopyNextChild(); // no contents, check subfolders
} else {
KMCommand *command = new KMCopyCommand( mNewFolder, msgList );
connect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
command->start();
}
}
void CopyFolderJob::slotCopyCompleted( KMCommand* command )
{
kDebug(5006) << k_funcinfo << (command?command->result():0) << endl;
disconnect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
mStorage->blockSignals( false );
if ( command && command->result() != KMCommand::OK ) {
rollback();
return;
}
// if we have children, recurse
if ( mHasChildFolders )
slotCopyNextChild();
else {
emit folderCopyComplete( true );
deleteLater();
}
}
void CopyFolderJob::slotCopyNextChild( bool success )
{
if ( mNextChildFolder )
mNextChildFolder->close( "copyfolder" ); // refcount
// previous sibling failed
if ( !success ) {
kDebug(5006) << "Failed to copy one subfolder, let's not continue: " << mNewFolder->prettyUrl() << endl;
rollback();
emit folderCopyComplete( false );
deleteLater();
}
//Attempt to find the next child folder which is not a directory
KMFolderNode* node = 0;
bool folderFound = false;
if ( mHasChildFolders )
for ( ; mChildFolderNodeIterator != mStorage->folder()->child()->end();
++mChildFolderNodeIterator ) {
node = *mChildFolderNodeIterator;
if ( !node->isDir() ) {
folderFound = true;
break;
}
}
if ( folderFound ) {
mNextChildFolder = static_cast<KMFolder*>(node);
++mChildFolderNodeIterator;
} else {
// no more children, we are done
emit folderCopyComplete( true );
deleteLater();
return;
}
KMFolderDir * const dir = mNewFolder->createChildFolder();
if ( !dir ) {
kDebug(5006) << "Failed to create subfolders of: " << mNewFolder->prettyUrl() << endl;
emit folderCopyComplete( false );
deleteLater();
return;
}
// let it do its thing and report back when we are ready to do the next sibling
mNextChildFolder->open( "copyfolder" ); // refcount
FolderJob* job = new CopyFolderJob( mNextChildFolder->storage(), dir);
connect( job, SIGNAL( folderCopyComplete( bool ) ),
this, SLOT( slotCopyNextChild( bool ) ) );
job->start();
}
// FIXME factor into CreateFolderJob and make async, so it works with online imap
// (create folder code taken from newfolderdialog.cpp)
bool CopyFolderJob::createTargetDir()
{
// get the default mailbox type
KConfig * const config = KMKernel::config();
KConfigGroup saver(config, "General");
int deftype = saver.readEntry("default-mailbox-format", 1);
if ( deftype < 0 || deftype > 1 ) deftype = 1;
// the type of the new folder
KMFolderType typenew =
( deftype == 0 ) ? KMFolderTypeMbox : KMFolderTypeMaildir;
if ( mNewParent->owner() )
typenew = mNewParent->owner()->folderType();
bool success = false, waitForFolderCreation = false;
if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeImap ) {
KMFolderImap* selectedStorage = static_cast<KMFolderImap*>( mNewParent->owner()->storage() );
KMAcctImap *anAccount = selectedStorage->account();
// check if a connection is available BEFORE creating the folder
if (anAccount->makeConnection() == ImapAccountBase::Connected) {
mNewFolder = kmkernel->imapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent );
if ( mNewFolder ) {
QString imapPath;
imapPath = anAccount->createImapPath( selectedStorage->imapPath(), mStorage->folder()->name() );
KMFolderImap* newStorage = static_cast<KMFolderImap*>( mNewFolder->storage() );
connect( selectedStorage, SIGNAL(folderCreationResult(const QString&, bool)),
this, SLOT(folderCreationDone(const QString&, bool)) );
selectedStorage->createFolder( mStorage->folder()->name(), QString() ); // create it on the server
newStorage->initializeFrom( selectedStorage, imapPath, QString() );
static_cast<KMFolderImap*>(mNewParent->owner()->storage())->setAccount( selectedStorage->account() );
waitForFolderCreation = true;
success = true;
}
}
} else if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeCachedImap ) {
mNewFolder = kmkernel->dimapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent );
if ( mNewFolder ) {
KMFolderCachedImap* selectedStorage = static_cast<KMFolderCachedImap*>( mNewParent->owner()->storage() );
KMFolderCachedImap* newStorage = static_cast<KMFolderCachedImap*>( mNewFolder->storage() );
newStorage->initializeFrom( selectedStorage );
success = true;
}
} else {
// local folder
mNewFolder = kmkernel->folderMgr()->createFolder(mStorage->folder()->name(), false, typenew, mNewParent );
if ( mNewFolder )
success = true;
}
if ( !success ) {
kWarning(5006) << k_funcinfo << "could not create folder" << endl;
emit folderCopyComplete( false );
deleteLater();
return false;
}
mNewFolder->setMoveInProgress( true );
// inherit the folder type
// FIXME we should probably copy over most if not all settings
mNewFolder->storage()->setContentsType( mStorage->contentsType(), true /*quiet*/ );
mNewFolder->storage()->writeConfig();
kDebug(5006)<< "CopyJob::createTargetDir - " << mStorage->folder()->idString()
<< " |=> " << mNewFolder->idString() << endl;
return !waitForFolderCreation;
}
void CopyFolderJob::rollback()
{
// copy failed - rollback the last transaction
// kmkernel->undoStack()->undo();
// .. and delete the new folder
if ( mNewFolder ) {
if ( mNewFolder->folderType() == KMFolderTypeImap )
{
kmkernel->imapFolderMgr()->remove( mNewFolder );
} else if ( mNewFolder->folderType() == KMFolderTypeCachedImap )
{
// tell the account (see KMFolderCachedImap::listDirectory2)
KMFolderCachedImap* folder = static_cast<KMFolderCachedImap*>(mNewFolder->storage());
KMAcctCachedImap* acct = folder->account();
if ( acct )
acct->addDeletedFolder( folder->imapPath() );
kmkernel->dimapFolderMgr()->remove( mNewFolder );
} else if ( mNewFolder->folderType() == KMFolderTypeSearch )
{
// invalid
kWarning(5006) << k_funcinfo << "cannot remove a search folder" << endl;
} else {
kmkernel->folderMgr()->remove( mNewFolder );
}
}
emit folderCopyComplete( false );
deleteLater();
}
void CopyFolderJob::folderCreationDone(const QString & name, bool success)
{
if ( mStorage->folder()->name() != name )
return; // not our business
kDebug(5006) << k_funcinfo << success << endl;
if ( !success ) {
rollback();
} else {
copyMessagesToTargetDir();
}
}
#include "copyfolderjob.moc"
<|endoftext|> |
<commit_before><commit_msg>Fix a big mistake<commit_after><|endoftext|> |
<commit_before><commit_msg>Improve warning message when extra attributes cannot be created<commit_after><|endoftext|> |
<commit_before>#include "Utility/Random.h"
#include <random>
#include <string>
#include <limits>
namespace
{
struct Seeder
{
using result_type = unsigned int;
template<typename Iterator>
void generate(Iterator begin, Iterator end)
{
std::random_device rd;
std::generate(begin, end, [&rd]() { return rd(); });
}
};
}
Random::Random_Bits_Generator Random::get_new_seeded_random_bit_source() noexcept
{
return Random_Bits_Generator{Seeder{}};
}
double Random::random_laplace(double width) noexcept
{
thread_local static auto generator = get_new_seeded_random_bit_source();
using ed = std::exponential_distribution<double>;
thread_local static auto dist = ed{};
return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0/width});
}
uint64_t Random::random_unsigned_int64() noexcept
{
return random_integer(std::numeric_limits<uint64_t>::min(),
std::numeric_limits<uint64_t>::max());
}
bool Random::coin_flip() noexcept
{
return success_probability(1, 2);
}
bool Random::success_probability(size_t successes, size_t attempts) noexcept
{
assert(attempts > 0);
return random_integer(size_t{1}, attempts) <= successes;
}
std::string Random::random_string(size_t size) noexcept
{
std::string s;
while(s.size() < size)
{
s.push_back('a' + random_integer(0, 25));
}
return s;
}
<commit_msg>Fix incorrect seeding (according to gcc and clang)<commit_after>#include "Utility/Random.h"
#include <random>
#include <string>
#include <limits>
namespace
{
struct Seeder
{
using result_type = unsigned int;
template<typename Iterator>
void generate(Iterator begin, Iterator end)
{
std::random_device rd;
std::generate(begin, end, [&rd]() { return rd(); });
}
};
}
Random::Random_Bits_Generator Random::get_new_seeded_random_bit_source() noexcept
{
auto seeder = Seeder{};
return Random_Bits_Generator(seeder);
}
double Random::random_laplace(double width) noexcept
{
thread_local static auto generator = get_new_seeded_random_bit_source();
using ed = std::exponential_distribution<double>;
thread_local static auto dist = ed{};
return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0/width});
}
uint64_t Random::random_unsigned_int64() noexcept
{
return random_integer(std::numeric_limits<uint64_t>::min(),
std::numeric_limits<uint64_t>::max());
}
bool Random::coin_flip() noexcept
{
return success_probability(1, 2);
}
bool Random::success_probability(size_t successes, size_t attempts) noexcept
{
assert(attempts > 0);
return random_integer(size_t{1}, attempts) <= successes;
}
std::string Random::random_string(size_t size) noexcept
{
std::string s;
while(s.size() < size)
{
s.push_back('a' + random_integer(0, 25));
}
return s;
}
<|endoftext|> |
<commit_before>#include "Utility/Random.h"
#include <random>
#include <string>
double Random::random_laplace(double width) noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using ed = std::exponential_distribution<double>;
thread_local static auto dist = ed{};
return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0/width});
}
uint64_t Random::random_unsigned_int64() noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
thread_local static std::uniform_int_distribution<uint64_t> dist;
return dist(generator);
}
bool Random::coin_flip() noexcept
{
return success_probability(1, 2);
}
bool Random::success_probability(size_t successes, size_t attempts) noexcept
{
assert(attempts > 0);
return random_integer(size_t{1}, attempts) <= successes;
}
std::string Random::random_string(size_t size) noexcept
{
std::string s;
while(s.size() < size)
{
s.push_back('a' + random_integer(0, 25));
}
return s;
}
<commit_msg>Reuse random_integer() for random_unsigned_int64()<commit_after>#include "Utility/Random.h"
#include <random>
#include <string>
#include <limits>
double Random::random_laplace(double width) noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using ed = std::exponential_distribution<double>;
thread_local static auto dist = ed{};
return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0/width});
}
uint64_t Random::random_unsigned_int64() noexcept
{
return random_integer(std::numeric_limits<uint64_t>::min(),
std::numeric_limits<uint64_t>::max());
}
bool Random::coin_flip() noexcept
{
return success_probability(1, 2);
}
bool Random::success_probability(size_t successes, size_t attempts) noexcept
{
assert(attempts > 0);
return random_integer(size_t{1}, attempts) <= successes;
}
std::string Random::random_string(size_t size) noexcept
{
std::string s;
while(s.size() < size)
{
s.push_back('a' + random_integer(0, 25));
}
return s;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.