text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* \file
* \brief Definitions of clocks for STM32L0
*
* \author Copyright (C) 2017 Cezary Gapinski [email protected]
*
* \par License
* 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/.
*/
#ifndef SOURCE_CHIP_STM32_STM32L0_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#define SOURCE_CHIP_STM32_STM32L0_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#include "distortos/distortosConfiguration.h"
#include <cstdint>
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global constants
+---------------------------------------------------------------------------------------------------------------------*/
/// allowed values for MSI frequency, Hz
/// [0] - range 0 around 65.536 kHz
/// [1] - range 1 around 131.072 kHz
/// [2] - range 2 around 262.144 kHz
/// [3] - range 3 around 524.288 kHz
/// [4] - range 4 around 1.048 MHz
/// [5] - range 5 around 2.097 MHz
/// [6] - range 6 around 4.194 MHz
constexpr uint32_t msiFrequencies[7]
{
65536,
131072,
262144,
524288,
1048000,
2097000,
4194000,
};
/// HSI16 clock frequency, Hz
constexpr uint32_t hsi16Frequency {16000000};
/// minimum allowed value for PLL VCO input frequency, Hz
constexpr uint32_t minPllInFrequency {2000000};
/// maximum allowed value for PLL VCO input frequency, Hz
constexpr uint32_t maxPllInFrequency {24000000};
/// minimum allowed value for PLL output frequency, Hz
constexpr uint32_t minPllOutFrequency {1500000};
/// maximum allowed values for PLL output frequency, Hz
/// [0] - voltage scale 1
/// [1] - voltage scale 2
/// [2] - voltage scale 3
constexpr uint32_t maxPllOutFrequencies[3]
{
960000000,
480000000,
240000000,
};
/// maximum allowed APB1 (low speed) frequency, Hz
constexpr uint32_t maxApb1Frequency {32000000};
/// maximum allowed APB2 (high speed) frequency, Hz
constexpr uint32_t maxApb2Frequency {32000000};
#ifdef CONFIG_CHIP_STM32L0_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// voltage scale index for \a maxPllOutFrequencies array (maxPllOutFrequencies[voltageScaleIndex])
constexpr uint8_t voltageScaleIndex {CONFIG_CHIP_STM32L0_PWR_VOLTAGE_SCALE_MODE - 1};
/// maximum allowed value for PLL output frequency, Hz
constexpr uint32_t maxPllOutFrequency {maxPllOutFrequencies[voltageScaleIndex]};
#if defined(CONFIG_CHIP_STM32L0_RCC_MSI_ENABLE)
/// voltage scale index for \a msiFrequencies array (maxPllOutFrequencies[msiRangeIndex])
constexpr uint8_t msiRangeIndex {CONFIG_CHIP_STM32L0_RCC_MSIRANGE};
/// allowed value for MSI frequency, Hz
constexpr uint32_t msiFrequency {msiFrequencies[msiRangeIndex]};
#endif // defined(CONFIG_CHIP_STM32L0_RCC_MSI_ENABLE)
#ifdef CONFIG_CHIP_STM32L0_RCC_PLL_ENABLE
/// PLL input frequency, Hz
#if defined(CONFIG_CHIP_STM32L0_RCC_PLLSRC_HSI16)
constexpr uint32_t pllInFrequency {hsi16Frequency};
#elif defined(CONFIG_CHIP_STM32L0_RCC_PLLSRC_HSE)
constexpr uint32_t pllInFrequency {CONFIG_CHIP_STM32L0_RCC_HSE_FREQUENCY};
#endif // defined(CONFIG_CHIP_STM32L0_RCC_PLLSRC_HSE)
static_assert(minPllInFrequency <= pllInFrequency && pllInFrequency <= maxPllInFrequency,
"Invalid PLL input frequency!");
/// PLL output frequency, Hz
constexpr uint32_t pllOutFrequency {(pllInFrequency * CONFIG_CHIP_STM32L0_RCC_PLLMUL) / CONFIG_CHIP_STM32L0_RCC_PLLDIV};
static_assert(minPllOutFrequency <= pllOutFrequency && pllOutFrequency <= maxPllOutFrequency,
"Invalid PLL output frequency!");
#endif // def CONFIG_CHIP_STM32L0_RCC_PLL_ENABLE
/// SYSCLK frequency, Hz
#if defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_MSI)
constexpr uint32_t sysclkFrequency {msiFrequency};
#elif defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_HSI16)
constexpr uint32_t sysclkFrequency {hsi16Frequency};
#elif defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_HSE)
constexpr uint32_t sysclkFrequency {CONFIG_CHIP_STM32L0_RCC_HSE_FREQUENCY};
#elif defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_PLL)
constexpr uint32_t sysclkFrequency {pllOutFrequency};
#else
#error "All SYSCLK sources disabled!"
#endif // defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_PLL)
#else // !def CONFIG_CHIP_STM32L0_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// SYSCLK frequency, Hz
constexpr uint32_t sysclkFrequency {CONFIG_CHIP_STM32L0_RCC_SYSCLK_FREQUENCY};
#endif // !def CONFIG_CHIP_STM32L0_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// AHB frequency, Hz
constexpr uint32_t ahbFrequency {sysclkFrequency / CONFIG_CHIP_STM32L0_RCC_HPRE};
/// APB1 frequency, Hz
constexpr uint32_t apb1Frequency {ahbFrequency / CONFIG_CHIP_STM32L0_RCC_PPRE1};
static_assert(apb1Frequency <= maxApb1Frequency, "Invalid APB1 (low speed) frequency!");
/// APB2 frequency, Hz
constexpr uint32_t apb2Frequency {ahbFrequency / CONFIG_CHIP_STM32L0_RCC_PPRE2};
static_assert(apb2Frequency <= maxApb2Frequency, "Invalid APB2 (high speed) frequency!");
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_STM32L0_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
<commit_msg>Simplify comment for msiFrequencies[] in clocks.hpp for STM32L0<commit_after>/**
* \file
* \brief Definitions of clocks for STM32L0
*
* \author Copyright (C) 2017 Cezary Gapinski [email protected]
*
* \par License
* 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/.
*/
#ifndef SOURCE_CHIP_STM32_STM32L0_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#define SOURCE_CHIP_STM32_STM32L0_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
#include "distortos/distortosConfiguration.h"
#include <cstdint>
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global constants
+---------------------------------------------------------------------------------------------------------------------*/
/// MSI frequencies, Hz
/// [0] - range 0
/// [1] - range 1
/// [2] - range 2
/// [3] - range 3
/// [4] - range 4
/// [5] - range 5
/// [6] - range 6
constexpr uint32_t msiFrequencies[7]
{
65536,
131072,
262144,
524288,
1048000,
2097000,
4194000,
};
/// HSI16 clock frequency, Hz
constexpr uint32_t hsi16Frequency {16000000};
/// minimum allowed value for PLL VCO input frequency, Hz
constexpr uint32_t minPllInFrequency {2000000};
/// maximum allowed value for PLL VCO input frequency, Hz
constexpr uint32_t maxPllInFrequency {24000000};
/// minimum allowed value for PLL output frequency, Hz
constexpr uint32_t minPllOutFrequency {1500000};
/// maximum allowed values for PLL output frequency, Hz
/// [0] - voltage scale 1
/// [1] - voltage scale 2
/// [2] - voltage scale 3
constexpr uint32_t maxPllOutFrequencies[3]
{
960000000,
480000000,
240000000,
};
/// maximum allowed APB1 (low speed) frequency, Hz
constexpr uint32_t maxApb1Frequency {32000000};
/// maximum allowed APB2 (high speed) frequency, Hz
constexpr uint32_t maxApb2Frequency {32000000};
#ifdef CONFIG_CHIP_STM32L0_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// voltage scale index for \a maxPllOutFrequencies array (maxPllOutFrequencies[voltageScaleIndex])
constexpr uint8_t voltageScaleIndex {CONFIG_CHIP_STM32L0_PWR_VOLTAGE_SCALE_MODE - 1};
/// maximum allowed value for PLL output frequency, Hz
constexpr uint32_t maxPllOutFrequency {maxPllOutFrequencies[voltageScaleIndex]};
#if defined(CONFIG_CHIP_STM32L0_RCC_MSI_ENABLE)
/// voltage scale index for \a msiFrequencies array (maxPllOutFrequencies[msiRangeIndex])
constexpr uint8_t msiRangeIndex {CONFIG_CHIP_STM32L0_RCC_MSIRANGE};
/// allowed value for MSI frequency, Hz
constexpr uint32_t msiFrequency {msiFrequencies[msiRangeIndex]};
#endif // defined(CONFIG_CHIP_STM32L0_RCC_MSI_ENABLE)
#ifdef CONFIG_CHIP_STM32L0_RCC_PLL_ENABLE
/// PLL input frequency, Hz
#if defined(CONFIG_CHIP_STM32L0_RCC_PLLSRC_HSI16)
constexpr uint32_t pllInFrequency {hsi16Frequency};
#elif defined(CONFIG_CHIP_STM32L0_RCC_PLLSRC_HSE)
constexpr uint32_t pllInFrequency {CONFIG_CHIP_STM32L0_RCC_HSE_FREQUENCY};
#endif // defined(CONFIG_CHIP_STM32L0_RCC_PLLSRC_HSE)
static_assert(minPllInFrequency <= pllInFrequency && pllInFrequency <= maxPllInFrequency,
"Invalid PLL input frequency!");
/// PLL output frequency, Hz
constexpr uint32_t pllOutFrequency {(pllInFrequency * CONFIG_CHIP_STM32L0_RCC_PLLMUL) / CONFIG_CHIP_STM32L0_RCC_PLLDIV};
static_assert(minPllOutFrequency <= pllOutFrequency && pllOutFrequency <= maxPllOutFrequency,
"Invalid PLL output frequency!");
#endif // def CONFIG_CHIP_STM32L0_RCC_PLL_ENABLE
/// SYSCLK frequency, Hz
#if defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_MSI)
constexpr uint32_t sysclkFrequency {msiFrequency};
#elif defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_HSI16)
constexpr uint32_t sysclkFrequency {hsi16Frequency};
#elif defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_HSE)
constexpr uint32_t sysclkFrequency {CONFIG_CHIP_STM32L0_RCC_HSE_FREQUENCY};
#elif defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_PLL)
constexpr uint32_t sysclkFrequency {pllOutFrequency};
#else
#error "All SYSCLK sources disabled!"
#endif // defined(CONFIG_CHIP_STM32L0_RCC_SYSCLK_PLL)
#else // !def CONFIG_CHIP_STM32L0_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// SYSCLK frequency, Hz
constexpr uint32_t sysclkFrequency {CONFIG_CHIP_STM32L0_RCC_SYSCLK_FREQUENCY};
#endif // !def CONFIG_CHIP_STM32L0_STANDARD_CLOCK_CONFIGURATION_ENABLE
/// AHB frequency, Hz
constexpr uint32_t ahbFrequency {sysclkFrequency / CONFIG_CHIP_STM32L0_RCC_HPRE};
/// APB1 frequency, Hz
constexpr uint32_t apb1Frequency {ahbFrequency / CONFIG_CHIP_STM32L0_RCC_PPRE1};
static_assert(apb1Frequency <= maxApb1Frequency, "Invalid APB1 (low speed) frequency!");
/// APB2 frequency, Hz
constexpr uint32_t apb2Frequency {ahbFrequency / CONFIG_CHIP_STM32L0_RCC_PPRE2};
static_assert(apb2Frequency <= maxApb2Frequency, "Invalid APB2 (high speed) frequency!");
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_STM32L0_INCLUDE_DISTORTOS_CHIP_CLOCKS_HPP_
<|endoftext|> |
<commit_before>//===- AnalysisOrderChecker - Print callbacks called ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This checker prints callbacks that are called during analysis.
// This is required to ensure that callbacks are fired in order
// and do not duplicate or get lost.
// Feel free to extend this checker with any callback you need to check.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/AST/ExprCXX.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
using namespace clang;
using namespace ento;
namespace {
class AnalysisOrderChecker
: public Checker<check::PreStmt<CastExpr>,
check::PostStmt<CastExpr>,
check::PreStmt<ArraySubscriptExpr>,
check::PostStmt<ArraySubscriptExpr>,
check::PreStmt<CXXNewExpr>,
check::PostStmt<CXXNewExpr>,
check::PreCall,
check::PostCall,
check::NewAllocator,
check::Bind,
check::RegionChanges,
check::LiveSymbols> {
bool isCallbackEnabled(AnalyzerOptions &Opts, StringRef CallbackName) const {
return Opts.getBooleanOption("*", false, this) ||
Opts.getBooleanOption(CallbackName, false, this);
}
bool isCallbackEnabled(CheckerContext &C, StringRef CallbackName) const {
AnalyzerOptions &Opts = C.getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
bool isCallbackEnabled(ProgramStateRef State, StringRef CallbackName) const {
AnalyzerOptions &Opts = State->getStateManager().getOwningEngine()
->getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
public:
void checkPreStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCastExpr"))
llvm::errs() << "PreStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPostStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCastExpr"))
llvm::errs() << "PostStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPreStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtArraySubscriptExpr"))
llvm::errs() << "PreStmt<ArraySubscriptExpr>\n";
}
void checkPostStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtArraySubscriptExpr"))
llvm::errs() << "PostStmt<ArraySubscriptExpr>\n";
}
void checkPreStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCXXNewExpr"))
llvm::errs() << "PreStmt<CXXNewExpr>\n";
}
void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCXXNewExpr"))
llvm::errs() << "PostStmt<CXXNewExpr>\n";
}
void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreCall")) {
llvm::errs() << "PreCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostCall")) {
llvm::errs() << "PostCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkNewAllocator(const CXXNewExpr *CNE, SVal Target,
CheckerContext &C) const {
if (isCallbackEnabled(C, "NewAllocator"))
llvm::errs() << "NewAllocator\n";
}
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {
if (isCallbackEnabled(C, "Bind"))
llvm::errs() << "Bind\n";
}
void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SymReaper) const {
if (isCallbackEnabled(State, "LiveSymbols"))
llvm::errs() << "LiveSymbols\n";
}
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const LocationContext *LCtx, const CallEvent *Call) const {
if (isCallbackEnabled(State, "RegionChanges"))
llvm::errs() << "RegionChanges\n";
return State;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Registration.
//===----------------------------------------------------------------------===//
void ento::registerAnalysisOrderChecker(CheckerManager &mgr) {
mgr.registerChecker<AnalysisOrderChecker>();
}
<commit_msg>[analyzer] Add missing pre-post-statement callbacks for OffsetOfExpr.<commit_after>//===- AnalysisOrderChecker - Print callbacks called ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This checker prints callbacks that are called during analysis.
// This is required to ensure that callbacks are fired in order
// and do not duplicate or get lost.
// Feel free to extend this checker with any callback you need to check.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/AST/ExprCXX.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
using namespace clang;
using namespace ento;
namespace {
class AnalysisOrderChecker
: public Checker<check::PreStmt<CastExpr>,
check::PostStmt<CastExpr>,
check::PreStmt<ArraySubscriptExpr>,
check::PostStmt<ArraySubscriptExpr>,
check::PreStmt<CXXNewExpr>,
check::PostStmt<CXXNewExpr>,
check::PreStmt<OffsetOfExpr>,
check::PostStmt<OffsetOfExpr>,
check::PreCall,
check::PostCall,
check::NewAllocator,
check::Bind,
check::RegionChanges,
check::LiveSymbols> {
bool isCallbackEnabled(AnalyzerOptions &Opts, StringRef CallbackName) const {
return Opts.getBooleanOption("*", false, this) ||
Opts.getBooleanOption(CallbackName, false, this);
}
bool isCallbackEnabled(CheckerContext &C, StringRef CallbackName) const {
AnalyzerOptions &Opts = C.getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
bool isCallbackEnabled(ProgramStateRef State, StringRef CallbackName) const {
AnalyzerOptions &Opts = State->getStateManager().getOwningEngine()
->getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
public:
void checkPreStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCastExpr"))
llvm::errs() << "PreStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPostStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCastExpr"))
llvm::errs() << "PostStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPreStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtArraySubscriptExpr"))
llvm::errs() << "PreStmt<ArraySubscriptExpr>\n";
}
void checkPostStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtArraySubscriptExpr"))
llvm::errs() << "PostStmt<ArraySubscriptExpr>\n";
}
void checkPreStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCXXNewExpr"))
llvm::errs() << "PreStmt<CXXNewExpr>\n";
}
void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCXXNewExpr"))
llvm::errs() << "PostStmt<CXXNewExpr>\n";
}
void checkPreStmt(const OffsetOfExpr *OOE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtOffsetOfExpr"))
llvm::errs() << "PreStmt<OffsetOfExpr>\n";
}
void checkPostStmt(const OffsetOfExpr *OOE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtOffsetOfExpr"))
llvm::errs() << "PostStmt<OffsetOfExpr>\n";
}
void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreCall")) {
llvm::errs() << "PreCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostCall")) {
llvm::errs() << "PostCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkNewAllocator(const CXXNewExpr *CNE, SVal Target,
CheckerContext &C) const {
if (isCallbackEnabled(C, "NewAllocator"))
llvm::errs() << "NewAllocator\n";
}
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {
if (isCallbackEnabled(C, "Bind"))
llvm::errs() << "Bind\n";
}
void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SymReaper) const {
if (isCallbackEnabled(State, "LiveSymbols"))
llvm::errs() << "LiveSymbols\n";
}
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const LocationContext *LCtx, const CallEvent *Call) const {
if (isCallbackEnabled(State, "RegionChanges"))
llvm::errs() << "RegionChanges\n";
return State;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Registration.
//===----------------------------------------------------------------------===//
void ento::registerAnalysisOrderChecker(CheckerManager &mgr) {
mgr.registerChecker<AnalysisOrderChecker>();
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2020, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file date_time_scanner.cc
*/
#include "date_time_scanner.hh"
#include "config.h"
#include "ptimec.hh"
size_t
date_time_scanner::ftime(char* dst,
size_t len,
const char* const time_fmt[],
const exttm& tm) const
{
off_t off = 0;
if (time_fmt == nullptr) {
PTIMEC_FORMATS[this->dts_fmt_lock].pf_ffunc(dst, off, len, tm);
if (tm.et_flags & ETF_MILLIS_SET) {
dst[off++] = '.';
ftime_L(dst, off, len, tm);
} else if (tm.et_flags & ETF_MICROS_SET) {
dst[off++] = '.';
ftime_f(dst, off, len, tm);
} else if (tm.et_flags & ETF_NANOS_SET) {
dst[off++] = '.';
ftime_N(dst, off, len, tm);
}
dst[off] = '\0';
} else {
off = ftime_fmt(dst, len, time_fmt[this->dts_fmt_lock], tm);
}
return (size_t) off;
}
bool
next_format(const char* const fmt[], int& index, int& locked_index)
{
bool retval = true;
if (locked_index == -1) {
index += 1;
if (fmt[index] == nullptr) {
retval = false;
}
} else if (index == locked_index) {
retval = false;
} else {
index = locked_index;
}
return retval;
}
const char*
date_time_scanner::scan(const char* time_dest,
size_t time_len,
const char* const time_fmt[],
struct exttm* tm_out,
struct timeval& tv_out,
bool convert_local)
{
int curr_time_fmt = -1;
bool found = false;
const char* retval = nullptr;
if (!time_fmt) {
time_fmt = PTIMEC_FORMAT_STR;
}
while (next_format(time_fmt, curr_time_fmt, this->dts_fmt_lock)) {
*tm_out = this->dts_base_tm;
tm_out->et_flags = 0;
if (time_len > 1 && time_dest[0] == '+' && isdigit(time_dest[1])) {
char time_cp[time_len + 1];
int gmt_int, off;
retval = nullptr;
memcpy(time_cp, time_dest, time_len);
time_cp[time_len] = '\0';
if (sscanf(time_cp, "+%d%n", &gmt_int, &off) == 1) {
time_t gmt = gmt_int;
if (convert_local && this->dts_local_time) {
localtime_r(&gmt, &tm_out->et_tm);
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm_out->et_tm.tm_zone = nullptr;
#endif
tm_out->et_tm.tm_isdst = 0;
gmt = tm2sec(&tm_out->et_tm);
}
tv_out.tv_sec = gmt;
tv_out.tv_usec = 0;
tm_out->et_flags = ETF_DAY_SET | ETF_MONTH_SET | ETF_YEAR_SET
| ETF_MACHINE_ORIENTED | ETF_EPOCH_TIME;
this->dts_fmt_lock = curr_time_fmt;
this->dts_fmt_len = off;
retval = time_dest + off;
found = true;
break;
}
} else if (time_fmt == PTIMEC_FORMAT_STR) {
ptime_func func = PTIMEC_FORMATS[curr_time_fmt].pf_func;
off_t off = 0;
#ifdef HAVE_STRUCT_TM_TM_ZONE
if (!this->dts_keep_base_tz) {
tm_out->et_tm.tm_zone = nullptr;
}
#endif
if (func(tm_out, time_dest, off, time_len)) {
retval = &time_dest[off];
if (tm_out->et_tm.tm_year < 70) {
tm_out->et_tm.tm_year = 80;
}
if (convert_local
&& (this->dts_local_time
|| tm_out->et_flags & ETF_EPOCH_TIME))
{
time_t gmt = tm2sec(&tm_out->et_tm);
this->to_localtime(gmt, *tm_out);
}
tv_out.tv_sec = tm2sec(&tm_out->et_tm);
tv_out.tv_usec = tm_out->et_nsec / 1000;
secs2wday(tv_out, &tm_out->et_tm);
this->dts_fmt_lock = curr_time_fmt;
this->dts_fmt_len = retval - time_dest;
found = true;
break;
}
} else {
off_t off = 0;
#ifdef HAVE_STRUCT_TM_TM_ZONE
if (!this->dts_keep_base_tz) {
tm_out->et_tm.tm_zone = nullptr;
}
#endif
if (ptime_fmt(
time_fmt[curr_time_fmt], tm_out, time_dest, off, time_len)
&& (time_dest[off] == '.' || time_dest[off] == ','
|| off == (off_t) time_len))
{
retval = &time_dest[off];
if (tm_out->et_tm.tm_year < 70) {
tm_out->et_tm.tm_year = 80;
}
if (convert_local
&& (this->dts_local_time
|| tm_out->et_flags & ETF_EPOCH_TIME))
{
time_t gmt = tm2sec(&tm_out->et_tm);
this->to_localtime(gmt, *tm_out);
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm_out->et_tm.tm_zone = nullptr;
#endif
tm_out->et_tm.tm_isdst = 0;
}
tv_out.tv_sec = tm2sec(&tm_out->et_tm);
tv_out.tv_usec = tm_out->et_nsec / 1000;
secs2wday(tv_out, &tm_out->et_tm);
this->dts_fmt_lock = curr_time_fmt;
this->dts_fmt_len = retval - time_dest;
found = true;
break;
}
}
}
if (!found) {
retval = nullptr;
}
if (retval != nullptr) {
/* Try to pull out the milli/micro-second value. */
if (retval[0] == '.' || retval[0] == ',') {
off_t off = (retval - time_dest) + 1;
if (ptime_N(tm_out, time_dest, off, time_len)) {
tv_out.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::nanoseconds{tm_out->et_nsec})
.count();
this->dts_fmt_len += 10;
tm_out->et_flags |= ETF_NANOS_SET;
retval += 10;
} else if (ptime_f(tm_out, time_dest, off, time_len)) {
tv_out.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::nanoseconds{tm_out->et_nsec})
.count();
this->dts_fmt_len += 7;
tm_out->et_flags |= ETF_MICROS_SET;
retval += 7;
} else if (ptime_L(tm_out, time_dest, off, time_len)) {
tv_out.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::nanoseconds{tm_out->et_nsec})
.count();
this->dts_fmt_len += 4;
tm_out->et_flags |= ETF_MILLIS_SET;
retval += 4;
}
}
}
return retval;
}
void
date_time_scanner::to_localtime(time_t t, exttm& tm_out)
{
if (t < (24 * 60 * 60)) {
// Don't convert and risk going past the epoch.
return;
}
if (t < this->dts_local_offset_valid || t >= this->dts_local_offset_expiry)
{
time_t new_gmt;
localtime_r(&t, &tm_out.et_tm);
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm_out.et_tm.tm_zone = nullptr;
#endif
tm_out.et_tm.tm_isdst = 0;
new_gmt = tm2sec(&tm_out.et_tm);
this->dts_local_offset_cache = t - new_gmt;
this->dts_local_offset_valid = t;
this->dts_local_offset_expiry = t + (EXPIRE_TIME - 1);
this->dts_local_offset_expiry
-= this->dts_local_offset_expiry % EXPIRE_TIME;
} else {
time_t adjust_gmt = t - this->dts_local_offset_cache;
gmtime_r(&adjust_gmt, &tm_out.et_tm);
}
}
<commit_msg>[build] missing include<commit_after>/**
* Copyright (c) 2020, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file date_time_scanner.cc
*/
#include <chrono>
#include "date_time_scanner.hh"
#include "config.h"
#include "ptimec.hh"
size_t
date_time_scanner::ftime(char* dst,
size_t len,
const char* const time_fmt[],
const exttm& tm) const
{
off_t off = 0;
if (time_fmt == nullptr) {
PTIMEC_FORMATS[this->dts_fmt_lock].pf_ffunc(dst, off, len, tm);
if (tm.et_flags & ETF_MILLIS_SET) {
dst[off++] = '.';
ftime_L(dst, off, len, tm);
} else if (tm.et_flags & ETF_MICROS_SET) {
dst[off++] = '.';
ftime_f(dst, off, len, tm);
} else if (tm.et_flags & ETF_NANOS_SET) {
dst[off++] = '.';
ftime_N(dst, off, len, tm);
}
dst[off] = '\0';
} else {
off = ftime_fmt(dst, len, time_fmt[this->dts_fmt_lock], tm);
}
return (size_t) off;
}
bool
next_format(const char* const fmt[], int& index, int& locked_index)
{
bool retval = true;
if (locked_index == -1) {
index += 1;
if (fmt[index] == nullptr) {
retval = false;
}
} else if (index == locked_index) {
retval = false;
} else {
index = locked_index;
}
return retval;
}
const char*
date_time_scanner::scan(const char* time_dest,
size_t time_len,
const char* const time_fmt[],
struct exttm* tm_out,
struct timeval& tv_out,
bool convert_local)
{
int curr_time_fmt = -1;
bool found = false;
const char* retval = nullptr;
if (!time_fmt) {
time_fmt = PTIMEC_FORMAT_STR;
}
while (next_format(time_fmt, curr_time_fmt, this->dts_fmt_lock)) {
*tm_out = this->dts_base_tm;
tm_out->et_flags = 0;
if (time_len > 1 && time_dest[0] == '+' && isdigit(time_dest[1])) {
char time_cp[time_len + 1];
int gmt_int, off;
retval = nullptr;
memcpy(time_cp, time_dest, time_len);
time_cp[time_len] = '\0';
if (sscanf(time_cp, "+%d%n", &gmt_int, &off) == 1) {
time_t gmt = gmt_int;
if (convert_local && this->dts_local_time) {
localtime_r(&gmt, &tm_out->et_tm);
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm_out->et_tm.tm_zone = nullptr;
#endif
tm_out->et_tm.tm_isdst = 0;
gmt = tm2sec(&tm_out->et_tm);
}
tv_out.tv_sec = gmt;
tv_out.tv_usec = 0;
tm_out->et_flags = ETF_DAY_SET | ETF_MONTH_SET | ETF_YEAR_SET
| ETF_MACHINE_ORIENTED | ETF_EPOCH_TIME;
this->dts_fmt_lock = curr_time_fmt;
this->dts_fmt_len = off;
retval = time_dest + off;
found = true;
break;
}
} else if (time_fmt == PTIMEC_FORMAT_STR) {
ptime_func func = PTIMEC_FORMATS[curr_time_fmt].pf_func;
off_t off = 0;
#ifdef HAVE_STRUCT_TM_TM_ZONE
if (!this->dts_keep_base_tz) {
tm_out->et_tm.tm_zone = nullptr;
}
#endif
if (func(tm_out, time_dest, off, time_len)) {
retval = &time_dest[off];
if (tm_out->et_tm.tm_year < 70) {
tm_out->et_tm.tm_year = 80;
}
if (convert_local
&& (this->dts_local_time
|| tm_out->et_flags & ETF_EPOCH_TIME))
{
time_t gmt = tm2sec(&tm_out->et_tm);
this->to_localtime(gmt, *tm_out);
}
tv_out.tv_sec = tm2sec(&tm_out->et_tm);
tv_out.tv_usec = tm_out->et_nsec / 1000;
secs2wday(tv_out, &tm_out->et_tm);
this->dts_fmt_lock = curr_time_fmt;
this->dts_fmt_len = retval - time_dest;
found = true;
break;
}
} else {
off_t off = 0;
#ifdef HAVE_STRUCT_TM_TM_ZONE
if (!this->dts_keep_base_tz) {
tm_out->et_tm.tm_zone = nullptr;
}
#endif
if (ptime_fmt(
time_fmt[curr_time_fmt], tm_out, time_dest, off, time_len)
&& (time_dest[off] == '.' || time_dest[off] == ','
|| off == (off_t) time_len))
{
retval = &time_dest[off];
if (tm_out->et_tm.tm_year < 70) {
tm_out->et_tm.tm_year = 80;
}
if (convert_local
&& (this->dts_local_time
|| tm_out->et_flags & ETF_EPOCH_TIME))
{
time_t gmt = tm2sec(&tm_out->et_tm);
this->to_localtime(gmt, *tm_out);
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm_out->et_tm.tm_zone = nullptr;
#endif
tm_out->et_tm.tm_isdst = 0;
}
tv_out.tv_sec = tm2sec(&tm_out->et_tm);
tv_out.tv_usec = tm_out->et_nsec / 1000;
secs2wday(tv_out, &tm_out->et_tm);
this->dts_fmt_lock = curr_time_fmt;
this->dts_fmt_len = retval - time_dest;
found = true;
break;
}
}
}
if (!found) {
retval = nullptr;
}
if (retval != nullptr) {
/* Try to pull out the milli/micro-second value. */
if (retval[0] == '.' || retval[0] == ',') {
off_t off = (retval - time_dest) + 1;
if (ptime_N(tm_out, time_dest, off, time_len)) {
tv_out.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::nanoseconds{tm_out->et_nsec})
.count();
this->dts_fmt_len += 10;
tm_out->et_flags |= ETF_NANOS_SET;
retval += 10;
} else if (ptime_f(tm_out, time_dest, off, time_len)) {
tv_out.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::nanoseconds{tm_out->et_nsec})
.count();
this->dts_fmt_len += 7;
tm_out->et_flags |= ETF_MICROS_SET;
retval += 7;
} else if (ptime_L(tm_out, time_dest, off, time_len)) {
tv_out.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::nanoseconds{tm_out->et_nsec})
.count();
this->dts_fmt_len += 4;
tm_out->et_flags |= ETF_MILLIS_SET;
retval += 4;
}
}
}
return retval;
}
void
date_time_scanner::to_localtime(time_t t, exttm& tm_out)
{
if (t < (24 * 60 * 60)) {
// Don't convert and risk going past the epoch.
return;
}
if (t < this->dts_local_offset_valid || t >= this->dts_local_offset_expiry)
{
time_t new_gmt;
localtime_r(&t, &tm_out.et_tm);
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm_out.et_tm.tm_zone = nullptr;
#endif
tm_out.et_tm.tm_isdst = 0;
new_gmt = tm2sec(&tm_out.et_tm);
this->dts_local_offset_cache = t - new_gmt;
this->dts_local_offset_valid = t;
this->dts_local_offset_expiry = t + (EXPIRE_TIME - 1);
this->dts_local_offset_expiry
-= this->dts_local_offset_expiry % EXPIRE_TIME;
} else {
time_t adjust_gmt = t - this->dts_local_offset_cache;
gmtime_r(&adjust_gmt, &tm_out.et_tm);
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2014 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Config.h"
#include "Control.h"
#include "Log.h"
#include "System.h"
namespace dagon {
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void System::browse(const char* url) {
// TODO: Re-implement
log.warning(kModSystem, "Browsing is currently disabled");
}
#ifdef DAGON_MAC
namespace {
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
}
void System::findPaths() {
CFURLRef mainRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFURLRef parentRef = CFURLCreateCopyDeletingLastPathComponent(NULL, mainRef);
CFStringRef macPath = CFURLCopyFileSystemPath(parentRef, kCFURLPOSIXPathStyle);
const char *pathPtr = CFStringGetCStringPtr(macPath,
CFStringGetSystemEncoding());
chdir(pathPtr);
}
#else
void System::findPaths() {
// Nothing to do for now
}
#endif
bool System::init() {
log.trace(kModSystem, "%s", kString13001);
SDL_version version;
SDL_GetVersion(&version);
log.info(kModSystem, "%s: %d.%d", kString13003,
version.major, version.minor);
SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO | SDL_INIT_TIMER);
Uint32 videoFlags = SDL_WINDOW_OPENGL;
if (!config.displayWidth || !config.displayHeight) {
if (config.fullscreen) {
SDL_DisplayMode displayMode;
SDL_GetCurrentDisplayMode(0, &displayMode);
config.displayWidth = displayMode.w;
config.displayHeight = displayMode.h;
videoFlags = videoFlags | SDL_WINDOW_FULLSCREEN;
} else {
// Use a third of the screen
SDL_DisplayMode desktopMode;
SDL_GetDesktopDisplayMode(0, &desktopMode);
config.displayWidth = static_cast<int>(desktopMode.w / 1.5f);
config.displayHeight = static_cast<int>(desktopMode.h / 1.5f);
videoFlags = videoFlags | SDL_WINDOW_RESIZABLE;
}
} else {
if (config.fullscreen) {
videoFlags = videoFlags | SDL_WINDOW_FULLSCREEN;
} else {
videoFlags = videoFlags | SDL_WINDOW_RESIZABLE;
}
}
_window = SDL_CreateWindow("Dagon", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
config.displayWidth, config.displayHeight,
videoFlags | SDL_WINDOW_ALLOW_HIGHDPI);
_context = SDL_GL_CreateContext(_window);
if (!_window) {
log.error(kModSystem, "%s", kString13010);
return false;
}
// Set vertical sync according to our configuration
SDL_GL_SetSwapInterval(config.verticalSync);
// Force our own frame limiter on if vertical sync wasn't enabled
if (!SDL_GL_GetSwapInterval())
config.frameLimiter = true;
SDL_WarpMouseInWindow(_window, config.displayWidth >> 1,
config.displayHeight >> 1);
SDL_ShowCursor(false);
return true;
}
void System::setTitle(const char* title) {
SDL_SetWindowTitle(_window, title);
}
void System::update() {
config.setFramesPerSecond(_calculateFrames(kFrameratePrecision));
SDL_GL_SwapWindow(_window);
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN: {
switch (event.key.keysym.sym) {
case SDLK_F1:
case SDLK_F2:
case SDLK_F3:
case SDLK_F4:
case SDLK_F5:
case SDLK_F6:
case SDLK_F7:
case SDLK_F8:
case SDLK_F9:
case SDLK_F10:
case SDLK_F11:
case SDLK_F12:
Control::instance().processFunctionKey(event.key.keysym.sym);
break;
case SDLK_BACKSPACE:
case SDLK_ESCAPE:
case SDLK_TAB:
case SDLK_RETURN:
Control::instance().processKey(event.key.keysym.sym,
EventKeyDown);
break;
case SDLK_f:
SDL_Keymod modified = SDL_GetModState();
if (modified & (KMOD_LALT | KMOD_LCTRL | KMOD_LGUI))
this->toggleFullscreen();
break;
}
break;
}
/*case SDL_KEYUP: {
switch (event.key.keysym.sym) {
case SDLK_w:
case SDLK_a:
case SDLK_s:
case SDLK_d:
Control::instance().processKey(event.key.keysym.sym,
EventKeyUp);
break;
}
}*/
case SDL_MOUSEMOTION:
Control::instance().processMouse(event.motion.x,
event.motion.y,
EventMouseMove);
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseDown);
} else if (event.button.button == SDL_BUTTON_RIGHT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseRightDown);
}
break;
case SDL_MOUSEBUTTONUP:
if (event.button.button == SDL_BUTTON_LEFT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseUp);
} else if (event.button.button == SDL_BUTTON_RIGHT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseRightUp);
}
break;
case SDL_TEXTINPUT:
Control::instance().processKey(event.text.text[0],
EventKeyDown);
break;
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_CLOSE:
Control::instance().terminate();
break;
case SDL_WINDOWEVENT_LEAVE:
Control::instance().processMouse(config.displayWidth >> 1,
config.displayHeight >> 1,
EventMouseMove);
break;
case SDL_WINDOWEVENT_RESIZED:
Control::instance().reshape(event.window.data1,
event.window.data2);
break;
default:
break;
}
break;
default:
break;
}
}
if (config.controlMode == kControlFixed) {
if (Control::instance().isDirectControlActive()) {
double currentTime = SDL_GetTicks();
static double lastTime = currentTime;
if ((currentTime - lastTime) >= 100) {
SDL_WarpMouseInWindow(_window, config.displayWidth >> 1,
config.displayHeight >> 1);
lastTime = SDL_GetTicks();
}
}
}
}
void System::terminate() {
SDL_GL_DeleteContext(_context);
if (config.fullscreen)
SDL_SetWindowFullscreen(_window, 0);
SDL_DestroyWindow(_window);
SDL_Quit();
}
void System::toggleFullscreen() {
config.fullscreen = !config.fullscreen;
if (config.fullscreen) {
SDL_DisplayMode desktopMode;
SDL_GetDesktopDisplayMode(0, &desktopMode);
SDL_SetWindowPosition(_window, 0, 0);
SDL_SetWindowSize(_window, desktopMode.w, desktopMode.h);
SDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN);
SDL_ShowCursor(false);
} else {
SDL_SetWindowFullscreen(_window, 0);
}
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
// TODO: For best precision, this should be suspended when
// performing a switch (the most expensive operation)
double System::_calculateFrames(double theInterval = 1.0) {
static double lastTime = SDL_GetTicks() / 1000;
static int fpsFrameCount = 0;
static double fps = 0.0;
double currentTime = SDL_GetTicks() / 1000;
if (theInterval < 0.1)
theInterval = 0.1;
if (theInterval > 10.0)
theInterval = 10.0;
if ((currentTime - lastTime) > theInterval) {
fps = (double)fpsFrameCount / (currentTime - lastTime);
fpsFrameCount = 0;
lastTime = SDL_GetTicks() / 1000;
}
else fpsFrameCount++;
return fps;
}
}
<commit_msg>Rewrite window code to better handle high dpi (#170)<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2014 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Config.h"
#include "Control.h"
#include "Log.h"
#include "System.h"
namespace dagon {
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void System::browse(const char* url) {
// TODO: Re-implement
log.warning(kModSystem, "Browsing is currently disabled");
}
#ifdef DAGON_MAC
namespace {
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
}
void System::findPaths() {
CFURLRef mainRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFURLRef parentRef = CFURLCreateCopyDeletingLastPathComponent(NULL, mainRef);
CFStringRef macPath = CFURLCopyFileSystemPath(parentRef, kCFURLPOSIXPathStyle);
const char *pathPtr = CFStringGetCStringPtr(macPath,
CFStringGetSystemEncoding());
chdir(pathPtr);
}
#else
void System::findPaths() {
// Nothing to do for now
}
#endif
bool System::init() {
log.trace(kModSystem, "%s", kString13001);
SDL_version version;
SDL_GetVersion(&version);
log.info(kModSystem, "%s: %d.%d", kString13003,
version.major, version.minor);
SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO | SDL_INIT_TIMER);
Uint32 videoFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
bool forcedRes = true;
if (!config.displayWidth || !config.displayHeight) {
// Use a third of the screen
SDL_DisplayMode desktopMode;
SDL_GetDesktopDisplayMode(0, &desktopMode);
config.displayWidth = static_cast<int>(desktopMode.w / 1.5f);
config.displayHeight = static_cast<int>(desktopMode.h / 1.5f);
forcedRes = false;
}
_window = SDL_CreateWindow("Dagon", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
config.displayWidth, config.displayHeight,
videoFlags);
_context = SDL_GL_CreateContext(_window);
if (!_window) {
log.error(kModSystem, "%s", kString13010);
return false;
}
if (config.fullscreen) {
int width = config.displayWidth;
int height = config.displayHeight;
if (!forcedRes) {
SDL_DisplayMode desktopMode;
SDL_GetDesktopDisplayMode(0, &desktopMode);
width = desktopMode.w;
height = desktopMode.h;
}
SDL_SetWindowPosition(_window, 0, 0);
SDL_SetWindowSize(_window, width, height);
SDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN);
}
// Set vertical sync according to our configuration
SDL_GL_SetSwapInterval(config.verticalSync);
// Force our own frame limiter on if vertical sync wasn't enabled
if (!SDL_GL_GetSwapInterval())
config.frameLimiter = true;
SDL_WarpMouseInWindow(_window, config.displayWidth >> 1,
config.displayHeight >> 1);
SDL_ShowCursor(false);
return true;
}
void System::setTitle(const char* title) {
SDL_SetWindowTitle(_window, title);
}
void System::update() {
config.setFramesPerSecond(_calculateFrames(kFrameratePrecision));
SDL_GL_SwapWindow(_window);
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN: {
switch (event.key.keysym.sym) {
case SDLK_F1:
case SDLK_F2:
case SDLK_F3:
case SDLK_F4:
case SDLK_F5:
case SDLK_F6:
case SDLK_F7:
case SDLK_F8:
case SDLK_F9:
case SDLK_F10:
case SDLK_F11:
case SDLK_F12:
Control::instance().processFunctionKey(event.key.keysym.sym);
break;
case SDLK_BACKSPACE:
case SDLK_ESCAPE:
case SDLK_TAB:
case SDLK_RETURN:
Control::instance().processKey(event.key.keysym.sym,
EventKeyDown);
break;
case SDLK_f:
SDL_Keymod modified = SDL_GetModState();
if (modified & (KMOD_LALT | KMOD_LCTRL | KMOD_LGUI))
this->toggleFullscreen();
break;
}
break;
}
/*case SDL_KEYUP: {
switch (event.key.keysym.sym) {
case SDLK_w:
case SDLK_a:
case SDLK_s:
case SDLK_d:
Control::instance().processKey(event.key.keysym.sym,
EventKeyUp);
break;
}
}*/
case SDL_MOUSEMOTION:
Control::instance().processMouse(event.motion.x,
event.motion.y,
EventMouseMove);
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseDown);
} else if (event.button.button == SDL_BUTTON_RIGHT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseRightDown);
}
break;
case SDL_MOUSEBUTTONUP:
if (event.button.button == SDL_BUTTON_LEFT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseUp);
} else if (event.button.button == SDL_BUTTON_RIGHT) {
Control::instance().processMouse(event.button.x,
event.button.y,
EventMouseRightUp);
}
break;
case SDL_TEXTINPUT:
Control::instance().processKey(event.text.text[0],
EventKeyDown);
break;
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_CLOSE:
Control::instance().terminate();
break;
case SDL_WINDOWEVENT_LEAVE:
Control::instance().processMouse(config.displayWidth >> 1,
config.displayHeight >> 1,
EventMouseMove);
break;
case SDL_WINDOWEVENT_RESIZED:
int w, h;
SDL_GetWindowSize(_window, &w, &h);
Control::instance().reshape(w, h);
break;
default:
break;
}
break;
default:
break;
}
}
if (config.controlMode == kControlFixed) {
if (Control::instance().isDirectControlActive()) {
double currentTime = SDL_GetTicks();
static double lastTime = currentTime;
if ((currentTime - lastTime) >= 100) {
SDL_WarpMouseInWindow(_window, config.displayWidth >> 1,
config.displayHeight >> 1);
lastTime = SDL_GetTicks();
}
}
}
}
void System::terminate() {
SDL_GL_DeleteContext(_context);
if (config.fullscreen)
SDL_SetWindowFullscreen(_window, 0);
SDL_DestroyWindow(_window);
SDL_Quit();
}
void System::toggleFullscreen() {
config.fullscreen = !config.fullscreen;
if (config.fullscreen) {
SDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN_DESKTOP);
} else {
SDL_SetWindowFullscreen(_window, 0);
SDL_DisplayMode desktopMode;
SDL_GetDesktopDisplayMode(0, &desktopMode);
SDL_SetWindowPosition(_window, 10, 10);
SDL_SetWindowSize(_window, desktopMode.w, desktopMode.h);
}
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
// TODO: For best precision, this should be suspended when
// performing a switch (the most expensive operation)
double System::_calculateFrames(double theInterval = 1.0) {
static double lastTime = SDL_GetTicks() / 1000;
static int fpsFrameCount = 0;
static double fps = 0.0;
double currentTime = SDL_GetTicks() / 1000;
if (theInterval < 0.1)
theInterval = 0.1;
if (theInterval > 10.0)
theInterval = 10.0;
if ((currentTime - lastTime) > theInterval) {
fps = (double)fpsFrameCount / (currentTime - lastTime);
fpsFrameCount = 0;
lastTime = SDL_GetTicks() / 1000;
}
else fpsFrameCount++;
return fps;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "Target.h"
#include "Debug.h"
#include "Error.h"
#include "LLVM_Headers.h"
#include "Util.h"
namespace Halide {
using std::string;
using std::vector;
namespace {
#ifndef __arm__
#ifdef _MSC_VER
static void cpuid(int info[4], int infoType, int extra) {
__cpuidex(info, infoType, extra);
}
#else
// CPU feature detection code taken from ispc
// (https://github.com/ispc/ispc/blob/master/builtins/dispatch.ll)
#ifdef _LP64
static void cpuid(int info[4], int infoType, int extra) {
__asm__ __volatile__ (
"cpuid \n\t"
: "=a" (info[0]), "=b" (info[1]), "=c" (info[2]), "=d" (info[3])
: "0" (infoType), "2" (extra));
}
#else
static void cpuid(int info[4], int infoType, int extra) {
// We save %ebx in case it's the PIC register
__asm__ __volatile__ (
"mov{l}\t{%%}ebx, %1 \n\t"
"cpuid \n\t"
"xchg{l}\t{%%}ebx, %1 \n\t"
: "=a" (info[0]), "=r" (info[1]), "=c" (info[2]), "=d" (info[3])
: "0" (infoType), "2" (extra));
}
#endif
#endif
#endif
}
Target get_host_target() {
Target::OS os = Target::OSUnknown;
#ifdef __linux__
os = Target::Linux;
#endif
#ifdef _MSC_VER
os = Target::Windows;
#endif
#ifdef __APPLE__
os = Target::OSX;
#endif
bool use_64_bits = (sizeof(size_t) == 8);
int bits = use_64_bits ? 64 : 32;
#if __mips__ || __mips || __MIPS__
Target::Arch arch = Target::MIPS;
return Target(os, arch, bits);
#else
#ifdef __arm__
Target::Arch arch = Target::ARM;
return Target(os, arch, bits);
#else
Target::Arch arch = Target::X86;
int info[4];
cpuid(info, 1, 0);
bool have_sse41 = info[2] & (1 << 19);
bool have_sse2 = info[3] & (1 << 26);
bool have_avx = info[2] & (1 << 28);
bool have_f16c = info[2] & (1 << 29);
bool have_rdrand = info[2] & (1 << 30);
bool have_fma = info[2] & (1 << 12);
user_assert(have_sse2)
<< "The x86 backend assumes at least sse2 support. This machine does not appear to have sse2.\n"
<< "cpuid returned: "
<< std::hex << info[0]
<< ", " << info[1]
<< ", " << info[2]
<< ", " << info[3]
<< std::dec << "\n";
std::vector<Target::Feature> initial_features;
if (have_sse41) initial_features.push_back(Target::SSE41);
if (have_avx) initial_features.push_back(Target::AVX);
if (have_f16c) initial_features.push_back(Target::F16C);
if (have_fma) initial_features.push_back(Target::FMA);
if (use_64_bits && have_avx && have_f16c && have_rdrand) {
// So far, so good. AVX2?
// Call cpuid with eax=7, ecx=0
int info2[4];
cpuid(info2, 7, 0);
bool have_avx2 = info[1] & (1 << 5);
if (have_avx2) {
initial_features.push_back(Target::AVX2);
}
}
return Target(os, arch, bits, initial_features);
#endif
#endif
}
namespace {
string get_env(const char *name) {
#ifdef _WIN32
char buf[128];
size_t read = 0;
getenv_s(&read, buf, name);
if (read) {
return string(buf);
} else {
return "";
}
#else
char *buf = getenv(name);
if (buf) {
return string(buf);
} else {
return "";
}
#endif
}
const std::map<std::string, Target::OS> os_name_map = {
{"os_unknown", Target::OSUnknown},
{"linux", Target::Linux},
{"windows", Target::Windows},
{"osx", Target::OSX},
{"android", Target::Android},
{"ios", Target::IOS},
{"nacl", Target::NaCl},
};
bool lookup_os(const std::string &tok, Target::OS &result) {
auto os_iter = os_name_map.find(tok);
if (os_iter != os_name_map.end()) {
result = os_iter->second;
return true;
}
return false;
}
const std::map<std::string, Target::Arch> arch_name_map = {
{"arch_unknown", Target::ArchUnknown},
{"x86", Target::X86},
{"arm", Target::ARM},
{"pnacl", Target::PNaCl},
{"mips", Target::MIPS},
};
bool lookup_arch(const std::string &tok, Target::Arch &result) {
auto arch_iter = arch_name_map.find(tok);
if (arch_iter != arch_name_map.end()) {
result = arch_iter->second;
return true;
}
return false;
}
const std::map<std::string, Target::Feature> feature_name_map = {
{"jit", Target::JIT},
{"debug", Target::Debug},
{"no_asserts", Target::NoAsserts},
{"no_bounds_query", Target::NoBoundsQuery},
{"sse41", Target::SSE41},
{"avx", Target::AVX},
{"avx2", Target::AVX2},
{"fma", Target::FMA},
{"fma4", Target::FMA4},
{"f16c", Target::F16C},
{"armv7s", Target::ARMv7s},
{"no_neon", Target::NoNEON},
{"cuda", Target::CUDA},
{"cuda_capability_30", Target::CUDACapability30},
{"cuda_capability_32", Target::CUDACapability32},
{"cuda_capability_35", Target::CUDACapability35},
{"cuda_capability_50", Target::CUDACapability50},
{"opencl", Target::OpenCL},
{"cl_doubles", Target::CLDoubles},
{"opengl", Target::OpenGL},
{"openglcompute", Target::OpenGLCompute},
{"renderscript", Target::Renderscript},
{"user_context", Target::UserContext},
{"register_metadata", Target::RegisterMetadata},
{"matlab", Target::Matlab},
{"profile", Target::Profile},
{"no_runtime", Target::NoRuntime},
{"metal", Target::Metal},
};
bool lookup_feature(const std::string &tok, Target::Feature &result) {
auto feature_iter = feature_name_map.find(tok);
if (feature_iter != feature_name_map.end()) {
result = feature_iter->second;
return true;
}
return false;
}
} // End anonymous namespace
Target get_target_from_environment() {
string target = get_env("HL_TARGET");
if (target.empty()) {
return get_host_target();
} else {
return parse_target_string(target);
}
}
Target get_jit_target_from_environment() {
Target host = get_host_target();
host.set_feature(Target::JIT);
string target = get_env("HL_JIT_TARGET");
if (target.empty()) {
return host;
} else {
Target t = parse_target_string(target);
t.set_feature(Target::JIT);
user_assert(t.os == host.os && t.arch == host.arch && t.bits == host.bits)
<< "HL_JIT_TARGET must match the host OS, architecture, and bit width.\n"
<< "HL_JIT_TARGET was " << target << ". "
<< "Host is " << host.to_string() << ".\n";
return t;
}
}
Target parse_target_string(const std::string &target) {
Target host = get_host_target();
if (target.empty()) {
// If nothing is specified, use the host target.
return host;
}
// Default to the host OS and architecture.
Target t;
t.os = host.os;
t.arch = host.arch;
t.bits = host.bits;
if (!t.merge_string(target)) {
const char *separator = "";
std::string architectures;
for (auto arch_iter = arch_name_map.begin(); arch_iter != arch_name_map.end(); arch_iter++) {
architectures += separator + arch_iter->first;
separator = ", ";
}
separator = "";
std::string oses;
for (auto os_iter = os_name_map.begin(); os_iter != os_name_map.end(); os_iter++) {
oses += separator + os_iter->first;
separator = ", ";
}
separator = "";
// Format the features to go one feature over 70 characters per line,
// assume the first line starts with "Features are ".
int line_char_start = -(int)sizeof("Features are");
std::string features;
for (auto feature_iter = feature_name_map.begin(); feature_iter != feature_name_map.end(); feature_iter++) {
features += separator + feature_iter->first;
if (features.length() - line_char_start > 70) {
separator = "\n";
line_char_start = features.length();
} else {
separator = ", ";
}
}
user_error << "Did not understand HL_TARGET=" << target << "\n"
<< "Expected format is arch-os-feature1-feature2-...\n"
<< "Where arch is " << architectures << " .\n"
<< "Os is " << oses << " .\n"
<< "If arch or os are omitted, they default to the host.\n"
<< "Features are " << features << " .\n"
<< "HL_TARGET can also begin with \"host\", which sets the "
<< "host's architecture, os, and feature set, with the "
<< "exception of the GPU runtimes, which default to off.\n"
<< "On this platform, the host target is: " << host.to_string() << "\n";
}
return t;
}
bool Target::merge_string(const std::string &target) {
string rest = target;
vector<string> tokens;
size_t first_dash;
while ((first_dash = rest.find('-')) != string::npos) {
//Internal::debug(0) << first_dash << ", " << rest << "\n";
tokens.push_back(rest.substr(0, first_dash));
rest = rest.substr(first_dash + 1);
}
tokens.push_back(rest);
bool os_specified = false, arch_specified = false, bits_specified = false;
for (size_t i = 0; i < tokens.size(); i++) {
const string &tok = tokens[i];
Target::Feature feature;
if (tok == "host") {
if (i > 0) {
// "host" is now only allowed as the first token.
return false;
}
*this = get_host_target();
} else if (tok == "32" || tok == "64") {
if (bits_specified) {
return false;
}
bits_specified = true;
bits = std::stoi(tok);
} else if (lookup_arch(tok, arch)) {
if (arch_specified) {
return false;
}
arch_specified = true;
} else if (lookup_os(tok, os)) {
if (os_specified) {
return false;
}
os_specified = true;
} else if (lookup_feature(tok, feature)) {
set_feature(feature);
} else {
return false;
}
}
if (arch_specified && !bits_specified) {
return false;
}
// If arch is PNaCl, require explicit setting of os and bits as well.
if (arch_specified && arch == Target::PNaCl) {
if (!os_specified || os != Target::NaCl) {
return false;
}
if (!bits_specified || bits != 32) {
return false;
}
}
return true;
}
std::string Target::to_string() const {
string result;
for (auto const &arch_entry : arch_name_map) {
if (arch_entry.second == arch) {
result += arch_entry.first;
break;
}
}
result += "-" + std::to_string(bits);
for (auto const &os_entry : os_name_map) {
if (os_entry.second == os) {
result += "-" + os_entry.first;
break;
}
}
for (auto const &feature_entry : feature_name_map) {
if (has_feature(feature_entry.second)) {
result += "-" + feature_entry.first;
}
}
return result;
}
namespace Internal{
EXPORT void target_test() {
Target t;
for (auto const &feature : feature_name_map) {
t.set_feature(feature.second);
}
for (int i = 0; i < (int)(Target::FeatureEnd); i++) {
internal_assert(t.has_feature((Target::Feature)i)) << "Feature " << i << " not in feature_names_map.\n";
}
std::cout << "Target test passed" << std::endl;
}
}
}
<commit_msg>Switch to uniform use of range based for loops for iterating name maps.<commit_after>#include <iostream>
#include <string>
#include "Target.h"
#include "Debug.h"
#include "Error.h"
#include "LLVM_Headers.h"
#include "Util.h"
namespace Halide {
using std::string;
using std::vector;
namespace {
#ifndef __arm__
#ifdef _MSC_VER
static void cpuid(int info[4], int infoType, int extra) {
__cpuidex(info, infoType, extra);
}
#else
// CPU feature detection code taken from ispc
// (https://github.com/ispc/ispc/blob/master/builtins/dispatch.ll)
#ifdef _LP64
static void cpuid(int info[4], int infoType, int extra) {
__asm__ __volatile__ (
"cpuid \n\t"
: "=a" (info[0]), "=b" (info[1]), "=c" (info[2]), "=d" (info[3])
: "0" (infoType), "2" (extra));
}
#else
static void cpuid(int info[4], int infoType, int extra) {
// We save %ebx in case it's the PIC register
__asm__ __volatile__ (
"mov{l}\t{%%}ebx, %1 \n\t"
"cpuid \n\t"
"xchg{l}\t{%%}ebx, %1 \n\t"
: "=a" (info[0]), "=r" (info[1]), "=c" (info[2]), "=d" (info[3])
: "0" (infoType), "2" (extra));
}
#endif
#endif
#endif
}
Target get_host_target() {
Target::OS os = Target::OSUnknown;
#ifdef __linux__
os = Target::Linux;
#endif
#ifdef _MSC_VER
os = Target::Windows;
#endif
#ifdef __APPLE__
os = Target::OSX;
#endif
bool use_64_bits = (sizeof(size_t) == 8);
int bits = use_64_bits ? 64 : 32;
#if __mips__ || __mips || __MIPS__
Target::Arch arch = Target::MIPS;
return Target(os, arch, bits);
#else
#ifdef __arm__
Target::Arch arch = Target::ARM;
return Target(os, arch, bits);
#else
Target::Arch arch = Target::X86;
int info[4];
cpuid(info, 1, 0);
bool have_sse41 = info[2] & (1 << 19);
bool have_sse2 = info[3] & (1 << 26);
bool have_avx = info[2] & (1 << 28);
bool have_f16c = info[2] & (1 << 29);
bool have_rdrand = info[2] & (1 << 30);
bool have_fma = info[2] & (1 << 12);
user_assert(have_sse2)
<< "The x86 backend assumes at least sse2 support. This machine does not appear to have sse2.\n"
<< "cpuid returned: "
<< std::hex << info[0]
<< ", " << info[1]
<< ", " << info[2]
<< ", " << info[3]
<< std::dec << "\n";
std::vector<Target::Feature> initial_features;
if (have_sse41) initial_features.push_back(Target::SSE41);
if (have_avx) initial_features.push_back(Target::AVX);
if (have_f16c) initial_features.push_back(Target::F16C);
if (have_fma) initial_features.push_back(Target::FMA);
if (use_64_bits && have_avx && have_f16c && have_rdrand) {
// So far, so good. AVX2?
// Call cpuid with eax=7, ecx=0
int info2[4];
cpuid(info2, 7, 0);
bool have_avx2 = info[1] & (1 << 5);
if (have_avx2) {
initial_features.push_back(Target::AVX2);
}
}
return Target(os, arch, bits, initial_features);
#endif
#endif
}
namespace {
string get_env(const char *name) {
#ifdef _WIN32
char buf[128];
size_t read = 0;
getenv_s(&read, buf, name);
if (read) {
return string(buf);
} else {
return "";
}
#else
char *buf = getenv(name);
if (buf) {
return string(buf);
} else {
return "";
}
#endif
}
const std::map<std::string, Target::OS> os_name_map = {
{"os_unknown", Target::OSUnknown},
{"linux", Target::Linux},
{"windows", Target::Windows},
{"osx", Target::OSX},
{"android", Target::Android},
{"ios", Target::IOS},
{"nacl", Target::NaCl},
};
bool lookup_os(const std::string &tok, Target::OS &result) {
auto os_iter = os_name_map.find(tok);
if (os_iter != os_name_map.end()) {
result = os_iter->second;
return true;
}
return false;
}
const std::map<std::string, Target::Arch> arch_name_map = {
{"arch_unknown", Target::ArchUnknown},
{"x86", Target::X86},
{"arm", Target::ARM},
{"pnacl", Target::PNaCl},
{"mips", Target::MIPS},
};
bool lookup_arch(const std::string &tok, Target::Arch &result) {
auto arch_iter = arch_name_map.find(tok);
if (arch_iter != arch_name_map.end()) {
result = arch_iter->second;
return true;
}
return false;
}
const std::map<std::string, Target::Feature> feature_name_map = {
{"jit", Target::JIT},
{"debug", Target::Debug},
{"no_asserts", Target::NoAsserts},
{"no_bounds_query", Target::NoBoundsQuery},
{"sse41", Target::SSE41},
{"avx", Target::AVX},
{"avx2", Target::AVX2},
{"fma", Target::FMA},
{"fma4", Target::FMA4},
{"f16c", Target::F16C},
{"armv7s", Target::ARMv7s},
{"no_neon", Target::NoNEON},
{"cuda", Target::CUDA},
{"cuda_capability_30", Target::CUDACapability30},
{"cuda_capability_32", Target::CUDACapability32},
{"cuda_capability_35", Target::CUDACapability35},
{"cuda_capability_50", Target::CUDACapability50},
{"opencl", Target::OpenCL},
{"cl_doubles", Target::CLDoubles},
{"opengl", Target::OpenGL},
{"openglcompute", Target::OpenGLCompute},
{"renderscript", Target::Renderscript},
{"user_context", Target::UserContext},
{"register_metadata", Target::RegisterMetadata},
{"matlab", Target::Matlab},
{"profile", Target::Profile},
{"no_runtime", Target::NoRuntime},
{"metal", Target::Metal},
};
bool lookup_feature(const std::string &tok, Target::Feature &result) {
auto feature_iter = feature_name_map.find(tok);
if (feature_iter != feature_name_map.end()) {
result = feature_iter->second;
return true;
}
return false;
}
} // End anonymous namespace
Target get_target_from_environment() {
string target = get_env("HL_TARGET");
if (target.empty()) {
return get_host_target();
} else {
return parse_target_string(target);
}
}
Target get_jit_target_from_environment() {
Target host = get_host_target();
host.set_feature(Target::JIT);
string target = get_env("HL_JIT_TARGET");
if (target.empty()) {
return host;
} else {
Target t = parse_target_string(target);
t.set_feature(Target::JIT);
user_assert(t.os == host.os && t.arch == host.arch && t.bits == host.bits)
<< "HL_JIT_TARGET must match the host OS, architecture, and bit width.\n"
<< "HL_JIT_TARGET was " << target << ". "
<< "Host is " << host.to_string() << ".\n";
return t;
}
}
Target parse_target_string(const std::string &target) {
Target host = get_host_target();
if (target.empty()) {
// If nothing is specified, use the host target.
return host;
}
// Default to the host OS and architecture.
Target t;
t.os = host.os;
t.arch = host.arch;
t.bits = host.bits;
if (!t.merge_string(target)) {
const char *separator = "";
std::string architectures;
for (auto const &arch_entry : arch_name_map) {
architectures += separator + arch_entry.first;
separator = ", ";
}
separator = "";
std::string oses;
for (auto os_entry : os_name_map) {
oses += separator + os_entry.first;
separator = ", ";
}
separator = "";
// Format the features to go one feature over 70 characters per line,
// assume the first line starts with "Features are ".
int line_char_start = -(int)sizeof("Features are");
std::string features;
for (auto feature_entry : feature_name_map) {
features += separator + feature_entry.first;
if (features.length() - line_char_start > 70) {
separator = "\n";
line_char_start = features.length();
} else {
separator = ", ";
}
}
user_error << "Did not understand HL_TARGET=" << target << "\n"
<< "Expected format is arch-os-feature1-feature2-...\n"
<< "Where arch is " << architectures << " .\n"
<< "Os is " << oses << " .\n"
<< "If arch or os are omitted, they default to the host.\n"
<< "Features are " << features << " .\n"
<< "HL_TARGET can also begin with \"host\", which sets the "
<< "host's architecture, os, and feature set, with the "
<< "exception of the GPU runtimes, which default to off.\n"
<< "On this platform, the host target is: " << host.to_string() << "\n";
}
return t;
}
bool Target::merge_string(const std::string &target) {
string rest = target;
vector<string> tokens;
size_t first_dash;
while ((first_dash = rest.find('-')) != string::npos) {
//Internal::debug(0) << first_dash << ", " << rest << "\n";
tokens.push_back(rest.substr(0, first_dash));
rest = rest.substr(first_dash + 1);
}
tokens.push_back(rest);
bool os_specified = false, arch_specified = false, bits_specified = false;
for (size_t i = 0; i < tokens.size(); i++) {
const string &tok = tokens[i];
Target::Feature feature;
if (tok == "host") {
if (i > 0) {
// "host" is now only allowed as the first token.
return false;
}
*this = get_host_target();
} else if (tok == "32" || tok == "64") {
if (bits_specified) {
return false;
}
bits_specified = true;
bits = std::stoi(tok);
} else if (lookup_arch(tok, arch)) {
if (arch_specified) {
return false;
}
arch_specified = true;
} else if (lookup_os(tok, os)) {
if (os_specified) {
return false;
}
os_specified = true;
} else if (lookup_feature(tok, feature)) {
set_feature(feature);
} else {
return false;
}
}
if (arch_specified && !bits_specified) {
return false;
}
// If arch is PNaCl, require explicit setting of os and bits as well.
if (arch_specified && arch == Target::PNaCl) {
if (!os_specified || os != Target::NaCl) {
return false;
}
if (!bits_specified || bits != 32) {
return false;
}
}
return true;
}
std::string Target::to_string() const {
string result;
for (auto const &arch_entry : arch_name_map) {
if (arch_entry.second == arch) {
result += arch_entry.first;
break;
}
}
result += "-" + std::to_string(bits);
for (auto const &os_entry : os_name_map) {
if (os_entry.second == os) {
result += "-" + os_entry.first;
break;
}
}
for (auto const &feature_entry : feature_name_map) {
if (has_feature(feature_entry.second)) {
result += "-" + feature_entry.first;
}
}
return result;
}
namespace Internal{
EXPORT void target_test() {
Target t;
for (auto const &feature : feature_name_map) {
t.set_feature(feature.second);
}
for (int i = 0; i < (int)(Target::FeatureEnd); i++) {
internal_assert(t.has_feature((Target::Feature)i)) << "Feature " << i << " not in feature_names_map.\n";
}
std::cout << "Target test passed" << std::endl;
}
}
}
<|endoftext|> |
<commit_before>
#include <libclientserver.h>
void Timers::Start()
{
m_run = true;
Thread::Start();
}
void Timers::Stop()
{
if (m_timers.size() != 0)
abort(); //We still have active timers
m_run = false;
m_mutex.WakeUp(); //Tell thread to wakeup and exit
Thread::Stop();
}
void Timers::Add(ITimer *timer)
{
ScopedLock lock(&m_mutex);
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
abort();
struct timespec timeout;
timer->GetDelay(&timeout);
struct timespec expire;
Time::Add(&ts, &timeout, &expire);
unsigned long long curtime = Time::NanoSeconds(&expire);
m_timers.insert( std::pair<unsigned long long, ITimer *>(curtime, timer) );
m_mutex.WakeUp();
}
void Timers::Remove(ITimer *timer)
{
ScopedLock lock(&m_mutex);
std::multimap<unsigned long long, ITimer *>::iterator it = m_timers.begin();
while(it != m_timers.end())
{
if (it->second == timer)
{
m_timers.erase(it);
return;
}
it++;
}
m_mutex.WakeUp();
}
void Timers::Run()
{
m_mutex.Lock(); //We really only unlock when we are asleep
while(m_run == true)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
abort();
unsigned long long curtime = Time::NanoSeconds(&ts);
std::multimap<unsigned long long, ITimer *>::iterator it = m_timers.begin();
if (it == m_timers.end())
{
m_mutex.Wait(); //Wait forever on empty list until told otherwise
continue; //Restart
}
if (curtime < it->first)
{
unsigned long long diff = it->first - curtime;
struct timespec delay;
Time::TimeSpecFromNanoSeconds(diff, &delay);
m_mutex.Wait(&delay);
}
it = m_timers.begin();
if (it == m_timers.end())
continue; //All timers we removed while we were sleeping
if (curtime >= it->first)
{
ITimer *timer = it->second;
m_timers.erase(it);
timer->TimerExpired(this, timer);
continue;
}
}
m_mutex.Unlock();
}
<commit_msg>Fixed a few bugs. Mutex not being locked during WakeUp and current time needed to be updated after sleeping<commit_after>
#include <libclientserver.h>
void Timers::Start()
{
m_run = true;
Thread::Start();
}
void Timers::Stop()
{
if (m_timers.size() != 0)
abort(); //We still have active timers
m_run = false;
m_mutex.Lock();
m_mutex.WakeUp(); //Tell thread to wakeup and exit
m_mutex.Unlock();
Thread::Stop();
}
void Timers::Add(ITimer *timer)
{
struct timespec ts;
Time::MonoTonic(&ts);
struct timespec timeout;
timer->GetDelay(&timeout);
struct timespec expire;
Time::Add(&ts, &timeout, &expire);
unsigned long long curtime = Time::NanoSeconds(&expire);
ScopedLock lock(&m_mutex);
m_timers.insert( std::pair<unsigned long long, ITimer *>(curtime, timer) );
m_mutex.WakeUp();
}
void Timers::Remove(ITimer *timer)
{
ScopedLock lock(&m_mutex);
std::multimap<unsigned long long, ITimer *>::iterator it = m_timers.begin();
while(it != m_timers.end())
{
if (it->second == timer)
{
m_timers.erase(it);
return;
}
it++;
}
m_mutex.WakeUp();
}
void Timers::Run()
{
m_mutex.Lock(); //We really only unlock when we are asleep
while(m_run == true)
{
struct timespec ts;
Time::MonoTonic(&ts);
unsigned long long curtime = Time::NanoSeconds(&ts);
std::multimap<unsigned long long, ITimer *>::iterator it = m_timers.begin();
if (it == m_timers.end())
{
m_mutex.Wait(); //Wait forever on empty list until told otherwise
continue; //Restart
}
if (curtime < it->first)
{
unsigned long long diff = it->first - curtime;
struct timespec delay;
Time::TimeSpecFromNanoSeconds(diff, &delay);
m_mutex.Wait(&delay);
}
//We were asleep an unlocked. So thing things may have changed.
it = m_timers.begin();
if (it == m_timers.end())
continue; //All timers we removed while we were sleeping
//Get current time *again*
Time::MonoTonic(&ts);
curtime = Time::NanoSeconds(&ts);
if (curtime >= it->first)
{
ITimer *timer = it->second;
m_timers.erase(it);
timer->TimerExpired(this, timer);
continue;
}
}
m_mutex.Unlock();
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
#include "calling_convention_arm.h"
#include "logging.h"
#include "managed_register_arm.h"
namespace art {
namespace arm {
// Calling convention
ManagedRegister ArmManagedRuntimeCallingConvention::InterproceduralScratchRegister() {
return ArmManagedRegister::FromCoreRegister(IP); // R12
}
ManagedRegister ArmJniCallingConvention::InterproceduralScratchRegister() {
return ArmManagedRegister::FromCoreRegister(IP); // R12
}
static ManagedRegister ReturnRegisterForMethod(Method* method) {
if (method->IsReturnAFloat()) {
return ArmManagedRegister::FromCoreRegister(R0);
} else if (method->IsReturnADouble()) {
return ArmManagedRegister::FromRegisterPair(R0_R1);
} else if (method->IsReturnALong()) {
return ArmManagedRegister::FromRegisterPair(R0_R1);
} else if (method->IsReturnVoid()) {
return ArmManagedRegister::NoRegister();
} else {
return ArmManagedRegister::FromCoreRegister(R0);
}
}
ManagedRegister ArmManagedRuntimeCallingConvention::ReturnRegister() {
return ReturnRegisterForMethod(GetMethod());
}
ManagedRegister ArmJniCallingConvention::ReturnRegister() {
return ReturnRegisterForMethod(GetMethod());
}
// Managed runtime calling convention
ManagedRegister ArmManagedRuntimeCallingConvention::MethodRegister() {
return ArmManagedRegister::FromCoreRegister(R0);
}
bool ArmManagedRuntimeCallingConvention::IsCurrentParamInRegister() {
return itr_slots_ < 3;
}
bool ArmManagedRuntimeCallingConvention::IsCurrentParamOnStack() {
if (itr_slots_ < 2) {
return false;
} else if (itr_slots_ > 2) {
return true;
} else {
// handle funny case of a long/double straddling registers and the stack
return GetMethod()->IsParamALongOrDouble(itr_args_);
}
}
static const Register kManagedArgumentRegisters[] = {
R1, R2, R3
};
ManagedRegister ArmManagedRuntimeCallingConvention::CurrentParamRegister() {
CHECK(IsCurrentParamInRegister());
const Method* method = GetMethod();
if (method->IsParamALongOrDouble(itr_args_)) {
if (itr_slots_ == 0) {
return ArmManagedRegister::FromRegisterPair(R1_R2);
} else if (itr_slots_ == 1) {
return ArmManagedRegister::FromRegisterPair(R2_R3);
} else {
// This is a long/double split between registers and the stack
return ArmManagedRegister::FromCoreRegister(
kManagedArgumentRegisters[itr_slots_]);
}
} else {
return
ArmManagedRegister::FromCoreRegister(kManagedArgumentRegisters[itr_slots_]);
}
}
FrameOffset ArmManagedRuntimeCallingConvention::CurrentParamStackOffset() {
CHECK(IsCurrentParamOnStack());
FrameOffset result =
FrameOffset(displacement_.Int32Value() + // displacement
kPointerSize + // Method*
(itr_slots_ * kPointerSize)); // offset into in args
if (itr_slots_ == 2) {
// the odd spanning case, bump the offset to skip the first half of the
// input which is in a register
CHECK(IsCurrentParamInRegister());
result = FrameOffset(result.Int32Value() + 4);
}
return result;
}
// JNI calling convention
ArmJniCallingConvention::ArmJniCallingConvention(Method* method) : JniCallingConvention(method) {
// Compute padding to ensure longs and doubles are not split in AAPCS
// TODO: in terms of outgoing argument size this may be overly generous
// due to padding appearing in the registers
size_t padding = 0;
size_t check = method->IsStatic() ? 1 : 0;
for(size_t i = 0; i < method->NumArgs(); i++) {
if (((i & 1) == check) && method->IsParamALongOrDouble(i)) {
padding += 4;
}
}
padding_ = padding;
if (method->IsSynchronized()) {
// Preserve callee saves that may be clobbered during monitor enter where
// we copy across R0 to R3
if (method->NumArgs() > 0) {
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R4));
if (method->NumArgs() > 1) {
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R5));
if (method->NumArgs() > 2) {
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R6));
if (method->NumArgs() > 3) {
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R7));
}
}
}
}
}
}
uint32_t ArmJniCallingConvention::CoreSpillMask() const {
// Compute spill mask to agree with callee saves initialized in the constructor
uint32_t result = 0;
Method* method = GetMethod();
if (method->IsSynchronized()) {
if (method->NumArgs() > 0) {
result |= 1 << R4;
if (method->NumArgs() > 1) {
result |= 1 << R5;
if (method->NumArgs() > 2) {
result |= 1 << R6;
if (method->NumArgs() > 3) {
result |= 1 << R7;
}
}
}
}
}
return result;
}
ManagedRegister ArmJniCallingConvention::ReturnScratchRegister() const {
return ArmManagedRegister::FromCoreRegister(R2);
}
size_t ArmJniCallingConvention::FrameSize() {
// Method*, LR and callee save area size, local reference segment state
size_t frame_data_size = (3 + CalleeSaveRegisters().size()) * kPointerSize;
// References plus 2 words for SIRT header
size_t sirt_size = (ReferenceCount() + 2) * kPointerSize;
// Plus return value spill area size
return RoundUp(frame_data_size + sirt_size + SizeOfReturnValue(), kStackAlignment);
}
size_t ArmJniCallingConvention::OutArgSize() {
return RoundUp(NumberOfOutgoingStackArgs() * kPointerSize + padding_,
kStackAlignment);
}
size_t ArmJniCallingConvention::ReturnPcOffset() {
// Link register is always the first value pushed when the frame is constructed
return FrameSize() - kPointerSize;
}
// Will reg be crushed by an outgoing argument?
bool ArmJniCallingConvention::IsMethodRegisterClobberedPreCall() {
return true; // The method register R0 is always clobbered by the JNIEnv
}
// JniCallingConvention ABI follows AAPCS where longs and doubles must occur
// in even register numbers and stack slots
void ArmJniCallingConvention::Next() {
JniCallingConvention::Next();
Method* method = GetMethod();
size_t arg_pos = itr_args_ - NumberOfExtraArgumentsForJni(method);
if ((itr_args_ >= 2) &&
(arg_pos < GetMethod()->NumArgs()) &&
method->IsParamALongOrDouble(arg_pos)) {
// itr_slots_ needs to be an even number, according to AAPCS.
if ((itr_slots_ & 0x1u) != 0) {
itr_slots_++;
}
}
}
bool ArmJniCallingConvention::IsCurrentParamInRegister() {
return itr_slots_ < 4;
}
bool ArmJniCallingConvention::IsCurrentParamOnStack() {
return !IsCurrentParamInRegister();
}
static const Register kJniArgumentRegisters[] = {
R0, R1, R2, R3
};
ManagedRegister ArmJniCallingConvention::CurrentParamRegister() {
CHECK_LT(itr_slots_, 4u);
Method* method = GetMethod();
int arg_pos = itr_args_ - NumberOfExtraArgumentsForJni(method);
if ((itr_args_ >= 2) && method->IsParamALongOrDouble(arg_pos)) {
CHECK_EQ(itr_slots_, 2u);
return ArmManagedRegister::FromRegisterPair(R2_R3);
} else {
return
ArmManagedRegister::FromCoreRegister(kJniArgumentRegisters[itr_slots_]);
}
}
FrameOffset ArmJniCallingConvention::CurrentParamStackOffset() {
CHECK_GE(itr_slots_, 4u);
return FrameOffset(displacement_.Int32Value() - OutArgSize()
+ ((itr_slots_ - 4) * kPointerSize));
}
size_t ArmJniCallingConvention::NumberOfOutgoingStackArgs() {
Method* method = GetMethod();
size_t static_args = method->IsStatic() ? 1 : 0; // count jclass
// regular argument parameters and this
size_t param_args = method->NumArgs() +
method->NumLongOrDoubleArgs();
// count JNIEnv* less arguments in registers
return static_args + param_args + 1 - 4;
}
} // namespace arm
} // namespace art
<commit_msg>Callee-save these ARM registers: R5-R8, R10-R11 and LR.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
#include "calling_convention_arm.h"
#include "logging.h"
#include "managed_register_arm.h"
namespace art {
namespace arm {
// Calling convention
ManagedRegister ArmManagedRuntimeCallingConvention::InterproceduralScratchRegister() {
return ArmManagedRegister::FromCoreRegister(IP); // R12
}
ManagedRegister ArmJniCallingConvention::InterproceduralScratchRegister() {
return ArmManagedRegister::FromCoreRegister(IP); // R12
}
static ManagedRegister ReturnRegisterForMethod(Method* method) {
if (method->IsReturnAFloat()) {
return ArmManagedRegister::FromCoreRegister(R0);
} else if (method->IsReturnADouble()) {
return ArmManagedRegister::FromRegisterPair(R0_R1);
} else if (method->IsReturnALong()) {
return ArmManagedRegister::FromRegisterPair(R0_R1);
} else if (method->IsReturnVoid()) {
return ArmManagedRegister::NoRegister();
} else {
return ArmManagedRegister::FromCoreRegister(R0);
}
}
ManagedRegister ArmManagedRuntimeCallingConvention::ReturnRegister() {
return ReturnRegisterForMethod(GetMethod());
}
ManagedRegister ArmJniCallingConvention::ReturnRegister() {
return ReturnRegisterForMethod(GetMethod());
}
// Managed runtime calling convention
ManagedRegister ArmManagedRuntimeCallingConvention::MethodRegister() {
return ArmManagedRegister::FromCoreRegister(R0);
}
bool ArmManagedRuntimeCallingConvention::IsCurrentParamInRegister() {
return itr_slots_ < 3;
}
bool ArmManagedRuntimeCallingConvention::IsCurrentParamOnStack() {
if (itr_slots_ < 2) {
return false;
} else if (itr_slots_ > 2) {
return true;
} else {
// handle funny case of a long/double straddling registers and the stack
return GetMethod()->IsParamALongOrDouble(itr_args_);
}
}
static const Register kManagedArgumentRegisters[] = {
R1, R2, R3
};
ManagedRegister ArmManagedRuntimeCallingConvention::CurrentParamRegister() {
CHECK(IsCurrentParamInRegister());
const Method* method = GetMethod();
if (method->IsParamALongOrDouble(itr_args_)) {
if (itr_slots_ == 0) {
return ArmManagedRegister::FromRegisterPair(R1_R2);
} else if (itr_slots_ == 1) {
return ArmManagedRegister::FromRegisterPair(R2_R3);
} else {
// This is a long/double split between registers and the stack
return ArmManagedRegister::FromCoreRegister(
kManagedArgumentRegisters[itr_slots_]);
}
} else {
return
ArmManagedRegister::FromCoreRegister(kManagedArgumentRegisters[itr_slots_]);
}
}
FrameOffset ArmManagedRuntimeCallingConvention::CurrentParamStackOffset() {
CHECK(IsCurrentParamOnStack());
FrameOffset result =
FrameOffset(displacement_.Int32Value() + // displacement
kPointerSize + // Method*
(itr_slots_ * kPointerSize)); // offset into in args
if (itr_slots_ == 2) {
// the odd spanning case, bump the offset to skip the first half of the
// input which is in a register
CHECK(IsCurrentParamInRegister());
result = FrameOffset(result.Int32Value() + 4);
}
return result;
}
// JNI calling convention
ArmJniCallingConvention::ArmJniCallingConvention(Method* method) : JniCallingConvention(method) {
// Compute padding to ensure longs and doubles are not split in AAPCS
// TODO: in terms of outgoing argument size this may be overly generous
// due to padding appearing in the registers
size_t padding = 0;
size_t check = method->IsStatic() ? 1 : 0;
for(size_t i = 0; i < method->NumArgs(); i++) {
if (((i & 1) == check) && method->IsParamALongOrDouble(i)) {
padding += 4;
}
}
padding_ = padding;
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R5));
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R6));
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R7));
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R8));
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R10));
callee_save_regs_.push_back(ArmManagedRegister::FromCoreRegister(R11));
}
uint32_t ArmJniCallingConvention::CoreSpillMask() const {
// Compute spill mask to agree with callee saves initialized in the constructor
uint32_t result = 0;
result = 1 << R5 | 1 << R6 | 1 << R7 | 1 << R8 | 1 << R10 | 1 << R11 | 1 << LR;
return result;
}
ManagedRegister ArmJniCallingConvention::ReturnScratchRegister() const {
return ArmManagedRegister::FromCoreRegister(R2);
}
size_t ArmJniCallingConvention::FrameSize() {
// Method*, LR and callee save area size, local reference segment state
size_t frame_data_size = (3 + CalleeSaveRegisters().size()) * kPointerSize;
// References plus 2 words for SIRT header
size_t sirt_size = (ReferenceCount() + 2) * kPointerSize;
// Plus return value spill area size
return RoundUp(frame_data_size + sirt_size + SizeOfReturnValue(), kStackAlignment);
}
size_t ArmJniCallingConvention::OutArgSize() {
return RoundUp(NumberOfOutgoingStackArgs() * kPointerSize + padding_,
kStackAlignment);
}
size_t ArmJniCallingConvention::ReturnPcOffset() {
// Link register is always the first value pushed when the frame is constructed
return FrameSize() - kPointerSize;
}
// Will reg be crushed by an outgoing argument?
bool ArmJniCallingConvention::IsMethodRegisterClobberedPreCall() {
return true; // The method register R0 is always clobbered by the JNIEnv
}
// JniCallingConvention ABI follows AAPCS where longs and doubles must occur
// in even register numbers and stack slots
void ArmJniCallingConvention::Next() {
JniCallingConvention::Next();
Method* method = GetMethod();
size_t arg_pos = itr_args_ - NumberOfExtraArgumentsForJni(method);
if ((itr_args_ >= 2) &&
(arg_pos < GetMethod()->NumArgs()) &&
method->IsParamALongOrDouble(arg_pos)) {
// itr_slots_ needs to be an even number, according to AAPCS.
if ((itr_slots_ & 0x1u) != 0) {
itr_slots_++;
}
}
}
bool ArmJniCallingConvention::IsCurrentParamInRegister() {
return itr_slots_ < 4;
}
bool ArmJniCallingConvention::IsCurrentParamOnStack() {
return !IsCurrentParamInRegister();
}
static const Register kJniArgumentRegisters[] = {
R0, R1, R2, R3
};
ManagedRegister ArmJniCallingConvention::CurrentParamRegister() {
CHECK_LT(itr_slots_, 4u);
Method* method = GetMethod();
int arg_pos = itr_args_ - NumberOfExtraArgumentsForJni(method);
if ((itr_args_ >= 2) && method->IsParamALongOrDouble(arg_pos)) {
CHECK_EQ(itr_slots_, 2u);
return ArmManagedRegister::FromRegisterPair(R2_R3);
} else {
return
ArmManagedRegister::FromCoreRegister(kJniArgumentRegisters[itr_slots_]);
}
}
FrameOffset ArmJniCallingConvention::CurrentParamStackOffset() {
CHECK_GE(itr_slots_, 4u);
return FrameOffset(displacement_.Int32Value() - OutArgSize()
+ ((itr_slots_ - 4) * kPointerSize));
}
size_t ArmJniCallingConvention::NumberOfOutgoingStackArgs() {
Method* method = GetMethod();
size_t static_args = method->IsStatic() ? 1 : 0; // count jclass
// regular argument parameters and this
size_t param_args = method->NumArgs() +
method->NumLongOrDoubleArgs();
// count JNIEnv* less arguments in registers
return static_args + param_args + 1 - 4;
}
} // namespace arm
} // namespace art
<|endoftext|> |
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/14
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 <sys/poll.h>
#include <cerrno>
#include <boost/scoped_array.hpp>
#include "NetManager.h"
#include "TcpSocket.h"
#include "Globals.h"
#include "common/log.h"
#include "kfsutils.h"
using std::mem_fun;
using std::list;
using namespace KFS;
using namespace KFS::libkfsio;
NetManager::NetManager(int timeoutMs)
: mRemove(),
mTimerWheelBucketItr(mRemove.end()),
mCurConnection(0),
mCurTimerWheelSlot(0),
mConnectionsCount(0),
mDiskOverloaded(false),
mNetworkOverloaded(false),
mIsOverloaded(false),
mRunFlag(true),
mTimerRunningFlag(false),
mTimeoutMs(timeoutMs),
mNow(time(0)),
mMaxOutgoingBacklog(0),
mNumBytesToSend(0),
mPoll(*(new FdPoll()))
{}
NetManager::~NetManager()
{
NetManager::CleanUp();
delete &mPoll;
}
void
NetManager::AddConnection(NetConnectionPtr &conn)
{
NetConnection::NetManagerEntry* const entry =
conn->GetNetMangerEntry(*this);
if (! entry) {
return;
}
if (! entry->mAdded) {
entry->mTimerWheelSlot = kTimerWheelSize;
entry->mListIt = mTimerWheel[kTimerWheelSize].insert(
mTimerWheel[kTimerWheelSize].end(), conn);
mConnectionsCount++;
assert(mConnectionsCount > 0);
entry->mAdded = true;
}
conn->Update();
}
void
NetManager::RegisterTimeoutHandler(ITimeout *handler)
{
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
return;
}
}
mTimeoutHandlers.push_back(handler);
}
void
NetManager::UnRegisterTimeoutHandler(ITimeout *handler)
{
if (handler == NULL)
return;
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
// Not not remove list element: this can be called when iterating
// trough the list.
*iter = 0;
return;
}
}
}
inline void
NetManager::UpdateTimer(NetConnection::NetManagerEntry& entry, int timeOut)
{
assert(entry.mAdded);
int timerWheelSlot;
if (timeOut < 0) {
timerWheelSlot = kTimerWheelSize;
} else if ((timerWheelSlot = mCurTimerWheelSlot +
// When the timer is running the effective wheel size "grows" by 1:
// leave (move) entries with timeouts >= kTimerWheelSize in (to) the
// current slot.
std::min((kTimerWheelSize - mTimerRunningFlag ? 0 : 1), timeOut)) >=
kTimerWheelSize) {
timerWheelSlot -= kTimerWheelSize;
}
// This method can be invoked from timeout handler.
// Make sure that the entry doesn't get moved to the end of the current
// list, which can be traversed by the timer.
if (timerWheelSlot != entry.mTimerWheelSlot) {
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mTimerWheel[timerWheelSlot].splice(
mTimerWheel[timerWheelSlot].end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
entry.mTimerWheelSlot = timerWheelSlot;
}
}
inline static int CheckFatalSysError(int err, const char* msg)
{
if (err) {
std::string const msg = KFSUtils::SysError(err);
KFS_LOG_VA_FATAL("%s: %d %s", err, msg.c_str());
abort();
}
return err;
}
void
NetManager::Update(NetConnection::NetManagerEntry& entry, int fd, bool resetTimer)
{
if (! entry.mAdded) {
return;
}
assert(*entry.mListIt);
NetConnection& conn = **entry.mListIt;
assert(fd >= 0 || ! conn.IsGood());
// Always check if connection has to be removed: this method always
// called before socket fd gets closed.
if (! conn.IsGood() || fd < 0) {
if (entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
assert(mConnectionsCount > 0 &&
entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
entry.mAdded = false;
mConnectionsCount--;
mNumBytesToSend -= entry.mWriteByteCount;
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mRemove.splice(mRemove.end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
return;
}
if (&conn == mCurConnection) {
// Defer all updates for the currently dispatched connection until the
// end of the event dispatch loop.
return;
}
// Update timer.
if (resetTimer) {
const int timeOut = conn.GetInactivityTimeout();
if (timeOut >= 0) {
entry.mExpirationTime = mNow + timeOut;
}
UpdateTimer(entry, timeOut);
}
// Update pending send.
assert(entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
mNumBytesToSend -= entry.mWriteByteCount;
entry.mWriteByteCount = std::max(0, conn.GetNumBytesToWrite());
mNumBytesToSend += entry.mWriteByteCount;
// Update poll set.
const bool in = conn.IsReadReady() &&
(! mIsOverloaded || entry.mEnableReadIfOverloaded);
const bool out = conn.IsWriteReady() || entry.mConnectPending;
if (in != entry.mIn || out != entry.mOut) {
assert(fd >= 0);
const int op =
(in ? FdPoll::kOpTypeIn : 0) + (out ? FdPoll::kOpTypeOut : 0);
if (fd != entry.mFd && entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
if (entry.mFd < 0) {
if (op && CheckFatalSysError(
mPoll.Add(fd, op, &conn),
"failed to add fd to poll set") == 0) {
entry.mFd = fd;
}
} else {
CheckFatalSysError(
mPoll.Set(fd, op, &conn),
"failed to change pool flags"
);
}
entry.mIn = in && entry.mFd >= 0;
entry.mOut = out && entry.mFd >= 0;
}
}
void
NetManager::MainLoop()
{
mNow = time(0);
time_t lastTimerTime = mNow;
CheckFatalSysError(
mPoll.Add(globals().netKicker.GetFd(), FdPoll::kOpTypeIn),
"failed to add net kicker's fd to poll set"
);
const int timerOverrunWarningTime(mTimeoutMs / (1000/2));
while (mRunFlag) {
const bool wasOverloaded = mIsOverloaded;
CheckIfOverloaded();
if (mIsOverloaded != wasOverloaded) {
KFS_LOG_VA_INFO(
"%s (%0.f bytes to send; %d disk IO's) ",
mIsOverloaded ?
"System is now in overloaded state " :
"Clearing system overload state",
double(mNumBytesToSend),
globals().diskManager.NumDiskIOOutstanding());
for (int i = 0; i <= kTimerWheelSize; i++) {
for (List::iterator c = mTimerWheel[i].begin();
c != mTimerWheel[i].end(); ) {
assert(*c);
NetConnection& conn = **c;
++c;
conn.Update(false);
}
}
}
const int ret = mPoll.Poll(mConnectionsCount + 1, mTimeoutMs);
if (ret < 0 && ret != -EINTR && ret != -EAGAIN) {
std::string const msg = KFSUtils::SysError(-ret);
KFS_LOG_VA_ERROR("poll errror %d %s", -ret, msg.c_str());
}
globals().netKicker.Drain();
const int64_t nowMs = ITimeout::NowMs();
mNow = time_t(nowMs / 1000);
globals().diskManager.ReapCompletedIOs();
// Unregister will set pointer to 0, but will never remove the list
// node, so that the iterator always remains valid.
for (std::list<ITimeout *>::iterator it = mTimeoutHandlers.begin();
it != mTimeoutHandlers.end(); ) {
if (*it) {
(*it)->TimerExpired(nowMs);
}
if (*it) {
++it;
} else {
it = mTimeoutHandlers.erase(it);
}
}
/// Process poll events.
int op;
void* ptr;
while (mPoll.Next(op, ptr)) {
if (op == 0 || ! ptr) {
continue;
}
NetConnection& conn = *reinterpret_cast<NetConnection*>(ptr);
assert(conn.GetNetMangerEntry(*this)->mAdded);
// Defer update for this connection.
mCurConnection = &conn;
if ((op & FdPoll::kOpTypeIn) != 0 && conn.IsGood()) {
conn.HandleReadEvent();
}
if ((op & FdPoll::kOpTypeOut) != 0 && conn.IsGood()) {
conn.HandleWriteEvent();
}
if ((op & (FdPoll::kOpTypeError | FdPoll::kOpTypeHup)) != 0 &&
conn.IsGood()) {
conn.HandleErrorEvent();
}
// Try to write, if the last write was sucessfull.
conn.StartFlush();
// Update the connection.
mCurConnection = 0;
conn.Update();
}
mRemove.clear();
mNow = time(0);
int slotCnt = std::min(int(kTimerWheelSize), int(mNow - lastTimerTime));
if (slotCnt > timerOverrunWarningTime) {
KFS_LOG_VA_DEBUG("Timer overrun %d seconds detected", slotCnt - 1);
}
mTimerRunningFlag = true;
while (slotCnt-- > 0) {
List& bucket = mTimerWheel[mCurTimerWheelSlot];
mTimerWheelBucketItr = bucket.begin();
while (mTimerWheelBucketItr != bucket.end()) {
assert(*mTimerWheelBucketItr);
NetConnection& conn = **mTimerWheelBucketItr;
assert(conn.IsGood());
++mTimerWheelBucketItr;
NetConnection::NetManagerEntry& entry =
*conn.GetNetMangerEntry(*this);
const int timeOut = conn.GetInactivityTimeout();
if (timeOut < 0) {
// No timeout, move it to the corresponding list.
UpdateTimer(entry, timeOut);
} else if (entry.mExpirationTime <= mNow) {
conn.HandleTimeoutEvent();
} else {
// Not expired yet, move to the new slot, taking into the
// account possible timer overrun.
UpdateTimer(entry,
slotCnt + int(entry.mExpirationTime - mNow));
}
}
if (++mCurTimerWheelSlot >= kTimerWheelSize) {
mCurTimerWheelSlot = 0;
}
mRemove.clear();
}
mTimerRunningFlag = false;
lastTimerTime = mNow;
mTimerWheelBucketItr = mRemove.end();
}
CheckFatalSysError(
mPoll.Remove(globals().netKicker.GetFd()),
"failed to removed net kicker's fd from poll set"
);
CleanUp();
}
void
NetManager::CheckIfOverloaded()
{
if (mMaxOutgoingBacklog > 0) {
if (!mNetworkOverloaded) {
mNetworkOverloaded = (mNumBytesToSend > mMaxOutgoingBacklog);
} else if (mNumBytesToSend <= mMaxOutgoingBacklog / 2) {
// network was overloaded and that has now cleared
mNetworkOverloaded = false;
}
}
mIsOverloaded = mDiskOverloaded || mNetworkOverloaded;
}
void
NetManager::ChangeDiskOverloadState(bool v)
{
if (mDiskOverloaded == v)
return;
mDiskOverloaded = v;
}
void
NetManager::CleanUp()
{
mTimeoutHandlers.clear();
for (int i = 0; i <= kTimerWheelSize; i++) {
for (mTimerWheelBucketItr = mTimerWheel[i].begin();
mTimerWheelBucketItr != mTimerWheel[i].end(); ) {
NetConnection* const conn = mTimerWheelBucketItr->get();
++mTimerWheelBucketItr;
if (conn) {
if (conn->IsGood()) {
conn->HandleErrorEvent();
}
conn->Close();
}
}
assert(mTimerWheel[i].empty());
mRemove.clear();
}
mTimerWheelBucketItr = mRemove.end();
}
<commit_msg> -- Remove an invalid assertion: when stale events are received on a connection that is closed, ignore the event; previously, we were incorrectly asserting.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/14
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 <sys/poll.h>
#include <cerrno>
#include <boost/scoped_array.hpp>
#include "NetManager.h"
#include "TcpSocket.h"
#include "Globals.h"
#include "common/log.h"
#include "kfsutils.h"
using std::mem_fun;
using std::list;
using namespace KFS;
using namespace KFS::libkfsio;
NetManager::NetManager(int timeoutMs)
: mRemove(),
mTimerWheelBucketItr(mRemove.end()),
mCurConnection(0),
mCurTimerWheelSlot(0),
mConnectionsCount(0),
mDiskOverloaded(false),
mNetworkOverloaded(false),
mIsOverloaded(false),
mRunFlag(true),
mTimerRunningFlag(false),
mTimeoutMs(timeoutMs),
mNow(time(0)),
mMaxOutgoingBacklog(0),
mNumBytesToSend(0),
mPoll(*(new FdPoll()))
{}
NetManager::~NetManager()
{
NetManager::CleanUp();
delete &mPoll;
}
void
NetManager::AddConnection(NetConnectionPtr &conn)
{
NetConnection::NetManagerEntry* const entry =
conn->GetNetMangerEntry(*this);
if (! entry) {
return;
}
if (! entry->mAdded) {
entry->mTimerWheelSlot = kTimerWheelSize;
entry->mListIt = mTimerWheel[kTimerWheelSize].insert(
mTimerWheel[kTimerWheelSize].end(), conn);
mConnectionsCount++;
assert(mConnectionsCount > 0);
entry->mAdded = true;
}
conn->Update();
}
void
NetManager::RegisterTimeoutHandler(ITimeout *handler)
{
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
return;
}
}
mTimeoutHandlers.push_back(handler);
}
void
NetManager::UnRegisterTimeoutHandler(ITimeout *handler)
{
if (handler == NULL)
return;
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
// Not not remove list element: this can be called when iterating
// trough the list.
*iter = 0;
return;
}
}
}
inline void
NetManager::UpdateTimer(NetConnection::NetManagerEntry& entry, int timeOut)
{
assert(entry.mAdded);
int timerWheelSlot;
if (timeOut < 0) {
timerWheelSlot = kTimerWheelSize;
} else if ((timerWheelSlot = mCurTimerWheelSlot +
// When the timer is running the effective wheel size "grows" by 1:
// leave (move) entries with timeouts >= kTimerWheelSize in (to) the
// current slot.
std::min((kTimerWheelSize - mTimerRunningFlag ? 0 : 1), timeOut)) >=
kTimerWheelSize) {
timerWheelSlot -= kTimerWheelSize;
}
// This method can be invoked from timeout handler.
// Make sure that the entry doesn't get moved to the end of the current
// list, which can be traversed by the timer.
if (timerWheelSlot != entry.mTimerWheelSlot) {
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mTimerWheel[timerWheelSlot].splice(
mTimerWheel[timerWheelSlot].end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
entry.mTimerWheelSlot = timerWheelSlot;
}
}
inline static int CheckFatalSysError(int err, const char* msg)
{
if (err) {
std::string const msg = KFSUtils::SysError(err);
KFS_LOG_VA_FATAL("%s: %d %s", err, msg.c_str());
abort();
}
return err;
}
void
NetManager::Update(NetConnection::NetManagerEntry& entry, int fd, bool resetTimer)
{
if (! entry.mAdded) {
return;
}
assert(*entry.mListIt);
NetConnection& conn = **entry.mListIt;
assert(fd >= 0 || ! conn.IsGood());
// Always check if connection has to be removed: this method always
// called before socket fd gets closed.
if (! conn.IsGood() || fd < 0) {
if (entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
assert(mConnectionsCount > 0 &&
entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
entry.mAdded = false;
mConnectionsCount--;
mNumBytesToSend -= entry.mWriteByteCount;
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mRemove.splice(mRemove.end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
return;
}
if (&conn == mCurConnection) {
// Defer all updates for the currently dispatched connection until the
// end of the event dispatch loop.
return;
}
// Update timer.
if (resetTimer) {
const int timeOut = conn.GetInactivityTimeout();
if (timeOut >= 0) {
entry.mExpirationTime = mNow + timeOut;
}
UpdateTimer(entry, timeOut);
}
// Update pending send.
assert(entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
mNumBytesToSend -= entry.mWriteByteCount;
entry.mWriteByteCount = std::max(0, conn.GetNumBytesToWrite());
mNumBytesToSend += entry.mWriteByteCount;
// Update poll set.
const bool in = conn.IsReadReady() &&
(! mIsOverloaded || entry.mEnableReadIfOverloaded);
const bool out = conn.IsWriteReady() || entry.mConnectPending;
if (in != entry.mIn || out != entry.mOut) {
assert(fd >= 0);
const int op =
(in ? FdPoll::kOpTypeIn : 0) + (out ? FdPoll::kOpTypeOut : 0);
if (fd != entry.mFd && entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
if (entry.mFd < 0) {
if (op && CheckFatalSysError(
mPoll.Add(fd, op, &conn),
"failed to add fd to poll set") == 0) {
entry.mFd = fd;
}
} else {
CheckFatalSysError(
mPoll.Set(fd, op, &conn),
"failed to change pool flags"
);
}
entry.mIn = in && entry.mFd >= 0;
entry.mOut = out && entry.mFd >= 0;
}
}
void
NetManager::MainLoop()
{
mNow = time(0);
time_t lastTimerTime = mNow;
CheckFatalSysError(
mPoll.Add(globals().netKicker.GetFd(), FdPoll::kOpTypeIn),
"failed to add net kicker's fd to poll set"
);
const int timerOverrunWarningTime(mTimeoutMs / (1000/2));
while (mRunFlag) {
const bool wasOverloaded = mIsOverloaded;
CheckIfOverloaded();
if (mIsOverloaded != wasOverloaded) {
KFS_LOG_VA_INFO(
"%s (%0.f bytes to send; %d disk IO's) ",
mIsOverloaded ?
"System is now in overloaded state " :
"Clearing system overload state",
double(mNumBytesToSend),
globals().diskManager.NumDiskIOOutstanding());
for (int i = 0; i <= kTimerWheelSize; i++) {
for (List::iterator c = mTimerWheel[i].begin();
c != mTimerWheel[i].end(); ) {
assert(*c);
NetConnection& conn = **c;
++c;
conn.Update(false);
}
}
}
const int ret = mPoll.Poll(mConnectionsCount + 1, mTimeoutMs);
if (ret < 0 && ret != -EINTR && ret != -EAGAIN) {
std::string const msg = KFSUtils::SysError(-ret);
KFS_LOG_VA_ERROR("poll errror %d %s", -ret, msg.c_str());
}
globals().netKicker.Drain();
const int64_t nowMs = ITimeout::NowMs();
mNow = time_t(nowMs / 1000);
globals().diskManager.ReapCompletedIOs();
// Unregister will set pointer to 0, but will never remove the list
// node, so that the iterator always remains valid.
for (std::list<ITimeout *>::iterator it = mTimeoutHandlers.begin();
it != mTimeoutHandlers.end(); ) {
if (*it) {
(*it)->TimerExpired(nowMs);
}
if (*it) {
++it;
} else {
it = mTimeoutHandlers.erase(it);
}
}
/// Process poll events.
int op;
void* ptr;
while (mPoll.Next(op, ptr)) {
if (op == 0 || ! ptr) {
continue;
}
NetConnection& conn = *reinterpret_cast<NetConnection*>(ptr);
if (! conn.GetNetMangerEntry(*this)->mAdded) {
// Skip stale event, the conection should be in mRemove list.
continue;
}
// Defer update for this connection.
mCurConnection = &conn;
if ((op & FdPoll::kOpTypeIn) != 0 && conn.IsGood()) {
conn.HandleReadEvent();
}
if ((op & FdPoll::kOpTypeOut) != 0 && conn.IsGood()) {
conn.HandleWriteEvent();
}
if ((op & (FdPoll::kOpTypeError | FdPoll::kOpTypeHup)) != 0 &&
conn.IsGood()) {
conn.HandleErrorEvent();
}
// Try to write, if the last write was sucessfull.
conn.StartFlush();
// Update the connection.
mCurConnection = 0;
conn.Update();
}
mRemove.clear();
mNow = time(0);
int slotCnt = std::min(int(kTimerWheelSize), int(mNow - lastTimerTime));
if (slotCnt > timerOverrunWarningTime) {
KFS_LOG_VA_DEBUG("Timer overrun %d seconds detected", slotCnt - 1);
}
mTimerRunningFlag = true;
while (slotCnt-- > 0) {
List& bucket = mTimerWheel[mCurTimerWheelSlot];
mTimerWheelBucketItr = bucket.begin();
while (mTimerWheelBucketItr != bucket.end()) {
assert(*mTimerWheelBucketItr);
NetConnection& conn = **mTimerWheelBucketItr;
assert(conn.IsGood());
++mTimerWheelBucketItr;
NetConnection::NetManagerEntry& entry =
*conn.GetNetMangerEntry(*this);
const int timeOut = conn.GetInactivityTimeout();
if (timeOut < 0) {
// No timeout, move it to the corresponding list.
UpdateTimer(entry, timeOut);
} else if (entry.mExpirationTime <= mNow) {
conn.HandleTimeoutEvent();
} else {
// Not expired yet, move to the new slot, taking into the
// account possible timer overrun.
UpdateTimer(entry,
slotCnt + int(entry.mExpirationTime - mNow));
}
}
if (++mCurTimerWheelSlot >= kTimerWheelSize) {
mCurTimerWheelSlot = 0;
}
mRemove.clear();
}
mTimerRunningFlag = false;
lastTimerTime = mNow;
mTimerWheelBucketItr = mRemove.end();
}
CheckFatalSysError(
mPoll.Remove(globals().netKicker.GetFd()),
"failed to removed net kicker's fd from poll set"
);
CleanUp();
}
void
NetManager::CheckIfOverloaded()
{
if (mMaxOutgoingBacklog > 0) {
if (!mNetworkOverloaded) {
mNetworkOverloaded = (mNumBytesToSend > mMaxOutgoingBacklog);
} else if (mNumBytesToSend <= mMaxOutgoingBacklog / 2) {
// network was overloaded and that has now cleared
mNetworkOverloaded = false;
}
}
mIsOverloaded = mDiskOverloaded || mNetworkOverloaded;
}
void
NetManager::ChangeDiskOverloadState(bool v)
{
if (mDiskOverloaded == v)
return;
mDiskOverloaded = v;
}
void
NetManager::CleanUp()
{
mTimeoutHandlers.clear();
for (int i = 0; i <= kTimerWheelSize; i++) {
for (mTimerWheelBucketItr = mTimerWheel[i].begin();
mTimerWheelBucketItr != mTimerWheel[i].end(); ) {
NetConnection* const conn = mTimerWheelBucketItr->get();
++mTimerWheelBucketItr;
if (conn) {
if (conn->IsGood()) {
conn->HandleErrorEvent();
}
conn->Close();
}
}
assert(mTimerWheel[i].empty());
mRemove.clear();
}
mTimerWheelBucketItr = mRemove.end();
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/14
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 <sys/poll.h>
#include <cerrno>
#include <boost/scoped_array.hpp>
#include "NetManager.h"
#include "TcpSocket.h"
#include "Globals.h"
#include "common/log.h"
#include "kfsutils.h"
using std::mem_fun;
using std::list;
using namespace KFS;
using namespace KFS::libkfsio;
NetManager::NetManager(int timeoutMs)
: mRemove(),
mTimerWheelBucketItr(mRemove.end()),
mCurConnection(0),
mCurTimerWheelSlot(0),
mConnectionsCount(0),
mDiskOverloaded(false),
mNetworkOverloaded(false),
mIsOverloaded(false),
mRunFlag(true),
mTimerRunningFlag(false),
mIsForkedChild(false),
mTimeoutMs(timeoutMs),
mNow(time(0)),
mMaxOutgoingBacklog(0),
mNumBytesToSend(0),
mPoll(*(new FdPoll()))
{}
NetManager::~NetManager()
{
NetManager::CleanUp();
delete &mPoll;
}
void
NetManager::AddConnection(NetConnectionPtr &conn)
{
NetConnection::NetManagerEntry* const entry =
conn->GetNetMangerEntry(*this);
if (! entry) {
return;
}
if (! entry->mAdded) {
entry->mTimerWheelSlot = kTimerWheelSize;
entry->mListIt = mTimerWheel[kTimerWheelSize].insert(
mTimerWheel[kTimerWheelSize].end(), conn);
mConnectionsCount++;
assert(mConnectionsCount > 0);
entry->mAdded = true;
}
conn->Update();
}
void
NetManager::RegisterTimeoutHandler(ITimeout *handler)
{
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
return;
}
}
mTimeoutHandlers.push_back(handler);
}
void
NetManager::UnRegisterTimeoutHandler(ITimeout *handler)
{
if (handler == NULL)
return;
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
// Not not remove list element: this can be called when iterating
// trough the list.
*iter = 0;
return;
}
}
}
inline void
NetManager::UpdateTimer(NetConnection::NetManagerEntry& entry, int timeOut)
{
assert(entry.mAdded);
int timerWheelSlot;
if (timeOut < 0) {
timerWheelSlot = kTimerWheelSize;
} else if ((timerWheelSlot = mCurTimerWheelSlot +
// When the timer is running the effective wheel size "grows" by 1:
// leave (move) entries with timeouts >= kTimerWheelSize in (to) the
// current slot.
std::min((kTimerWheelSize - mTimerRunningFlag ? 0 : 1), timeOut)) >=
kTimerWheelSize) {
timerWheelSlot -= kTimerWheelSize;
}
// This method can be invoked from timeout handler.
// Make sure that the entry doesn't get moved to the end of the current
// list, which can be traversed by the timer.
if (timerWheelSlot != entry.mTimerWheelSlot) {
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mTimerWheel[timerWheelSlot].splice(
mTimerWheel[timerWheelSlot].end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
entry.mTimerWheelSlot = timerWheelSlot;
}
}
inline static int CheckFatalSysError(int err, const char* msg)
{
if (err) {
std::string const sysMsg = KFSUtils::SysError(err);
KFS_LOG_VA_FATAL("%s: %d %s", msg ? msg : "", err, sysMsg.c_str());
abort();
}
return err;
}
void
NetManager::Update(NetConnection::NetManagerEntry& entry, int fd, bool resetTimer)
{
if ((! entry.mAdded) || (mIsForkedChild)) {
return;
}
assert(*entry.mListIt);
NetConnection& conn = **entry.mListIt;
assert(fd >= 0 || ! conn.IsGood());
// Always check if connection has to be removed: this method always
// called before socket fd gets closed.
if (! conn.IsGood() || fd < 0) {
if (entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
assert(mConnectionsCount > 0 &&
entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
entry.mAdded = false;
mConnectionsCount--;
mNumBytesToSend -= entry.mWriteByteCount;
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mRemove.splice(mRemove.end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
return;
}
if (&conn == mCurConnection) {
// Defer all updates for the currently dispatched connection until the
// end of the event dispatch loop.
return;
}
// Update timer.
if (resetTimer) {
const int timeOut = conn.GetInactivityTimeout();
if (timeOut >= 0) {
entry.mExpirationTime = mNow + timeOut;
}
UpdateTimer(entry, timeOut);
}
// Update pending send.
assert(entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
mNumBytesToSend -= entry.mWriteByteCount;
entry.mWriteByteCount = std::max(0, conn.GetNumBytesToWrite());
mNumBytesToSend += entry.mWriteByteCount;
// Update poll set.
const bool in = conn.IsReadReady() &&
(! mIsOverloaded || entry.mEnableReadIfOverloaded);
const bool out = conn.IsWriteReady() || entry.mConnectPending;
if (in != entry.mIn || out != entry.mOut) {
assert(fd >= 0);
const int op =
(in ? FdPoll::kOpTypeIn : 0) + (out ? FdPoll::kOpTypeOut : 0);
if (fd != entry.mFd && entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
if (entry.mFd < 0) {
if (op && CheckFatalSysError(
mPoll.Add(fd, op, &conn),
"failed to add fd to poll set") == 0) {
entry.mFd = fd;
}
} else {
CheckFatalSysError(
mPoll.Set(fd, op, &conn),
"failed to change pool flags"
);
}
entry.mIn = in && entry.mFd >= 0;
entry.mOut = out && entry.mFd >= 0;
}
}
void
NetManager::MainLoop()
{
mNow = time(0);
time_t lastTimerTime = mNow;
CheckFatalSysError(
mPoll.Add(globals().netKicker.GetFd(), FdPoll::kOpTypeIn),
"failed to add net kicker's fd to poll set"
);
const int timerOverrunWarningTime(mTimeoutMs / (1000/2));
while (mRunFlag) {
const bool wasOverloaded = mIsOverloaded;
CheckIfOverloaded();
if (mIsOverloaded != wasOverloaded) {
KFS_LOG_VA_INFO(
"%s (%0.f bytes to send; %d disk IO's) ",
mIsOverloaded ?
"System is now in overloaded state " :
"Clearing system overload state",
double(mNumBytesToSend),
globals().diskManager.NumDiskIOOutstanding());
for (int i = 0; i <= kTimerWheelSize; i++) {
for (List::iterator c = mTimerWheel[i].begin();
c != mTimerWheel[i].end(); ) {
assert(*c);
NetConnection& conn = **c;
++c;
conn.Update(false);
}
}
}
const int ret = mPoll.Poll(mConnectionsCount + 1, mTimeoutMs);
if (ret < 0 && ret != -EINTR && ret != -EAGAIN) {
std::string const msg = KFSUtils::SysError(-ret);
KFS_LOG_VA_ERROR("poll errror %d %s", -ret, msg.c_str());
}
globals().netKicker.Drain();
const int64_t nowMs = ITimeout::NowMs();
mNow = time_t(nowMs / 1000);
globals().diskManager.ReapCompletedIOs();
// Unregister will set pointer to 0, but will never remove the list
// node, so that the iterator always remains valid.
for (std::list<ITimeout *>::iterator it = mTimeoutHandlers.begin();
it != mTimeoutHandlers.end(); ) {
if (*it) {
(*it)->TimerExpired(nowMs);
}
if (*it) {
++it;
} else {
it = mTimeoutHandlers.erase(it);
}
}
/// Process poll events.
int op;
void* ptr;
while (mPoll.Next(op, ptr)) {
if (op == 0 || ! ptr) {
continue;
}
NetConnection& conn = *reinterpret_cast<NetConnection*>(ptr);
if (! conn.GetNetMangerEntry(*this)->mAdded) {
// Skip stale event, the conection should be in mRemove list.
continue;
}
// Defer update for this connection.
mCurConnection = &conn;
if ((op & FdPoll::kOpTypeIn) != 0 && conn.IsGood()) {
conn.HandleReadEvent();
}
if ((op & FdPoll::kOpTypeOut) != 0 && conn.IsGood()) {
conn.HandleWriteEvent();
}
if ((op & (FdPoll::kOpTypeError | FdPoll::kOpTypeHup)) != 0 &&
conn.IsGood()) {
conn.HandleErrorEvent();
}
// Try to write, if the last write was sucessfull.
conn.StartFlush();
// Update the connection.
mCurConnection = 0;
conn.Update();
}
mRemove.clear();
mNow = time(0);
int slotCnt = std::min(int(kTimerWheelSize), int(mNow - lastTimerTime));
if (slotCnt > timerOverrunWarningTime) {
KFS_LOG_VA_DEBUG("Timer overrun %d seconds detected", slotCnt - 1);
}
mTimerRunningFlag = true;
while (slotCnt-- > 0) {
List& bucket = mTimerWheel[mCurTimerWheelSlot];
mTimerWheelBucketItr = bucket.begin();
while (mTimerWheelBucketItr != bucket.end()) {
assert(*mTimerWheelBucketItr);
NetConnection& conn = **mTimerWheelBucketItr;
assert(conn.IsGood());
++mTimerWheelBucketItr;
NetConnection::NetManagerEntry& entry =
*conn.GetNetMangerEntry(*this);
const int timeOut = conn.GetInactivityTimeout();
if (timeOut < 0) {
// No timeout, move it to the corresponding list.
UpdateTimer(entry, timeOut);
} else if (entry.mExpirationTime <= mNow) {
conn.HandleTimeoutEvent();
} else {
// Not expired yet, move to the new slot, taking into the
// account possible timer overrun.
UpdateTimer(entry,
slotCnt + int(entry.mExpirationTime - mNow));
}
}
if (++mCurTimerWheelSlot >= kTimerWheelSize) {
mCurTimerWheelSlot = 0;
}
mRemove.clear();
}
mTimerRunningFlag = false;
lastTimerTime = mNow;
mTimerWheelBucketItr = mRemove.end();
}
CheckFatalSysError(
mPoll.Remove(globals().netKicker.GetFd()),
"failed to removed net kicker's fd from poll set"
);
CleanUp();
}
void
NetManager::CheckIfOverloaded()
{
if (mMaxOutgoingBacklog > 0) {
if (!mNetworkOverloaded) {
mNetworkOverloaded = (mNumBytesToSend > mMaxOutgoingBacklog);
} else if (mNumBytesToSend <= mMaxOutgoingBacklog / 2) {
// network was overloaded and that has now cleared
mNetworkOverloaded = false;
}
}
mIsOverloaded = mDiskOverloaded || mNetworkOverloaded;
}
void
NetManager::ChangeDiskOverloadState(bool v)
{
if (mDiskOverloaded == v)
return;
mDiskOverloaded = v;
}
void
NetManager::CleanUp()
{
mTimeoutHandlers.clear();
for (int i = 0; i <= kTimerWheelSize; i++) {
for (mTimerWheelBucketItr = mTimerWheel[i].begin();
mTimerWheelBucketItr != mTimerWheel[i].end(); ) {
NetConnection* const conn = mTimerWheelBucketItr->get();
++mTimerWheelBucketItr;
if (conn) {
if (conn->IsGood()) {
conn->HandleErrorEvent();
}
conn->Close();
}
}
assert(mTimerWheel[i].empty());
mRemove.clear();
}
mTimerWheelBucketItr = mRemove.end();
}
<commit_msg> -- Fix timer wheel slot calculation.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/14
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 <sys/poll.h>
#include <cerrno>
#include <boost/scoped_array.hpp>
#include "NetManager.h"
#include "TcpSocket.h"
#include "Globals.h"
#include "common/log.h"
#include "kfsutils.h"
using std::mem_fun;
using std::list;
using namespace KFS;
using namespace KFS::libkfsio;
NetManager::NetManager(int timeoutMs)
: mRemove(),
mTimerWheelBucketItr(mRemove.end()),
mCurConnection(0),
mCurTimerWheelSlot(0),
mConnectionsCount(0),
mDiskOverloaded(false),
mNetworkOverloaded(false),
mIsOverloaded(false),
mRunFlag(true),
mTimerRunningFlag(false),
mIsForkedChild(false),
mTimeoutMs(timeoutMs),
mNow(time(0)),
mMaxOutgoingBacklog(0),
mNumBytesToSend(0),
mPoll(*(new FdPoll()))
{}
NetManager::~NetManager()
{
NetManager::CleanUp();
delete &mPoll;
}
void
NetManager::AddConnection(NetConnectionPtr &conn)
{
NetConnection::NetManagerEntry* const entry =
conn->GetNetMangerEntry(*this);
if (! entry) {
return;
}
if (! entry->mAdded) {
entry->mTimerWheelSlot = kTimerWheelSize;
entry->mListIt = mTimerWheel[kTimerWheelSize].insert(
mTimerWheel[kTimerWheelSize].end(), conn);
mConnectionsCount++;
assert(mConnectionsCount > 0);
entry->mAdded = true;
}
conn->Update();
}
void
NetManager::RegisterTimeoutHandler(ITimeout *handler)
{
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
return;
}
}
mTimeoutHandlers.push_back(handler);
}
void
NetManager::UnRegisterTimeoutHandler(ITimeout *handler)
{
if (handler == NULL)
return;
list<ITimeout *>::iterator iter;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
if (*iter == handler) {
// Not not remove list element: this can be called when iterating
// trough the list.
*iter = 0;
return;
}
}
}
inline void
NetManager::UpdateTimer(NetConnection::NetManagerEntry& entry, int timeOut)
{
assert(entry.mAdded);
int timerWheelSlot;
if (timeOut < 0) {
timerWheelSlot = kTimerWheelSize;
} else if ((timerWheelSlot = mCurTimerWheelSlot +
// When the timer is running the effective wheel size "grows" by 1:
// leave (move) entries with timeouts >= kTimerWheelSize in (to) the
// current slot.
std::min((kTimerWheelSize - (mTimerRunningFlag ? 0 : 1)), timeOut)) >=
kTimerWheelSize) {
timerWheelSlot -= kTimerWheelSize;
}
// This method can be invoked from timeout handler.
// Make sure that the entry doesn't get moved to the end of the current
// list, which can be traversed by the timer.
if (timerWheelSlot != entry.mTimerWheelSlot) {
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mTimerWheel[timerWheelSlot].splice(
mTimerWheel[timerWheelSlot].end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
entry.mTimerWheelSlot = timerWheelSlot;
}
}
inline static int CheckFatalSysError(int err, const char* msg)
{
if (err) {
std::string const sysMsg = KFSUtils::SysError(err);
KFS_LOG_VA_FATAL("%s: %d %s", msg ? msg : "", err, sysMsg.c_str());
abort();
}
return err;
}
void
NetManager::Update(NetConnection::NetManagerEntry& entry, int fd, bool resetTimer)
{
if ((! entry.mAdded) || (mIsForkedChild)) {
return;
}
assert(*entry.mListIt);
NetConnection& conn = **entry.mListIt;
assert(fd >= 0 || ! conn.IsGood());
// Always check if connection has to be removed: this method always
// called before socket fd gets closed.
if (! conn.IsGood() || fd < 0) {
if (entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
assert(mConnectionsCount > 0 &&
entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
entry.mAdded = false;
mConnectionsCount--;
mNumBytesToSend -= entry.mWriteByteCount;
if (mTimerWheelBucketItr == entry.mListIt) {
++mTimerWheelBucketItr;
}
mRemove.splice(mRemove.end(),
mTimerWheel[entry.mTimerWheelSlot], entry.mListIt);
return;
}
if (&conn == mCurConnection) {
// Defer all updates for the currently dispatched connection until the
// end of the event dispatch loop.
return;
}
// Update timer.
if (resetTimer) {
const int timeOut = conn.GetInactivityTimeout();
if (timeOut >= 0) {
entry.mExpirationTime = mNow + timeOut;
}
UpdateTimer(entry, timeOut);
}
// Update pending send.
assert(entry.mWriteByteCount >= 0 &&
entry.mWriteByteCount <= mNumBytesToSend);
mNumBytesToSend -= entry.mWriteByteCount;
entry.mWriteByteCount = std::max(0, conn.GetNumBytesToWrite());
mNumBytesToSend += entry.mWriteByteCount;
// Update poll set.
const bool in = conn.IsReadReady() &&
(! mIsOverloaded || entry.mEnableReadIfOverloaded);
const bool out = conn.IsWriteReady() || entry.mConnectPending;
if (in != entry.mIn || out != entry.mOut) {
assert(fd >= 0);
const int op =
(in ? FdPoll::kOpTypeIn : 0) + (out ? FdPoll::kOpTypeOut : 0);
if (fd != entry.mFd && entry.mFd >= 0) {
CheckFatalSysError(
mPoll.Remove(entry.mFd),
"failed to removed fd from poll set"
);
entry.mFd = -1;
}
if (entry.mFd < 0) {
if (op && CheckFatalSysError(
mPoll.Add(fd, op, &conn),
"failed to add fd to poll set") == 0) {
entry.mFd = fd;
}
} else {
CheckFatalSysError(
mPoll.Set(fd, op, &conn),
"failed to change pool flags"
);
}
entry.mIn = in && entry.mFd >= 0;
entry.mOut = out && entry.mFd >= 0;
}
}
void
NetManager::MainLoop()
{
mNow = time(0);
time_t lastTimerTime = mNow;
CheckFatalSysError(
mPoll.Add(globals().netKicker.GetFd(), FdPoll::kOpTypeIn),
"failed to add net kicker's fd to poll set"
);
const int timerOverrunWarningTime(mTimeoutMs / (1000/2));
while (mRunFlag) {
const bool wasOverloaded = mIsOverloaded;
CheckIfOverloaded();
if (mIsOverloaded != wasOverloaded) {
KFS_LOG_VA_INFO(
"%s (%0.f bytes to send; %d disk IO's) ",
mIsOverloaded ?
"System is now in overloaded state " :
"Clearing system overload state",
double(mNumBytesToSend),
globals().diskManager.NumDiskIOOutstanding());
for (int i = 0; i <= kTimerWheelSize; i++) {
for (List::iterator c = mTimerWheel[i].begin();
c != mTimerWheel[i].end(); ) {
assert(*c);
NetConnection& conn = **c;
++c;
conn.Update(false);
}
}
}
const int ret = mPoll.Poll(mConnectionsCount + 1, mTimeoutMs);
if (ret < 0 && ret != -EINTR && ret != -EAGAIN) {
std::string const msg = KFSUtils::SysError(-ret);
KFS_LOG_VA_ERROR("poll errror %d %s", -ret, msg.c_str());
}
globals().netKicker.Drain();
const int64_t nowMs = ITimeout::NowMs();
mNow = time_t(nowMs / 1000);
globals().diskManager.ReapCompletedIOs();
// Unregister will set pointer to 0, but will never remove the list
// node, so that the iterator always remains valid.
for (std::list<ITimeout *>::iterator it = mTimeoutHandlers.begin();
it != mTimeoutHandlers.end(); ) {
if (*it) {
(*it)->TimerExpired(nowMs);
}
if (*it) {
++it;
} else {
it = mTimeoutHandlers.erase(it);
}
}
/// Process poll events.
int op;
void* ptr;
while (mPoll.Next(op, ptr)) {
if (op == 0 || ! ptr) {
continue;
}
NetConnection& conn = *reinterpret_cast<NetConnection*>(ptr);
if (! conn.GetNetMangerEntry(*this)->mAdded) {
// Skip stale event, the conection should be in mRemove list.
continue;
}
// Defer update for this connection.
mCurConnection = &conn;
if ((op & FdPoll::kOpTypeIn) != 0 && conn.IsGood()) {
conn.HandleReadEvent();
}
if ((op & FdPoll::kOpTypeOut) != 0 && conn.IsGood()) {
conn.HandleWriteEvent();
}
if ((op & (FdPoll::kOpTypeError | FdPoll::kOpTypeHup)) != 0 &&
conn.IsGood()) {
conn.HandleErrorEvent();
}
// Try to write, if the last write was sucessfull.
conn.StartFlush();
// Update the connection.
mCurConnection = 0;
conn.Update();
}
mRemove.clear();
mNow = time(0);
int slotCnt = std::min(int(kTimerWheelSize), int(mNow - lastTimerTime));
if (slotCnt > timerOverrunWarningTime) {
KFS_LOG_VA_DEBUG("Timer overrun %d seconds detected", slotCnt - 1);
}
mTimerRunningFlag = true;
while (slotCnt-- > 0) {
List& bucket = mTimerWheel[mCurTimerWheelSlot];
mTimerWheelBucketItr = bucket.begin();
while (mTimerWheelBucketItr != bucket.end()) {
assert(*mTimerWheelBucketItr);
NetConnection& conn = **mTimerWheelBucketItr;
assert(conn.IsGood());
++mTimerWheelBucketItr;
NetConnection::NetManagerEntry& entry =
*conn.GetNetMangerEntry(*this);
const int timeOut = conn.GetInactivityTimeout();
if (timeOut < 0) {
// No timeout, move it to the corresponding list.
UpdateTimer(entry, timeOut);
} else if (entry.mExpirationTime <= mNow) {
conn.HandleTimeoutEvent();
} else {
// Not expired yet, move to the new slot, taking into the
// account possible timer overrun.
UpdateTimer(entry,
slotCnt + int(entry.mExpirationTime - mNow));
}
}
if (++mCurTimerWheelSlot >= kTimerWheelSize) {
mCurTimerWheelSlot = 0;
}
mRemove.clear();
}
mTimerRunningFlag = false;
lastTimerTime = mNow;
mTimerWheelBucketItr = mRemove.end();
}
CheckFatalSysError(
mPoll.Remove(globals().netKicker.GetFd()),
"failed to removed net kicker's fd from poll set"
);
CleanUp();
}
void
NetManager::CheckIfOverloaded()
{
if (mMaxOutgoingBacklog > 0) {
if (!mNetworkOverloaded) {
mNetworkOverloaded = (mNumBytesToSend > mMaxOutgoingBacklog);
} else if (mNumBytesToSend <= mMaxOutgoingBacklog / 2) {
// network was overloaded and that has now cleared
mNetworkOverloaded = false;
}
}
mIsOverloaded = mDiskOverloaded || mNetworkOverloaded;
}
void
NetManager::ChangeDiskOverloadState(bool v)
{
if (mDiskOverloaded == v)
return;
mDiskOverloaded = v;
}
void
NetManager::CleanUp()
{
mTimeoutHandlers.clear();
for (int i = 0; i <= kTimerWheelSize; i++) {
for (mTimerWheelBucketItr = mTimerWheel[i].begin();
mTimerWheelBucketItr != mTimerWheel[i].end(); ) {
NetConnection* const conn = mTimerWheelBucketItr->get();
++mTimerWheelBucketItr;
if (conn) {
if (conn->IsGood()) {
conn->HandleErrorEvent();
}
conn->Close();
}
}
assert(mTimerWheel[i].empty());
mRemove.clear();
}
mTimerWheelBucketItr = mRemove.end();
}
<|endoftext|> |
<commit_before><commit_msg>Dreamview: fix format string for unsigned int (#10134)<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_gflags.h"
DEFINE_bool(planning_test_mode, false, "Enable planning test mode.");
DEFINE_int32(planning_loop_rate, 10, "Loop rate for planning node");
DEFINE_string(planning_adapter_config_filename,
"modules/planning/conf/adapter.conf",
"The adapter configuration file");
DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv",
"Loop rate for planning node");
DEFINE_uint64(rtk_trajectory_forward, 800,
"The number of points to be included in RTK trajectory "
"after the matched point");
DEFINE_double(rtk_trajectory_resolution, 0.01,
"The time resolution of output trajectory for rtk planner.");
DEFINE_bool(publish_estop, false, "publish estop decision in planning");
DEFINE_bool(enable_trajectory_stitcher, true, "enable stitching trajectory");
DEFINE_double(
look_backward_distance, 30,
"look backward this distance when creating reference line from routing");
DEFINE_double(look_forward_short_distance, 150,
"short look forward this distance when creating reference line "
"from routing when ADC is slow");
DEFINE_double(
look_forward_long_distance, 250,
"look forward this distance when creating reference line from routing");
DEFINE_double(look_forward_time_sec, 8.0,
"look forward time times adc speed to calculate this distance "
"when creating reference line from routing");
DEFINE_bool(enable_reference_line_stitching, true,
"Enable stitching reference line, which can reducing computing "
"time and improve stabilty");
DEFINE_double(look_forward_extend_distance, 50,
"The step size when extending reference line.");
DEFINE_double(reference_line_stitch_overlap_distance, 20,
"The overlap distance with the existing reference line when "
"stitching the existing reference line");
DEFINE_double(reference_line_lateral_buffer, 1.0,
"When creating reference line, the minimum distance with road "
"curb for a vehicle driving on this line.");
DEFINE_double(prepare_rerouting_time, 2.0,
"If there are this amount of seconds left to finish driving on "
"current route, and there is no routing, do rerouting");
DEFINE_double(rerouting_cooldown_time, 0.6,
"Wait for at least this amount of seconds before send another "
"rerouting request");
DEFINE_bool(enable_smooth_reference_line, true,
"enable smooth the map reference line");
DEFINE_bool(enable_spiral_reference_line, false,
"enable new spiral based reference line");
DEFINE_double(spiral_smoother_max_deviation, 0.1,
"The max deviation of spiral reference line smoother.");
DEFINE_int32(spiral_smoother_num_iteration, 1000,
"The iteration num of spiral reference line smoother.");
DEFINE_double(spiral_smoother_piecewise_length, 10.0,
"The piecewise length of spiral smoother.");
DEFINE_double(spiral_reference_line_resolution, 0.02,
"The output resolution for reference line.");
DEFINE_bool(prioritize_change_lane, false,
"change lane strategy has higher priority, always use a valid "
"change lane path if such path exists");
DEFINE_bool(reckless_change_lane, false,
"Alway allow the vehicle change lane. The vehicle may contineous "
"change lane. This is mainly test purpose");
DEFINE_double(change_lane_fail_freeze_time, 3.0,
"seconds. Not allowed to change lane this amount of time "
"if it just finished change lane or failed to change lane");
DEFINE_double(change_lane_success_freeze_time, 3.0,
"seconds. Not allowed to change lane this amount of time "
"if it just finished change lane or failed to change lane");
DEFINE_double(change_lane_min_length, 30.0,
"meters. If the change lane target has longer length than this "
"threshold, it can shortcut the default lane.");
DEFINE_bool(enable_change_lane_decider, false,
"True to use change lane state machine decider.");
DEFINE_int32(max_history_frame_num, 1, "The maximum history frame number");
DEFINE_double(max_collision_distance, 0.1,
"considered as collision if distance (meters) is smaller than or "
"equal to this (meters)");
DEFINE_double(replan_lateral_distance_threshold, 5.0,
"The distance threshold of replan");
DEFINE_double(replan_longitudinal_distance_threshold, 5.0,
"The distance threshold of replan");
DEFINE_bool(estimate_current_vehicle_state, true,
"Estimate current vehicle state.");
DEFINE_bool(enable_reference_line_provider_thread, true,
"Enable reference line provider thread.");
DEFINE_double(default_reference_line_width, 4.0,
"Default reference line width");
DEFINE_double(smoothed_reference_line_max_diff, 5.0,
"Maximum position difference between the smoothed and the raw "
"reference lines.");
DEFINE_double(planning_upper_speed_limit, 31.3,
"Maximum speed (m/s) in planning.");
DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length");
// planning trajectory output time density control
DEFINE_double(
trajectory_time_min_interval, 0.02,
"(seconds) Trajectory time interval when publish. The is the min value.");
DEFINE_double(
trajectory_time_max_interval, 0.1,
"(seconds) Trajectory time interval when publish. The is the max value.");
DEFINE_double(
trajectory_time_high_density_period, 1.0,
"(seconds) Keep high density in the next this amount of seconds. ");
DEFINE_bool(enable_trajectory_check, false,
"Enable sanity check for planning trajectory.");
DEFINE_double(speed_lower_bound, -0.02, "The lowest speed allowed.");
DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed.");
DEFINE_double(longitudinal_acceleration_lower_bound, -4.5,
"The lowest longitudinal acceleration allowed.");
DEFINE_double(longitudinal_acceleration_upper_bound, 4.0,
"The highest longitudinal acceleration allowed.");
DEFINE_double(lateral_jerk_bound, 4.0,
"Bound of lateral jerk; symmetric for left and right");
DEFINE_double(longitudinal_jerk_lower_bound, -4.0,
"The lower bound of longitudinal jerk.");
DEFINE_double(longitudinal_jerk_upper_bound, 4.0,
"The upper bound of longitudinal jerk.");
DEFINE_double(dl_bound, 0.10,
"The bound for derivative l in s-l coordinate system.");
DEFINE_double(kappa_bound, 0.20, "The bound for vehicle curvature");
DEFINE_double(dkappa_bound, 0.02,
"The bound for vehicle curvature change rate");
// ST Boundary
DEFINE_double(st_max_s, 100, "the maximum s of st boundary");
DEFINE_double(st_max_t, 8, "the maximum t of st boundary");
// Decision Part
DEFINE_double(static_obstacle_speed_threshold, 1.0,
"obstacles are considered as static obstacle if its speed is "
"less than this value (m/s)");
DEFINE_bool(enable_nudge_decision, true, "enable nudge decision");
DEFINE_bool(enable_nudge_slowdown, true,
"True to slow down when nudge obstacles.");
DEFINE_double(static_decision_nudge_l_buffer, 0.3, "l buffer for nudge");
DEFINE_double(longitudinal_ignore_buffer, 10.0,
"If an obstacle's longitudinal distance is further away "
"than this distance, ignore it");
DEFINE_double(lateral_ignore_buffer, 3.0,
"If an obstacle's lateral distance is further away than this "
"distance, ignore it");
DEFINE_double(max_stop_distance_obstacle, 10.0,
"max stop distance from in-lane obstacle (meters)");
DEFINE_double(min_stop_distance_obstacle, 3.0,
"min stop distance from in-lane obstacle (meters)");
DEFINE_double(stop_distance_destination, 0.5,
"stop distance from destination line");
DEFINE_double(stop_distance_traffic_light, 3.0,
"stop distance from traffic light line");
DEFINE_double(destination_check_distance, 5.0,
"if the distance between destination and ADC is less than this,"
" it is considered to reach destination");
DEFINE_double(nudge_distance_obstacle, 0.3,
"minimum distance to nudge a obstacle (meters)");
DEFINE_double(follow_min_distance, 3.0,
"min follow distance for vehicles/bicycles/moving objects");
DEFINE_double(yield_min_distance, 3.0,
"min yield distance for vehicles/bicycles/moving objects");
DEFINE_double(
follow_time_buffer, 2.0,
"follow time buffer (in second) to calculate the following distance.");
DEFINE_double(
follow_min_time_sec, 0.1,
"min following time in st region before considering a valid follow");
DEFINE_string(destination_obstacle_id, "DEST",
"obstacle id for converting destination to an obstacle");
DEFINE_double(virtual_stop_wall_length, 0.1,
"virtual stop wall length (meters)");
DEFINE_double(virtual_stop_wall_height, 2.0,
"virtual stop wall height (meters)");
DEFINE_string(reference_line_end_obstacle_id, "REF_END",
"Obstacle id for the end of reference line obstacle");
DEFINE_double(signal_expire_time_sec, 5.0,
"consider the signal msg is expired if its timestamp over "
"this threshold (second)");
// Speed Decider
DEFINE_double(low_speed_obstacle_threshold, 2.0,
"speed lower than this value is considered as low speed");
DEFINE_double(
decelerating_obstacle_threshold, -0.25,
"acceleration lower than this value is considered as decelerating");
// Prediction Part
DEFINE_double(prediction_total_time, 5.0, "Total prediction time");
DEFINE_bool(align_prediction_time, false,
"enable align prediction data based planning time");
// Trajectory
DEFINE_bool(enable_rule_layer, true,
"enable rule for trajectory before model computation");
// Traffic decision
/// common
DEFINE_double(stop_max_distance_buffer, 4.0,
"distance buffer of passing stop line");
DEFINE_double(stop_min_speed, 0.2, "min speed(m/s) for computing stop");
DEFINE_double(stop_max_deceleration, 6.0, "max deceleration");
DEFINE_double(max_valid_stop_distance, 2.0,
"max distance(m) to the stop line to be "
"considered as a valid stop");
/// Clear Zone
DEFINE_string(clear_zone_virtual_object_id_prefix, "CZ_",
"prefix for converting clear zone id to virtual object id");
/// traffic light
DEFINE_string(signal_light_virtual_object_id_prefix, "SL_",
"prefix for converting signal id to virtual object id");
DEFINE_double(max_deacceleration_for_yellow_light_stop, 2.0,
"treat yellow light as red when deceleration (abstract value"
" in m/s^2) is less than this threshold; otherwise treated"
" as green light");
/// crosswalk
DEFINE_bool(enable_crosswalk, false, "enable crosswalk");
DEFINE_string(crosswalk_virtual_object_id_prefix, "CW_",
"prefix for converting crosswalk id to virtual object id");
DEFINE_double(crosswalk_expand_distance, 2.0,
"crosswalk expand distance(meter) "
"for pedestrian/bicycle detection");
DEFINE_double(crosswalk_strick_l_distance, 4.0,
"strick stop rule within this l_distance");
DEFINE_double(crosswalk_loose_l_distance, 5.0,
"loose stop rule beyond this l_distance");
/// stop_sign
DEFINE_bool(enable_stop_sign, false, "enable stop_sign");
DEFINE_string(stop_sign_virtual_object_id_prefix, "SS_",
"prefix for converting stop_sign id to virtual object id");
DEFINE_double(stop_duration_for_stop_sign, 3,
"min time(second) to stop at stop sign");
DEFINE_double(max_distance_stop_sign_waiting_area, 3,
"max distance(meter) to be considered as "
"having arrived stop sign waiting area");
// according to DMV's rule, turn signal should be on within 200 ft from
// intersection.
DEFINE_double(
turn_signal_distance, 60.96,
"In meters. If there is a turn within this distance, use turn signal");
DEFINE_bool(right_turn_creep_forward, false,
"Creep forward at right turn when the signal is red and traffic "
"rule is not violated.");
// planning config file
DEFINE_string(planning_config_file,
"modules/planning/conf/planning_config.pb.txt",
"planning config file");
DEFINE_int32(trajectory_point_num_for_debug, 10,
"number of output trajectory points for debugging");
DEFINE_double(decision_valid_stop_range, 0.5,
"The valid stop range in decision.");
DEFINE_bool(enable_record_debug, true,
"True to enable record debug into debug protobuf.");
DEFINE_bool(enable_prediction, true, "True to enable prediction input.");
DEFINE_bool(enable_lag_prediction, true,
"Enable lagged prediction, which is more tolerant to obstacles "
"that appear and disappear dequeickly");
DEFINE_int32(lag_prediction_min_appear_num, 5,
"The minimum of appearance of the obstacle for lagged prediction");
DEFINE_double(lag_prediction_max_disappear_num, 3,
"In lagged prediction, ingnore obstacle disappeared for more "
"than this value");
DEFINE_bool(enable_traffic_light, true, "True to enable traffic light input.");
// QpSt optimizer
DEFINE_bool(enable_slowdown_profile_generator, true,
"True to enable slowdown speed profile generator.");
DEFINE_double(slowdown_profile_deceleration, -1.0,
"The deceleration to generate slowdown profile. unit: m/s^2.");
DEFINE_bool(enable_follow_accel_constraint, true,
"Enable follow acceleration constraint.");
// SQP solver
DEFINE_bool(enable_sqp_solver, true, "True to enable SQP solver.");
<commit_msg>planning: changed max stop acc limit for yellow light.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_gflags.h"
DEFINE_bool(planning_test_mode, false, "Enable planning test mode.");
DEFINE_int32(planning_loop_rate, 10, "Loop rate for planning node");
DEFINE_string(planning_adapter_config_filename,
"modules/planning/conf/adapter.conf",
"The adapter configuration file");
DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv",
"Loop rate for planning node");
DEFINE_uint64(rtk_trajectory_forward, 800,
"The number of points to be included in RTK trajectory "
"after the matched point");
DEFINE_double(rtk_trajectory_resolution, 0.01,
"The time resolution of output trajectory for rtk planner.");
DEFINE_bool(publish_estop, false, "publish estop decision in planning");
DEFINE_bool(enable_trajectory_stitcher, true, "enable stitching trajectory");
DEFINE_double(
look_backward_distance, 30,
"look backward this distance when creating reference line from routing");
DEFINE_double(look_forward_short_distance, 150,
"short look forward this distance when creating reference line "
"from routing when ADC is slow");
DEFINE_double(
look_forward_long_distance, 250,
"look forward this distance when creating reference line from routing");
DEFINE_double(look_forward_time_sec, 8.0,
"look forward time times adc speed to calculate this distance "
"when creating reference line from routing");
DEFINE_bool(enable_reference_line_stitching, true,
"Enable stitching reference line, which can reducing computing "
"time and improve stabilty");
DEFINE_double(look_forward_extend_distance, 50,
"The step size when extending reference line.");
DEFINE_double(reference_line_stitch_overlap_distance, 20,
"The overlap distance with the existing reference line when "
"stitching the existing reference line");
DEFINE_double(reference_line_lateral_buffer, 1.0,
"When creating reference line, the minimum distance with road "
"curb for a vehicle driving on this line.");
DEFINE_double(prepare_rerouting_time, 2.0,
"If there are this amount of seconds left to finish driving on "
"current route, and there is no routing, do rerouting");
DEFINE_double(rerouting_cooldown_time, 0.6,
"Wait for at least this amount of seconds before send another "
"rerouting request");
DEFINE_bool(enable_smooth_reference_line, true,
"enable smooth the map reference line");
DEFINE_bool(enable_spiral_reference_line, false,
"enable new spiral based reference line");
DEFINE_double(spiral_smoother_max_deviation, 0.1,
"The max deviation of spiral reference line smoother.");
DEFINE_int32(spiral_smoother_num_iteration, 1000,
"The iteration num of spiral reference line smoother.");
DEFINE_double(spiral_smoother_piecewise_length, 10.0,
"The piecewise length of spiral smoother.");
DEFINE_double(spiral_reference_line_resolution, 0.02,
"The output resolution for reference line.");
DEFINE_bool(prioritize_change_lane, false,
"change lane strategy has higher priority, always use a valid "
"change lane path if such path exists");
DEFINE_bool(reckless_change_lane, false,
"Alway allow the vehicle change lane. The vehicle may contineous "
"change lane. This is mainly test purpose");
DEFINE_double(change_lane_fail_freeze_time, 3.0,
"seconds. Not allowed to change lane this amount of time "
"if it just finished change lane or failed to change lane");
DEFINE_double(change_lane_success_freeze_time, 3.0,
"seconds. Not allowed to change lane this amount of time "
"if it just finished change lane or failed to change lane");
DEFINE_double(change_lane_min_length, 30.0,
"meters. If the change lane target has longer length than this "
"threshold, it can shortcut the default lane.");
DEFINE_bool(enable_change_lane_decider, false,
"True to use change lane state machine decider.");
DEFINE_int32(max_history_frame_num, 1, "The maximum history frame number");
DEFINE_double(max_collision_distance, 0.1,
"considered as collision if distance (meters) is smaller than or "
"equal to this (meters)");
DEFINE_double(replan_lateral_distance_threshold, 5.0,
"The distance threshold of replan");
DEFINE_double(replan_longitudinal_distance_threshold, 5.0,
"The distance threshold of replan");
DEFINE_bool(estimate_current_vehicle_state, true,
"Estimate current vehicle state.");
DEFINE_bool(enable_reference_line_provider_thread, true,
"Enable reference line provider thread.");
DEFINE_double(default_reference_line_width, 4.0,
"Default reference line width");
DEFINE_double(smoothed_reference_line_max_diff, 5.0,
"Maximum position difference between the smoothed and the raw "
"reference lines.");
DEFINE_double(planning_upper_speed_limit, 31.3,
"Maximum speed (m/s) in planning.");
DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length");
// planning trajectory output time density control
DEFINE_double(
trajectory_time_min_interval, 0.02,
"(seconds) Trajectory time interval when publish. The is the min value.");
DEFINE_double(
trajectory_time_max_interval, 0.1,
"(seconds) Trajectory time interval when publish. The is the max value.");
DEFINE_double(
trajectory_time_high_density_period, 1.0,
"(seconds) Keep high density in the next this amount of seconds. ");
DEFINE_bool(enable_trajectory_check, false,
"Enable sanity check for planning trajectory.");
DEFINE_double(speed_lower_bound, -0.02, "The lowest speed allowed.");
DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed.");
DEFINE_double(longitudinal_acceleration_lower_bound, -4.5,
"The lowest longitudinal acceleration allowed.");
DEFINE_double(longitudinal_acceleration_upper_bound, 4.0,
"The highest longitudinal acceleration allowed.");
DEFINE_double(lateral_jerk_bound, 4.0,
"Bound of lateral jerk; symmetric for left and right");
DEFINE_double(longitudinal_jerk_lower_bound, -4.0,
"The lower bound of longitudinal jerk.");
DEFINE_double(longitudinal_jerk_upper_bound, 4.0,
"The upper bound of longitudinal jerk.");
DEFINE_double(dl_bound, 0.10,
"The bound for derivative l in s-l coordinate system.");
DEFINE_double(kappa_bound, 0.20, "The bound for vehicle curvature");
DEFINE_double(dkappa_bound, 0.02,
"The bound for vehicle curvature change rate");
// ST Boundary
DEFINE_double(st_max_s, 100, "the maximum s of st boundary");
DEFINE_double(st_max_t, 8, "the maximum t of st boundary");
// Decision Part
DEFINE_double(static_obstacle_speed_threshold, 1.0,
"obstacles are considered as static obstacle if its speed is "
"less than this value (m/s)");
DEFINE_bool(enable_nudge_decision, true, "enable nudge decision");
DEFINE_bool(enable_nudge_slowdown, true,
"True to slow down when nudge obstacles.");
DEFINE_double(static_decision_nudge_l_buffer, 0.3, "l buffer for nudge");
DEFINE_double(longitudinal_ignore_buffer, 10.0,
"If an obstacle's longitudinal distance is further away "
"than this distance, ignore it");
DEFINE_double(lateral_ignore_buffer, 3.0,
"If an obstacle's lateral distance is further away than this "
"distance, ignore it");
DEFINE_double(max_stop_distance_obstacle, 10.0,
"max stop distance from in-lane obstacle (meters)");
DEFINE_double(min_stop_distance_obstacle, 3.0,
"min stop distance from in-lane obstacle (meters)");
DEFINE_double(stop_distance_destination, 0.5,
"stop distance from destination line");
DEFINE_double(stop_distance_traffic_light, 3.0,
"stop distance from traffic light line");
DEFINE_double(destination_check_distance, 5.0,
"if the distance between destination and ADC is less than this,"
" it is considered to reach destination");
DEFINE_double(nudge_distance_obstacle, 0.3,
"minimum distance to nudge a obstacle (meters)");
DEFINE_double(follow_min_distance, 3.0,
"min follow distance for vehicles/bicycles/moving objects");
DEFINE_double(yield_min_distance, 3.0,
"min yield distance for vehicles/bicycles/moving objects");
DEFINE_double(
follow_time_buffer, 2.0,
"follow time buffer (in second) to calculate the following distance.");
DEFINE_double(
follow_min_time_sec, 0.1,
"min following time in st region before considering a valid follow");
DEFINE_string(destination_obstacle_id, "DEST",
"obstacle id for converting destination to an obstacle");
DEFINE_double(virtual_stop_wall_length, 0.1,
"virtual stop wall length (meters)");
DEFINE_double(virtual_stop_wall_height, 2.0,
"virtual stop wall height (meters)");
DEFINE_string(reference_line_end_obstacle_id, "REF_END",
"Obstacle id for the end of reference line obstacle");
DEFINE_double(signal_expire_time_sec, 5.0,
"consider the signal msg is expired if its timestamp over "
"this threshold (second)");
// Speed Decider
DEFINE_double(low_speed_obstacle_threshold, 2.0,
"speed lower than this value is considered as low speed");
DEFINE_double(
decelerating_obstacle_threshold, -0.25,
"acceleration lower than this value is considered as decelerating");
// Prediction Part
DEFINE_double(prediction_total_time, 5.0, "Total prediction time");
DEFINE_bool(align_prediction_time, false,
"enable align prediction data based planning time");
// Trajectory
DEFINE_bool(enable_rule_layer, true,
"enable rule for trajectory before model computation");
// Traffic decision
/// common
DEFINE_double(stop_max_distance_buffer, 4.0,
"distance buffer of passing stop line");
DEFINE_double(stop_min_speed, 0.2, "min speed(m/s) for computing stop");
DEFINE_double(stop_max_deceleration, 6.0, "max deceleration");
DEFINE_double(max_valid_stop_distance, 2.0,
"max distance(m) to the stop line to be "
"considered as a valid stop");
/// Clear Zone
DEFINE_string(clear_zone_virtual_object_id_prefix, "CZ_",
"prefix for converting clear zone id to virtual object id");
/// traffic light
DEFINE_string(signal_light_virtual_object_id_prefix, "SL_",
"prefix for converting signal id to virtual object id");
DEFINE_double(max_deacceleration_for_yellow_light_stop, 3.0,
"treat yellow light as red when deceleration (abstract value"
" in m/s^2) is less than this threshold; otherwise treated"
" as green light");
/// crosswalk
DEFINE_bool(enable_crosswalk, false, "enable crosswalk");
DEFINE_string(crosswalk_virtual_object_id_prefix, "CW_",
"prefix for converting crosswalk id to virtual object id");
DEFINE_double(crosswalk_expand_distance, 2.0,
"crosswalk expand distance(meter) "
"for pedestrian/bicycle detection");
DEFINE_double(crosswalk_strick_l_distance, 4.0,
"strick stop rule within this l_distance");
DEFINE_double(crosswalk_loose_l_distance, 5.0,
"loose stop rule beyond this l_distance");
/// stop_sign
DEFINE_bool(enable_stop_sign, false, "enable stop_sign");
DEFINE_string(stop_sign_virtual_object_id_prefix, "SS_",
"prefix for converting stop_sign id to virtual object id");
DEFINE_double(stop_duration_for_stop_sign, 3,
"min time(second) to stop at stop sign");
DEFINE_double(max_distance_stop_sign_waiting_area, 3,
"max distance(meter) to be considered as "
"having arrived stop sign waiting area");
// according to DMV's rule, turn signal should be on within 200 ft from
// intersection.
DEFINE_double(
turn_signal_distance, 60.96,
"In meters. If there is a turn within this distance, use turn signal");
DEFINE_bool(right_turn_creep_forward, false,
"Creep forward at right turn when the signal is red and traffic "
"rule is not violated.");
// planning config file
DEFINE_string(planning_config_file,
"modules/planning/conf/planning_config.pb.txt",
"planning config file");
DEFINE_int32(trajectory_point_num_for_debug, 10,
"number of output trajectory points for debugging");
DEFINE_double(decision_valid_stop_range, 0.5,
"The valid stop range in decision.");
DEFINE_bool(enable_record_debug, true,
"True to enable record debug into debug protobuf.");
DEFINE_bool(enable_prediction, true, "True to enable prediction input.");
DEFINE_bool(enable_lag_prediction, true,
"Enable lagged prediction, which is more tolerant to obstacles "
"that appear and disappear dequeickly");
DEFINE_int32(lag_prediction_min_appear_num, 5,
"The minimum of appearance of the obstacle for lagged prediction");
DEFINE_double(lag_prediction_max_disappear_num, 3,
"In lagged prediction, ingnore obstacle disappeared for more "
"than this value");
DEFINE_bool(enable_traffic_light, true, "True to enable traffic light input.");
// QpSt optimizer
DEFINE_bool(enable_slowdown_profile_generator, true,
"True to enable slowdown speed profile generator.");
DEFINE_double(slowdown_profile_deceleration, -1.0,
"The deceleration to generate slowdown profile. unit: m/s^2.");
DEFINE_bool(enable_follow_accel_constraint, true,
"Enable follow acceleration constraint.");
// SQP solver
DEFINE_bool(enable_sqp_solver, true, "True to enable SQP solver.");
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: document_statistic.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2007-09-06 14:23:59 $
*
* 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"
#ifdef _MSC_VER
#pragma warning (disable : 4786 4503)
#endif
#ifndef DOCUMENT_STATISTIC_HXX_INCLUDED
#include "document_statistic.hxx"
#endif
#ifndef UTILITIES_HXX_INCLUDED
#include "internal/utilities.hxx"
#endif
#ifndef METAINFOREADER_HXX_INCLUDED
#include "internal/metainforeader.hxx"
#endif
#ifndef RESOURCE_H_INCLUDED
#include "internal/resource.h"
#endif
#ifndef FILEEXTENSIONS_HXX_INCLUDED
#include "internal/fileextensions.hxx"
#endif
#ifndef CONFIG_HXX_INCLUDED
#include "internal/config.hxx"
#endif
#ifndef ISO8601_CONVERTER_HXX_INCLUDED
#include "internal/iso8601_converter.hxx"
#endif
//#####################################
const bool READONLY = false;
const bool WRITEABLE = true;
//#####################################
document_statistic_reader_ptr create_document_statistic_reader(const std::string& document_name, CMetaInfoReader* meta_info_accessor)
{
File_Type_t file_type = get_file_type(document_name);
if (WRITER == file_type)
return document_statistic_reader_ptr(new writer_document_statistic_reader(document_name, meta_info_accessor));
else if (CALC == file_type)
return document_statistic_reader_ptr(new calc_document_statistic_reader(document_name, meta_info_accessor));
else
return document_statistic_reader_ptr(new draw_impress_math_document_statistic_reader(document_name, meta_info_accessor));
}
//#####################################
document_statistic_reader::document_statistic_reader(const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_name_(document_name),
meta_info_accessor_(meta_info_accessor)
{}
//#####################################
document_statistic_reader::~document_statistic_reader()
{}
//#####################################
void document_statistic_reader::read(statistic_group_list_t* group_list)
{
group_list->clear();
fill_description_section(meta_info_accessor_, group_list);
fill_origin_section(meta_info_accessor_, group_list);
}
//#####################################
std::string document_statistic_reader::get_document_name() const
{
return document_name_;
}
//#####################################
void document_statistic_reader::fill_origin_section(CMetaInfoReader *meta_info_accessor, statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_AUTHOR), meta_info_accessor->getTagData( META_INFO_AUTHOR ), READONLY));
il.push_back(statistic_item(GetResString(IDS_MODIFIED),
iso8601_date_to_local_date(meta_info_accessor->getTagData(META_INFO_MODIFIED )), READONLY));
il.push_back(statistic_item(GetResString(IDS_DOCUMENT_NUMBER), meta_info_accessor->getTagData( META_INFO_DOCUMENT_NUMBER ), READONLY));
il.push_back(statistic_item(GetResString(IDS_EDITING_TIME),
iso8601_duration_to_local_duration(meta_info_accessor->getTagData( META_INFO_EDITING_TIME )), READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_ORIGIN), il));
}
//#####################################
writer_document_statistic_reader::writer_document_statistic_reader(const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_statistic_reader(document_name, meta_info_accessor)
{}
//#####################################
void writer_document_statistic_reader::fill_description_section(CMetaInfoReader *meta_info_accessor, statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_TITLE), meta_info_accessor->getTagData( META_INFO_TITLE ), READONLY));
il.push_back(statistic_item(GetResString(IDS_COMMENTS), meta_info_accessor->getTagData( META_INFO_DESCRIPTION ), READONLY));
il.push_back(statistic_item(GetResString(IDS_SUBJECT), meta_info_accessor->getTagData( META_INFO_SUBJECT ), READONLY));
il.push_back(statistic_item(GetResString(IDS_KEYWORDS), meta_info_accessor->getTagData(META_INFO_KEYWORDS ), READONLY));
il.push_back(statistic_item(GetResString(IDS_PAGES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_PAGES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_TABLES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_TABLES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_GRAPHICS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_DRAWS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_OLE_OBJECTS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_OBJECTS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_PARAGRAPHS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_PARAGRAPHS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_WORDS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_WORDS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_CHARACTERS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_CHARACTERS) , READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_DESCRIPTION), il));
}
//#######################################
calc_document_statistic_reader::calc_document_statistic_reader(
const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_statistic_reader(document_name, meta_info_accessor)
{}
//#######################################
void calc_document_statistic_reader::fill_description_section(
CMetaInfoReader *meta_info_accessor,statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_TITLE), meta_info_accessor->getTagData( META_INFO_TITLE ), READONLY));
il.push_back(statistic_item(GetResString(IDS_COMMENTS), meta_info_accessor->getTagData( META_INFO_DESCRIPTION ), READONLY));
il.push_back(statistic_item(GetResString(IDS_SUBJECT), meta_info_accessor->getTagData( META_INFO_SUBJECT ), READONLY));
il.push_back(statistic_item(GetResString(IDS_KEYWORDS), meta_info_accessor->getTagData(META_INFO_KEYWORDS ), READONLY));
il.push_back(statistic_item(GetResString(IDS_TABLES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_TABLES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_CELLS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_CELLS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_OLE_OBJECTS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_OBJECTS) , READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_DESCRIPTION), il));
}
//#######################################
draw_impress_math_document_statistic_reader::draw_impress_math_document_statistic_reader(
const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_statistic_reader(document_name, meta_info_accessor)
{}
//#######################################
void draw_impress_math_document_statistic_reader::fill_description_section(
CMetaInfoReader *meta_info_accessor, statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_TITLE), meta_info_accessor->getTagData( META_INFO_TITLE ), READONLY));
il.push_back(statistic_item(GetResString(IDS_COMMENTS), meta_info_accessor->getTagData( META_INFO_DESCRIPTION ), READONLY));
il.push_back(statistic_item(GetResString(IDS_SUBJECT), meta_info_accessor->getTagData( META_INFO_SUBJECT ), READONLY));
il.push_back(statistic_item(GetResString(IDS_KEYWORDS), meta_info_accessor->getTagData(META_INFO_KEYWORDS ), READONLY));
il.push_back(statistic_item(GetResString(IDS_PAGES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_PAGES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_OLE_OBJECTS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_OBJECTS) , READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_DESCRIPTION), il));
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.44); FILE MERGED 2008/04/01 12:41:15 thb 1.6.44.2: #i85898# Stripping all external header guards 2008/03/31 13:17:13 rt 1.6.44.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: document_statistic.cxx,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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"
#ifdef _MSC_VER
#pragma warning (disable : 4786 4503)
#endif
#include "document_statistic.hxx"
#include "internal/utilities.hxx"
#include "internal/metainforeader.hxx"
#include "internal/resource.h"
#include "internal/fileextensions.hxx"
#include "internal/config.hxx"
#include "internal/iso8601_converter.hxx"
//#####################################
const bool READONLY = false;
const bool WRITEABLE = true;
//#####################################
document_statistic_reader_ptr create_document_statistic_reader(const std::string& document_name, CMetaInfoReader* meta_info_accessor)
{
File_Type_t file_type = get_file_type(document_name);
if (WRITER == file_type)
return document_statistic_reader_ptr(new writer_document_statistic_reader(document_name, meta_info_accessor));
else if (CALC == file_type)
return document_statistic_reader_ptr(new calc_document_statistic_reader(document_name, meta_info_accessor));
else
return document_statistic_reader_ptr(new draw_impress_math_document_statistic_reader(document_name, meta_info_accessor));
}
//#####################################
document_statistic_reader::document_statistic_reader(const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_name_(document_name),
meta_info_accessor_(meta_info_accessor)
{}
//#####################################
document_statistic_reader::~document_statistic_reader()
{}
//#####################################
void document_statistic_reader::read(statistic_group_list_t* group_list)
{
group_list->clear();
fill_description_section(meta_info_accessor_, group_list);
fill_origin_section(meta_info_accessor_, group_list);
}
//#####################################
std::string document_statistic_reader::get_document_name() const
{
return document_name_;
}
//#####################################
void document_statistic_reader::fill_origin_section(CMetaInfoReader *meta_info_accessor, statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_AUTHOR), meta_info_accessor->getTagData( META_INFO_AUTHOR ), READONLY));
il.push_back(statistic_item(GetResString(IDS_MODIFIED),
iso8601_date_to_local_date(meta_info_accessor->getTagData(META_INFO_MODIFIED )), READONLY));
il.push_back(statistic_item(GetResString(IDS_DOCUMENT_NUMBER), meta_info_accessor->getTagData( META_INFO_DOCUMENT_NUMBER ), READONLY));
il.push_back(statistic_item(GetResString(IDS_EDITING_TIME),
iso8601_duration_to_local_duration(meta_info_accessor->getTagData( META_INFO_EDITING_TIME )), READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_ORIGIN), il));
}
//#####################################
writer_document_statistic_reader::writer_document_statistic_reader(const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_statistic_reader(document_name, meta_info_accessor)
{}
//#####################################
void writer_document_statistic_reader::fill_description_section(CMetaInfoReader *meta_info_accessor, statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_TITLE), meta_info_accessor->getTagData( META_INFO_TITLE ), READONLY));
il.push_back(statistic_item(GetResString(IDS_COMMENTS), meta_info_accessor->getTagData( META_INFO_DESCRIPTION ), READONLY));
il.push_back(statistic_item(GetResString(IDS_SUBJECT), meta_info_accessor->getTagData( META_INFO_SUBJECT ), READONLY));
il.push_back(statistic_item(GetResString(IDS_KEYWORDS), meta_info_accessor->getTagData(META_INFO_KEYWORDS ), READONLY));
il.push_back(statistic_item(GetResString(IDS_PAGES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_PAGES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_TABLES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_TABLES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_GRAPHICS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_DRAWS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_OLE_OBJECTS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_OBJECTS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_PARAGRAPHS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_PARAGRAPHS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_WORDS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_WORDS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_CHARACTERS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_CHARACTERS) , READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_DESCRIPTION), il));
}
//#######################################
calc_document_statistic_reader::calc_document_statistic_reader(
const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_statistic_reader(document_name, meta_info_accessor)
{}
//#######################################
void calc_document_statistic_reader::fill_description_section(
CMetaInfoReader *meta_info_accessor,statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_TITLE), meta_info_accessor->getTagData( META_INFO_TITLE ), READONLY));
il.push_back(statistic_item(GetResString(IDS_COMMENTS), meta_info_accessor->getTagData( META_INFO_DESCRIPTION ), READONLY));
il.push_back(statistic_item(GetResString(IDS_SUBJECT), meta_info_accessor->getTagData( META_INFO_SUBJECT ), READONLY));
il.push_back(statistic_item(GetResString(IDS_KEYWORDS), meta_info_accessor->getTagData(META_INFO_KEYWORDS ), READONLY));
il.push_back(statistic_item(GetResString(IDS_TABLES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_TABLES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_CELLS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_CELLS) , READONLY));
il.push_back(statistic_item(GetResString(IDS_OLE_OBJECTS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_OBJECTS) , READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_DESCRIPTION), il));
}
//#######################################
draw_impress_math_document_statistic_reader::draw_impress_math_document_statistic_reader(
const std::string& document_name, CMetaInfoReader* meta_info_accessor) :
document_statistic_reader(document_name, meta_info_accessor)
{}
//#######################################
void draw_impress_math_document_statistic_reader::fill_description_section(
CMetaInfoReader *meta_info_accessor, statistic_group_list_t* group_list)
{
statistic_item_list_t il;
il.push_back(statistic_item(GetResString(IDS_TITLE), meta_info_accessor->getTagData( META_INFO_TITLE ), READONLY));
il.push_back(statistic_item(GetResString(IDS_COMMENTS), meta_info_accessor->getTagData( META_INFO_DESCRIPTION ), READONLY));
il.push_back(statistic_item(GetResString(IDS_SUBJECT), meta_info_accessor->getTagData( META_INFO_SUBJECT ), READONLY));
il.push_back(statistic_item(GetResString(IDS_KEYWORDS), meta_info_accessor->getTagData(META_INFO_KEYWORDS ), READONLY));
il.push_back(statistic_item(GetResString(IDS_PAGES), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_PAGES) , READONLY));
il.push_back(statistic_item(GetResString(IDS_OLE_OBJECTS), meta_info_accessor->getTagAttribute( META_INFO_DOCUMENT_STATISTIC,META_INFO_OBJECTS) , READONLY));
group_list->push_back(statistic_group_t(GetResString(IDS_DESCRIPTION), il));
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <math.h>
#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/drc_lcmtypes.hpp"
inline void
bot_quat_mult (double c[4], const double a[4], const double b[4])
{
c[0] = a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3];
c[1] = a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2];
c[2] = a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1];
c[3] = a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0];
}
void
bot_quat_rotate_rev (const double rot[4], double v[3])
{
double a[4], b[4], c[4];
b[0] = 0;
memcpy (b+1, v, 3 * sizeof (double));
bot_quat_mult (a, b, rot);
b[0] = rot[0];
b[1] = -rot[1];
b[2] = -rot[2];
b[3] = -rot[3];
bot_quat_mult (c, b, a);
memcpy (v, c+1, 3 * sizeof (double));
}
static inline int
feq (double a, double b) {
return fabs (a - b) < 1e-9;
}
void
bot_quat_to_angle_axis (const double q[4], double *theta, double axis[3])
{
double halftheta = acos (q[0]);
*theta = halftheta * 2;
double sinhalftheta = sin (halftheta);
if (feq (halftheta, 0)) {
axis[0] = 0;
axis[1] = 0;
axis[2] = 1;
*theta = 0;
} else {
axis[0] = q[1] / sinhalftheta;
axis[1] = q[2] / sinhalftheta;
axis[2] = q[3] / sinhalftheta;
}
}
class Handler
{
drc::vector_3d_t translation;
drc::quaternion_t rotation;
public:
lcm::LCM lcm;
~Handler() {}
void handleStateMessage(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::robot_state_t* msg) {
// printf("received message on channel \"%s\":\n", channel.c_str());
// printf("timestamp = %11d\n", (long long)msg->utime);
translation = msg->origin_position.translation;
rotation = msg->origin_position.rotation;
};
void handleGoalMessage(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::nav_goal_timed_t* msg) {
printf("start = %f, %f, %f\n", translation.x, translation.y, translation.z);
printf("goal = %f, %f, %f\n", msg->goal_pos.translation.x, msg->goal_pos.translation.y, msg->goal_pos.translation.z);
double translation_to_goal[3] = {msg->goal_pos.translation.x - translation.x, msg->goal_pos.translation.y - translation.y, msg->goal_pos.translation.z - translation.z};
// translation_to_goal[0] = msg->goal_pos.translation.x - translation.x;
// translation_to_goal[1] = msg->goal_pos.translation.y - translation.y;
// translation_to_goal[2] = msg->goal_pos.translation.z - translation.z};
// printf("x vec: %f - %f = %f, %f\n", msg->goal_pos.translation.x, translation.x,msg->goal_pos.translation.x - translation.x, translation_to_goal[0]);
printf("vec to goal: %f, %f, %f\n", translation_to_goal[0], translation_to_goal[1], translation_to_goal[2]);
// double robot_rotation[4] = {rotation.x, rotation.y, rotation.z, rotation.w};
// printf("quaternion: %f, %f, %f, %f\n", rotation.x, rotation.y, rotation.z, rotation.w);
// double rot_axis[3];
// double rot_theta;
// bot_quat_to_angle_axis(robot_rotation, &rot_theta, rot_axis);
// printf("axis: %f, %f, %f\n", rot_axis[0], rot_axis[1], rot_axis[2]);
// printf("angle: %f\n", rot_theta);
// bot_quat_rotate_rev(robot_rotation, translation_to_goal);
printf("vec to goal in robot frame: %f, %f, %f\n", translation_to_goal[0], translation_to_goal[1], translation_to_goal[2]);
// double x_dist = msg->goal_pos.translation.x - translation.x;
// double y_dist = msg->goal_pos.translation.y - translation.y;
double total_dist = sqrt(pow(translation_to_goal[0], 2) + pow(translation_to_goal[1], 2));
// TODO: Handle case when y_dist == total_dist
double theta = 2 * acos(translation_to_goal[0] / total_dist);
double R = translation_to_goal[0] / sin(theta);
printf("plan: R = %f, theta = %f\n", R, theta);
if (translation_to_goal[1] < 0) {
R = -R;
theta = -theta;
}
double path_center[2];
path_center[0] = translation.x;
path_center[1] = translation.y + R;
printf("path center = %f, %f\n", path_center[0], path_center[1]);
double step_size_m = 0.5;
double step_width_m = 0.30;
double step_dt_s = 1;
double arc_dist_to_goal_m = theta * R;
int num_steps = floor(arc_dist_to_goal_m / step_size_m);
double step_arc_size_rad = theta / num_steps;
drc::ee_goal_sequence_t right_foot_goals;
right_foot_goals.utime = msg->utime;
right_foot_goals.robot_name = msg->robot_name;
right_foot_goals.num_goals = num_steps;
drc::ee_goal_sequence_t left_foot_goals;
left_foot_goals.utime = msg->utime;
left_foot_goals.robot_name = msg->robot_name;
left_foot_goals.num_goals = num_steps;
for (int i=0; i < num_steps; i++) {
double right_foot_angle = step_arc_size_rad * (i + 0.5);
double left_foot_angle = step_arc_size_rad * (i + 1);
double left_foot_radius;
double right_foot_radius;
if (R > 0) {
right_foot_radius = R - step_width_m / 2;
left_foot_radius = R + step_width_m / 2;
} else {
right_foot_radius = R + step_width_m / 2;
left_foot_radius = R - step_width_m / 2;
}
drc::ee_goal_t ee_goal;
ee_goal.utime = msg->utime + i * step_dt_s;
ee_goal.robot_name = msg->robot_name;
ee_goal.ee_name = "RbackWheel";
ee_goal.num_chain_joints = 0;
drc::position_3d_t step_pos;
step_pos.rotation = rotation;
step_pos.translation.x = translation.x + right_foot_radius * sin(right_foot_angle);
step_pos.translation.y = translation.y + right_foot_radius * (1 - cos(right_foot_angle));
step_pos.translation.z = 0;
ee_goal.ee_goal_pos = step_pos;
right_foot_goals.goals.push_back(ee_goal);
step_pos.rotation = rotation;
step_pos.translation.x = translation.x + left_foot_radius * sin(left_foot_angle);
step_pos.translation.y = translation.y + left_foot_radius * (1 - cos(left_foot_angle));
step_pos.translation.z = 0;
ee_goal.ee_goal_pos = step_pos;
ee_goal.ee_name = "LbackWheel";
left_foot_goals.goals.push_back(ee_goal);
}
lcm.publish("RIGHT_FOOT_STEPS", &right_foot_goals);
lcm.publish("LEFT_FOOT_STEPS", &left_foot_goals);
};
};
int main(int argc, char **argv)
{
lcm::LCM lcm;
if (!lcm.good())
return 1;
Handler handlerObject;
handlerObject.lcm = lcm;
lcm.subscribe("EST_ROBOT_STATE", &Handler::handleStateMessage, &handlerObject);
lcm.subscribe("NAV_GOAL_TIMED", &Handler::handleGoalMessage, &handlerObject);
while (0 == lcm.handle());
return 0;
}
<commit_msg>Fixed foot width bug<commit_after>#include <stdio.h>
#include <math.h>
#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/drc_lcmtypes.hpp"
inline void
bot_quat_mult (double c[4], const double a[4], const double b[4])
{
c[0] = a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3];
c[1] = a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2];
c[2] = a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1];
c[3] = a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0];
}
void
bot_quat_rotate_rev (const double rot[4], double v[3])
{
double a[4], b[4], c[4];
b[0] = 0;
memcpy (b+1, v, 3 * sizeof (double));
bot_quat_mult (a, b, rot);
b[0] = rot[0];
b[1] = -rot[1];
b[2] = -rot[2];
b[3] = -rot[3];
bot_quat_mult (c, b, a);
memcpy (v, c+1, 3 * sizeof (double));
}
static inline int
feq (double a, double b) {
return fabs (a - b) < 1e-9;
}
void
bot_quat_to_angle_axis (const double q[4], double *theta, double axis[3])
{
double halftheta = acos (q[0]);
*theta = halftheta * 2;
double sinhalftheta = sin (halftheta);
if (feq (halftheta, 0)) {
axis[0] = 0;
axis[1] = 0;
axis[2] = 1;
*theta = 0;
} else {
axis[0] = q[1] / sinhalftheta;
axis[1] = q[2] / sinhalftheta;
axis[2] = q[3] / sinhalftheta;
}
}
class Handler
{
drc::vector_3d_t translation;
drc::quaternion_t rotation;
public:
lcm::LCM lcm;
~Handler() {}
void handleStateMessage(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::robot_state_t* msg) {
// printf("received message on channel \"%s\":\n", channel.c_str());
// printf("timestamp = %11d\n", (long long)msg->utime);
translation = msg->origin_position.translation;
rotation = msg->origin_position.rotation;
};
void handleGoalMessage(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::nav_goal_timed_t* msg) {
printf("start = %f, %f, %f\n", translation.x, translation.y, translation.z);
printf("goal = %f, %f, %f\n", msg->goal_pos.translation.x, msg->goal_pos.translation.y, msg->goal_pos.translation.z);
double translation_to_goal[3] = {msg->goal_pos.translation.x - translation.x, msg->goal_pos.translation.y - translation.y, msg->goal_pos.translation.z - translation.z};
// translation_to_goal[0] = msg->goal_pos.translation.x - translation.x;
// translation_to_goal[1] = msg->goal_pos.translation.y - translation.y;
// translation_to_goal[2] = msg->goal_pos.translation.z - translation.z};
// printf("x vec: %f - %f = %f, %f\n", msg->goal_pos.translation.x, translation.x,msg->goal_pos.translation.x - translation.x, translation_to_goal[0]);
printf("vec to goal: %f, %f, %f\n", translation_to_goal[0], translation_to_goal[1], translation_to_goal[2]);
// double robot_rotation[4] = {rotation.x, rotation.y, rotation.z, rotation.w};
// printf("quaternion: %f, %f, %f, %f\n", rotation.x, rotation.y, rotation.z, rotation.w);
// double rot_axis[3];
// double rot_theta;
// bot_quat_to_angle_axis(robot_rotation, &rot_theta, rot_axis);
// printf("axis: %f, %f, %f\n", rot_axis[0], rot_axis[1], rot_axis[2]);
// printf("angle: %f\n", rot_theta);
// bot_quat_rotate_rev(robot_rotation, translation_to_goal);
printf("vec to goal in robot frame: %f, %f, %f\n", translation_to_goal[0], translation_to_goal[1], translation_to_goal[2]);
// double x_dist = msg->goal_pos.translation.x - translation.x;
// double y_dist = msg->goal_pos.translation.y - translation.y;
double total_dist = sqrt(pow(translation_to_goal[0], 2) + pow(translation_to_goal[1], 2));
// TODO: Handle case when y_dist == total_dist
double theta = 2 * acos(translation_to_goal[0] / total_dist);
double R = translation_to_goal[0] / sin(theta);
printf("plan: R = %f, theta = %f\n", R, theta);
if (translation_to_goal[1] < 0) {
R = -R;
theta = -theta;
}
double path_center[2];
path_center[0] = translation.x;
path_center[1] = translation.y + R;
printf("path center = %f, %f\n", path_center[0], path_center[1]);
double step_size_m = 0.5;
double step_width_m = 0.30;
double step_dt_s = 1;
double arc_dist_to_goal_m = theta * R;
int num_steps = floor(arc_dist_to_goal_m / step_size_m);
double step_arc_size_rad = theta / num_steps;
drc::ee_goal_sequence_t right_foot_goals;
right_foot_goals.utime = msg->utime;
right_foot_goals.robot_name = msg->robot_name;
right_foot_goals.num_goals = num_steps;
drc::ee_goal_sequence_t left_foot_goals;
left_foot_goals.utime = msg->utime;
left_foot_goals.robot_name = msg->robot_name;
left_foot_goals.num_goals = num_steps;
double left_foot_radius;
double right_foot_radius;
if (R > 0) {
right_foot_radius = R - step_width_m / 2;
left_foot_radius = R + step_width_m / 2;
} else {
right_foot_radius = R + step_width_m / 2;
left_foot_radius = R - step_width_m / 2;
}
printf("right foot rad = %f, left foot rad = %f\n", right_foot_radius, left_foot_radius);
for (int i=0; i < num_steps; i++) {
double right_foot_angle = step_arc_size_rad * (i + 0.5);
double left_foot_angle = step_arc_size_rad * (i + 1);
drc::ee_goal_t ee_goal;
ee_goal.utime = msg->utime + i * step_dt_s;
ee_goal.robot_name = msg->robot_name;
ee_goal.ee_name = "RbackWheel";
ee_goal.num_chain_joints = 0;
drc::position_3d_t step_pos;
step_pos.rotation = rotation;
step_pos.translation.x = translation.x + right_foot_radius * sin(right_foot_angle);
// printf("right trans x = %f\n", step_pos.translation.x);
step_pos.translation.y = translation.y + R - right_foot_radius * cos(right_foot_angle);
step_pos.translation.z = 0;
ee_goal.ee_goal_pos = step_pos;
right_foot_goals.goals.push_back(ee_goal);
step_pos.rotation = rotation;
step_pos.translation.x = translation.x + left_foot_radius * sin(left_foot_angle);
// printf("left trans x = %f\n", step_pos.translation.x);
step_pos.translation.y = translation.y + R - left_foot_radius * cos(left_foot_angle);
step_pos.translation.z = 0;
ee_goal.ee_goal_pos = step_pos;
ee_goal.ee_name = "LbackWheel";
left_foot_goals.goals.push_back(ee_goal);
}
lcm.publish("RIGHT_FOOT_STEPS", &right_foot_goals);
lcm.publish("LEFT_FOOT_STEPS", &left_foot_goals);
};
};
int main(int argc, char **argv)
{
lcm::LCM lcm;
if (!lcm.good())
return 1;
Handler handlerObject;
handlerObject.lcm = lcm;
lcm.subscribe("EST_ROBOT_STATE", &Handler::handleStateMessage, &handlerObject);
lcm.subscribe("NAV_GOAL_TIMED", &Handler::handleGoalMessage, &handlerObject);
while (0 == lcm.handle());
return 0;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Core/Algorithms/Base/Option.h>
#include <Core/Datatypes/DatatypeFwd.h>
#include <Core/Datatypes/Legacy/Field/CastFData.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/GeometryPrimitives/Tensor.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/GeometryPrimitives/Vector.h>
#include <Core/Datatypes/Dyadic3DTensor.h>
#include <Core/Algorithms/Base/AlgorithmData.h>
#include <Core/Algorithms/Math/ComputeTensorUncertaintyAlgorithm.h>
#include <boost/smart_ptr/make_shared_object.hpp>
#include "Core/Datatypes/MatrixFwd.h"
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Math;
const auto DIM = 3;
const auto epsilon = 1.0e-12;
const std::set<std::string> options = {"Linear Invariant","Log-Euclidean","Matrix Average"};
const auto MATRIX_AVERAGE = AlgoOption("Matrix Average", options);
const auto LOG_EUCLIDEAN = AlgoOption("Log-Euclidean", options);
const auto LINEAR_INVARIANT = AlgoOption("Linear Invariant", options);
// Used test from ReportFieldInfoTests as template for setting tensor data
TEST(ComputeTensorUncertaintTest, SetFieldData)
{
const double unitHalf = 0.5 * std::sqrt(2);
Tensor t1(5*Vector(1,0,0), 3*Vector(0,1,0), Vector(0,0,1));
Tensor t2(7*Vector(unitHalf,unitHalf,0), 2*Vector(unitHalf,-unitHalf,0), Vector(0,0,1));
Tensor t_expected(4.75, 1.25, 0, 3.75, 0, 1);
FieldInformation lfi("LatVolMesh", 1, "Tensor");
MeshHandle mesh1 = CreateMesh(lfi);
MeshHandle mesh2 = CreateMesh(lfi);
FieldHandle fh1 = CreateField(lfi, mesh1);
FieldHandle fh2 = CreateField(lfi, mesh2);
fh1->vfield()->set_all_values(t1);
fh2->vfield()->set_all_values(t2);
Tensor t;
fh1->vfield()->get_value(t, 0);
std::cout << "t1 from field: " << t << std::endl;
fh2->vfield()->get_value(t, 0);
std::cout << "t2 from field: " << t << std::endl;
FieldList fields = {fh1, fh2};
ComputeTensorUncertaintyAlgorithm algo;
boost::tuple<FieldHandle, MatrixHandle> output = algo.runImpl(fields, MATRIX_AVERAGE, MATRIX_AVERAGE);
output.get<0>()->vfield()->get_value(t,0);
std::cout << "t average: " << t << std::endl;
for (int i = 0; i < DIM; ++i)
for (int j = 0; j < DIM; ++j)
ASSERT_NEAR(t.val(i, j), t_expected.val(i, j), epsilon);
}
<commit_msg>Added tests for log euclidean and linear invariant<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Core/Algorithms/Base/Option.h>
#include <Core/Datatypes/DatatypeFwd.h>
#include <Core/Datatypes/Legacy/Field/CastFData.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/GeometryPrimitives/Tensor.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/GeometryPrimitives/Vector.h>
#include <Core/Datatypes/Dyadic3DTensor.h>
#include <Core/Algorithms/Base/AlgorithmData.h>
#include <Core/Algorithms/Math/ComputeTensorUncertaintyAlgorithm.h>
#include <boost/smart_ptr/make_shared_object.hpp>
#include "Core/Datatypes/MatrixFwd.h"
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Math;
const auto DIM = 3;
const std::set<std::string> options = {"Linear Invariant","Log-Euclidean","Matrix Average"};
const auto MATRIX_AVERAGE = AlgoOption("Matrix Average", options);
const auto LOG_EUCLIDEAN = AlgoOption("Log-Euclidean", options);
const auto LINEAR_INVARIANT = AlgoOption("Linear Invariant", options);
FieldHandle tensorToField(Tensor t)
{
FieldInformation lfi("LatVolMesh", 1, "Tensor");
MeshHandle mesh = CreateMesh(lfi);
FieldHandle fh = CreateField(lfi, mesh);
fh->vfield()->set_all_values(t);
return fh;
}
void assertTensorsNear(const Tensor& t, const Tensor& expected, double epsilon)
{
for (int i = 0; i < DIM; ++i)
for (int j = 0; j < DIM; ++j)
ASSERT_NEAR(t.val(i, j), expected.val(i, j), epsilon);
}
TEST(ComputeTensorUncertaintyTest, MatrixAverage)
{
const double unitHalf = 0.5 * std::sqrt(2);
auto fh1 = tensorToField(Tensor(5*Vector(1,0,0), 3*Vector(0,1,0), Vector(0,0,1)));
auto fh2 = tensorToField(Tensor(7*Vector(unitHalf,unitHalf,0), 2*Vector(unitHalf,-unitHalf,0), Vector(0,0,1)));
Tensor t_expected(4.75, 1.25, 0, 3.75, 0, 1);
const auto epsilon = 1.0e-12;
FieldList fields = {fh1, fh2};
ComputeTensorUncertaintyAlgorithm algo;
boost::tuple<FieldHandle, MatrixHandle> output = algo.runImpl(fields, MATRIX_AVERAGE, MATRIX_AVERAGE);
Tensor t;
output.get<0>()->vfield()->get_value(t,0);
assertTensorsNear(t, t_expected, epsilon);
}
// I hand calculated the Log-Euclidean calcuation except the last step of matrix exponential, hence the large epsilon
TEST(ComputeTensorUncertaintyTest, LogEuclidean)
{
const double unitHalf = 0.5 * std::sqrt(2);
auto fh1 = tensorToField(Tensor(5*Vector(1,0,0), 3*Vector(0,1,0), Vector(0,0,1)));
auto fh2 = tensorToField(Tensor(7*Vector(unitHalf,unitHalf,0), 2*Vector(unitHalf,-unitHalf,0), Vector(0,0,1)));
Tensor t_expected(4.522, 1.215, 0, 3.531, 0, 1);
const auto epsilon = 0.001;
FieldList fields = {fh1, fh2};
ComputeTensorUncertaintyAlgorithm algo;
boost::tuple<FieldHandle, MatrixHandle> output = algo.runImpl(fields, LOG_EUCLIDEAN, LOG_EUCLIDEAN);
Tensor t;
output.get<0>()->vfield()->get_value(t,0);
assertTensorsNear(t, t_expected, epsilon);
}
// Since this only tests the invariant calculation, we only need to check the eigenvalues
TEST(ComputeTensorUncertaintyTest, LinearInvariant)
{
const double unitHalf = 0.5 * std::sqrt(2);
auto fh1 = tensorToField(Tensor(5*Vector(1,0,0), 3*Vector(0,1,0), Vector(0,0,1)));
auto fh2 = tensorToField(Tensor(7*Vector(unitHalf,unitHalf,0), 2*Vector(unitHalf,-unitHalf,0), Vector(0,0,1)));
std::vector<double> eigs_expected = {5.9075, 2.715, 0.877};
const auto epsilon = 0.003;
FieldList fields = {fh1, fh2};
ComputeTensorUncertaintyAlgorithm algo;
boost::tuple<FieldHandle, MatrixHandle> output = algo.runImpl(fields, LINEAR_INVARIANT, MATRIX_AVERAGE);
Tensor t;
output.get<0>()->vfield()->get_value(t,0);
std::vector<double> eigs(3);
t.get_eigenvalues(eigs[0], eigs[1], eigs[2]);
for (auto i = 0; i < DIM; ++i)
ASSERT_NEAR(eigs[i], eigs_expected[i], epsilon);
}
<|endoftext|> |
<commit_before>#include "DlgAddWatchEntry.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QVBoxLayout>
#include <sstream>
#include "../../DolphinProcess/DolphinAccessor.h"
#include "../GUICommon.h"
DlgAddWatchEntry::DlgAddWatchEntry(MemWatchEntry* entry) : m_entry(entry)
{
m_chkBoundToPointer = new QCheckBox("This is a pointer", this);
connect(m_chkBoundToPointer, static_cast<void (QCheckBox::*)(int)>(&QCheckBox::stateChanged),
this, &DlgAddWatchEntry::onIsPointerChanged);
QLabel* lblPreview = new QLabel("Value preview: ");
m_lblValuePreview = new QLabel("", this);
QHBoxLayout* preview_layout = new QHBoxLayout;
preview_layout->addWidget(lblPreview);
preview_layout->addWidget(m_lblValuePreview);
QWidget* preview_widget = new QWidget();
preview_widget->setLayout(preview_layout);
QLabel* lblAddress = new QLabel("Address: ", this);
m_txbAddress = new QLineEdit(this);
QHBoxLayout* layout_addressAndPreview = new QHBoxLayout;
layout_addressAndPreview->addWidget(lblAddress);
layout_addressAndPreview->addWidget(m_txbAddress);
QWidget* addressWidget = new QWidget(this);
addressWidget->setLayout(layout_addressAndPreview);
connect(m_txbAddress, static_cast<void (QLineEdit::*)(const QString&)>(&QLineEdit::textEdited),
this, &DlgAddWatchEntry::onAddressChanged);
m_offsetsLayout = new QFormLayout;
m_offsetsWidgets = QVector<QLineEdit*>();
QWidget* offsetsWidget = new QWidget();
offsetsWidget->setLayout(m_offsetsLayout);
QLabel* lblOffset = new QLabel("Offsets (in hex): ", this);
m_btnAddOffset = new QPushButton("Add offset");
m_btnRemoveOffset = new QPushButton("Remove offset");
QHBoxLayout* pointerButtons_layout = new QHBoxLayout;
pointerButtons_layout->addWidget(m_btnAddOffset);
pointerButtons_layout->addWidget(m_btnRemoveOffset);
QWidget* pointerButtons_widget = new QWidget();
pointerButtons_widget->setLayout(pointerButtons_layout);
connect(m_btnAddOffset, static_cast<void (QPushButton::*)(bool)>(&QPushButton::clicked), this,
&DlgAddWatchEntry::addPointerOffset);
connect(m_btnRemoveOffset, static_cast<void (QPushButton::*)(bool)>(&QPushButton::clicked), this,
&DlgAddWatchEntry::removePointerOffset);
QVBoxLayout* pointerOffset_layout = new QVBoxLayout;
pointerOffset_layout->addWidget(lblOffset);
pointerOffset_layout->addWidget(offsetsWidget);
pointerOffset_layout->addWidget(pointerButtons_widget);
m_pointerWidget = new QWidget(this);
m_pointerWidget->setLayout(pointerOffset_layout);
QLabel* lblLabel = new QLabel("Label: ", this);
m_txbLabel = new QLineEdit(this);
QHBoxLayout* layout_label = new QHBoxLayout;
layout_label->addWidget(lblLabel);
layout_label->addWidget(m_txbLabel);
QWidget* labelWidget = new QWidget(this);
labelWidget->setLayout(layout_label);
QLabel* lblType = new QLabel("Type: ", this);
m_cmbTypes = new QComboBox(this);
m_cmbTypes->addItems(GUICommon::g_memTypeNames);
connect(m_cmbTypes, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
&DlgAddWatchEntry::onTypeChange);
QHBoxLayout* layout_type = new QHBoxLayout;
layout_type->addWidget(lblType);
layout_type->addWidget(m_cmbTypes);
QWidget* typeWidget = new QWidget(this);
typeWidget->setLayout(layout_type);
QLabel* lblLength = new QLabel(QString("Length: "), this);
m_spnLength = new QSpinBox(this);
m_spnLength->setMinimum(1);
QHBoxLayout* layout_length = new QHBoxLayout;
layout_length->addWidget(lblLength);
layout_length->addWidget(m_spnLength);
m_lengtWidget = new QWidget;
m_lengtWidget->setLayout(layout_length);
connect(m_spnLength, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&DlgAddWatchEntry::onLengthChanged);
QDialogButtonBox* buttonBox =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
QVBoxLayout* main_layout = new QVBoxLayout;
main_layout->addWidget(preview_widget);
main_layout->addWidget(m_chkBoundToPointer);
main_layout->addWidget(addressWidget);
main_layout->addWidget(m_pointerWidget);
main_layout->addWidget(labelWidget);
main_layout->addWidget(typeWidget);
main_layout->addWidget(m_lengtWidget);
main_layout->addWidget(buttonBox);
setLayout(main_layout);
connect(buttonBox, &QDialogButtonBox::accepted, this, &DlgAddWatchEntry::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &DlgAddWatchEntry::reject);
if (entry == nullptr)
{
m_entry = new MemWatchEntry();
m_entry->setLength(1);
m_cmbTypes->setCurrentIndex(0);
m_spnLength->setValue(1);
m_lengtWidget->hide();
m_lblValuePreview->setText("???");
m_chkBoundToPointer->setChecked(false);
m_pointerWidget->hide();
addPointerOffset();
}
else
{
m_cmbTypes->setCurrentIndex(static_cast<int>(m_entry->getType()));
m_spnLength->setValue(static_cast<int>(m_entry->getLength()));
if (m_entry->getType() == Common::MemType::type_string ||
m_entry->getType() == Common::MemType::type_byteArray)
m_lengtWidget->show();
else
m_lengtWidget->hide();
m_txbLabel->setText(QString::fromStdString(m_entry->getLabel()));
std::stringstream ssAddress;
ssAddress << std::hex << std::uppercase << m_entry->getConsoleAddress();
m_txbAddress->setText(QString::fromStdString(ssAddress.str()));
m_chkBoundToPointer->setChecked(m_entry->isBoundToPointer());
if (entry->isBoundToPointer())
{
m_pointerWidget->show();
for (int i = 0; i < m_entry->getPointerLevel(); ++i)
{
std::stringstream ssOffset;
ssOffset << std::hex << std::uppercase << m_entry->getPointerOffset(i);
QLineEdit* lineEdit = new QLineEdit();
lineEdit->setText(QString::fromStdString(ssOffset.str()));
m_offsetsWidgets.append(lineEdit);
QLabel* label = new QLabel(QString::fromStdString("Level " + std::to_string(i + 1) + ":"));
m_offsetsLayout->addRow(label, lineEdit);
}
}
else
{
m_pointerWidget->hide();
addPointerOffset();
}
updateValuePreview();
}
}
void DlgAddWatchEntry::addPointerOffset()
{
QLineEdit* lineEdit = new QLineEdit();
lineEdit->setText(0);
m_offsetsWidgets.append(lineEdit);
int level = m_offsetsLayout->rowCount();
QLabel* label = new QLabel(QString::fromStdString("Level " + std::to_string(level + 1) + ":"));
m_offsetsLayout->addRow(label, lineEdit);
m_entry->addOffset(0);
connect(lineEdit, static_cast<void (QLineEdit::*)(const QString&)>(&QLineEdit::textEdited), this,
&DlgAddWatchEntry::onOffsetChanged);
if (m_offsetsLayout->rowCount() > 1)
m_btnRemoveOffset->setEnabled(true);
else
m_btnRemoveOffset->setDisabled(true);
}
void DlgAddWatchEntry::removePointerOffset()
{
m_offsetsLayout->removeRow(m_offsetsLayout->rowCount() - 1);
m_offsetsWidgets.removeLast();
m_entry->removeOffset();
updateValuePreview();
if (m_offsetsLayout->rowCount() == 1)
m_btnRemoveOffset->setDisabled(true);
}
void DlgAddWatchEntry::onOffsetChanged()
{
QLineEdit* theLineEdit = static_cast<QLineEdit*>(sender());
int index = 0;
QFormLayout::ItemRole itemRole;
m_offsetsLayout->getWidgetPosition(theLineEdit, &index, &itemRole);
if (validateAndSetOffset(index))
{
updateValuePreview();
}
}
void DlgAddWatchEntry::onTypeChange(int index)
{
Common::MemType theType = static_cast<Common::MemType>(index);
if (theType == Common::MemType::type_string || theType == Common::MemType::type_byteArray)
m_lengtWidget->show();
else
m_lengtWidget->hide();
m_entry->setType(theType);
if (validateAndSetAddress())
updateValuePreview();
}
void DlgAddWatchEntry::accept()
{
if (!validateAndSetAddress())
{
QString errorMsg = QString(
"The address you entered is invalid, make sure it is an "
"hexadecimal number between 0x80000000 and 0x817FFFFF");
if (DolphinComm::DolphinAccessor::isMem2Enabled())
{
errorMsg.append(" or between 0x90000000 and 0x93FFFFFF");
}
QMessageBox* errorBox = new QMessageBox(QMessageBox::Critical, QString("Invalid address"),
errorMsg, QMessageBox::Ok, this);
errorBox->exec();
}
else
{
if (m_chkBoundToPointer->isChecked())
{
bool allOffsetsValid = true;
int i = 0;
for (i; i < m_offsetsWidgets.count(); ++i)
{
allOffsetsValid = validateAndSetOffset(i);
if (!allOffsetsValid)
break;
}
if (!allOffsetsValid)
{
QMessageBox* errorBox = new QMessageBox(
QMessageBox::Critical, "Invalid offset",
QString::fromStdString("The offset you entered for the level " + std::to_string(i + 1) +
" is invalid, make sure it is an "
"hexadecimal number"),
QMessageBox::Ok, this);
errorBox->exec();
return;
}
}
if (m_txbLabel->text() == "")
m_entry->setLabel("No label");
else
m_entry->setLabel(m_txbLabel->text().toStdString());
setResult(QDialog::Accepted);
hide();
}
}
bool DlgAddWatchEntry::validateAndSetAddress()
{
std::string addressStr = m_txbAddress->text().toStdString();
std::stringstream ss(addressStr);
ss >> std::hex;
u32 address = 0;
ss >> address;
if (!ss.fail())
{
if (DolphinComm::DolphinAccessor::isValidConsoleAddress(address))
{
m_entry->setConsoleAddress(address);
return true;
}
}
return false;
}
bool DlgAddWatchEntry::validateAndSetOffset(int index)
{
std::string offsetStr = m_offsetsWidgets[index]->text().toStdString();
std::stringstream ss(offsetStr);
ss >> std::hex;
int offset = 0;
ss >> offset;
if (!ss.fail())
{
m_entry->setPointerOffset(offset, index);
return true;
}
return false;
}
void DlgAddWatchEntry::onAddressChanged()
{
if (validateAndSetAddress())
{
updateValuePreview();
}
else
{
m_lblValuePreview->setText("???");
}
}
void DlgAddWatchEntry::updateValuePreview()
{
m_entry->readMemoryFromRAM();
m_lblValuePreview->setText(QString::fromStdString(m_entry->getStringFromMemory()));
}
void DlgAddWatchEntry::onLengthChanged()
{
m_entry->setLength(m_spnLength->value());
if (validateAndSetAddress())
updateValuePreview();
}
void DlgAddWatchEntry::onIsPointerChanged()
{
if (m_chkBoundToPointer->isChecked())
m_pointerWidget->show();
else
m_pointerWidget->hide();
m_entry->setBoundToPointer(m_chkBoundToPointer->isChecked());
updateValuePreview();
}
MemWatchEntry* DlgAddWatchEntry::getEntry() const
{
return m_entry;
}<commit_msg>Initializes the base and the sign property when adding an entry<commit_after>#include "DlgAddWatchEntry.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QVBoxLayout>
#include <sstream>
#include "../../DolphinProcess/DolphinAccessor.h"
#include "../GUICommon.h"
DlgAddWatchEntry::DlgAddWatchEntry(MemWatchEntry* entry) : m_entry(entry)
{
m_chkBoundToPointer = new QCheckBox("This is a pointer", this);
connect(m_chkBoundToPointer, static_cast<void (QCheckBox::*)(int)>(&QCheckBox::stateChanged),
this, &DlgAddWatchEntry::onIsPointerChanged);
QLabel* lblPreview = new QLabel("Value preview: ");
m_lblValuePreview = new QLabel("", this);
QHBoxLayout* preview_layout = new QHBoxLayout;
preview_layout->addWidget(lblPreview);
preview_layout->addWidget(m_lblValuePreview);
QWidget* preview_widget = new QWidget();
preview_widget->setLayout(preview_layout);
QLabel* lblAddress = new QLabel("Address: ", this);
m_txbAddress = new QLineEdit(this);
QHBoxLayout* layout_addressAndPreview = new QHBoxLayout;
layout_addressAndPreview->addWidget(lblAddress);
layout_addressAndPreview->addWidget(m_txbAddress);
QWidget* addressWidget = new QWidget(this);
addressWidget->setLayout(layout_addressAndPreview);
connect(m_txbAddress, static_cast<void (QLineEdit::*)(const QString&)>(&QLineEdit::textEdited),
this, &DlgAddWatchEntry::onAddressChanged);
m_offsetsLayout = new QFormLayout;
m_offsetsWidgets = QVector<QLineEdit*>();
QWidget* offsetsWidget = new QWidget();
offsetsWidget->setLayout(m_offsetsLayout);
QLabel* lblOffset = new QLabel("Offsets (in hex): ", this);
m_btnAddOffset = new QPushButton("Add offset");
m_btnRemoveOffset = new QPushButton("Remove offset");
QHBoxLayout* pointerButtons_layout = new QHBoxLayout;
pointerButtons_layout->addWidget(m_btnAddOffset);
pointerButtons_layout->addWidget(m_btnRemoveOffset);
QWidget* pointerButtons_widget = new QWidget();
pointerButtons_widget->setLayout(pointerButtons_layout);
connect(m_btnAddOffset, static_cast<void (QPushButton::*)(bool)>(&QPushButton::clicked), this,
&DlgAddWatchEntry::addPointerOffset);
connect(m_btnRemoveOffset, static_cast<void (QPushButton::*)(bool)>(&QPushButton::clicked), this,
&DlgAddWatchEntry::removePointerOffset);
QVBoxLayout* pointerOffset_layout = new QVBoxLayout;
pointerOffset_layout->addWidget(lblOffset);
pointerOffset_layout->addWidget(offsetsWidget);
pointerOffset_layout->addWidget(pointerButtons_widget);
m_pointerWidget = new QWidget(this);
m_pointerWidget->setLayout(pointerOffset_layout);
QLabel* lblLabel = new QLabel("Label: ", this);
m_txbLabel = new QLineEdit(this);
QHBoxLayout* layout_label = new QHBoxLayout;
layout_label->addWidget(lblLabel);
layout_label->addWidget(m_txbLabel);
QWidget* labelWidget = new QWidget(this);
labelWidget->setLayout(layout_label);
QLabel* lblType = new QLabel("Type: ", this);
m_cmbTypes = new QComboBox(this);
m_cmbTypes->addItems(GUICommon::g_memTypeNames);
connect(m_cmbTypes, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
&DlgAddWatchEntry::onTypeChange);
QHBoxLayout* layout_type = new QHBoxLayout;
layout_type->addWidget(lblType);
layout_type->addWidget(m_cmbTypes);
QWidget* typeWidget = new QWidget(this);
typeWidget->setLayout(layout_type);
QLabel* lblLength = new QLabel(QString("Length: "), this);
m_spnLength = new QSpinBox(this);
m_spnLength->setMinimum(1);
QHBoxLayout* layout_length = new QHBoxLayout;
layout_length->addWidget(lblLength);
layout_length->addWidget(m_spnLength);
m_lengtWidget = new QWidget;
m_lengtWidget->setLayout(layout_length);
connect(m_spnLength, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&DlgAddWatchEntry::onLengthChanged);
QDialogButtonBox* buttonBox =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
QVBoxLayout* main_layout = new QVBoxLayout;
main_layout->addWidget(preview_widget);
main_layout->addWidget(m_chkBoundToPointer);
main_layout->addWidget(addressWidget);
main_layout->addWidget(m_pointerWidget);
main_layout->addWidget(labelWidget);
main_layout->addWidget(typeWidget);
main_layout->addWidget(m_lengtWidget);
main_layout->addWidget(buttonBox);
setLayout(main_layout);
connect(buttonBox, &QDialogButtonBox::accepted, this, &DlgAddWatchEntry::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &DlgAddWatchEntry::reject);
if (entry == nullptr)
{
m_entry = new MemWatchEntry();
m_entry->setLength(1);
m_cmbTypes->setCurrentIndex(0);
m_spnLength->setValue(1);
m_lengtWidget->hide();
m_lblValuePreview->setText("???");
m_chkBoundToPointer->setChecked(false);
m_pointerWidget->hide();
addPointerOffset();
}
else
{
m_cmbTypes->setCurrentIndex(static_cast<int>(m_entry->getType()));
m_spnLength->setValue(static_cast<int>(m_entry->getLength()));
if (m_entry->getType() == Common::MemType::type_string ||
m_entry->getType() == Common::MemType::type_byteArray)
m_lengtWidget->show();
else
m_lengtWidget->hide();
m_txbLabel->setText(QString::fromStdString(m_entry->getLabel()));
std::stringstream ssAddress;
ssAddress << std::hex << std::uppercase << m_entry->getConsoleAddress();
m_txbAddress->setText(QString::fromStdString(ssAddress.str()));
m_chkBoundToPointer->setChecked(m_entry->isBoundToPointer());
if (entry->isBoundToPointer())
{
m_pointerWidget->show();
for (int i = 0; i < m_entry->getPointerLevel(); ++i)
{
std::stringstream ssOffset;
ssOffset << std::hex << std::uppercase << m_entry->getPointerOffset(i);
QLineEdit* lineEdit = new QLineEdit();
lineEdit->setText(QString::fromStdString(ssOffset.str()));
m_offsetsWidgets.append(lineEdit);
QLabel* label = new QLabel(QString::fromStdString("Level " + std::to_string(i + 1) + ":"));
m_offsetsLayout->addRow(label, lineEdit);
}
}
else
{
m_pointerWidget->hide();
addPointerOffset();
}
updateValuePreview();
}
}
void DlgAddWatchEntry::addPointerOffset()
{
QLineEdit* lineEdit = new QLineEdit();
lineEdit->setText(0);
m_offsetsWidgets.append(lineEdit);
int level = m_offsetsLayout->rowCount();
QLabel* label = new QLabel(QString::fromStdString("Level " + std::to_string(level + 1) + ":"));
m_offsetsLayout->addRow(label, lineEdit);
m_entry->addOffset(0);
connect(lineEdit, static_cast<void (QLineEdit::*)(const QString&)>(&QLineEdit::textEdited), this,
&DlgAddWatchEntry::onOffsetChanged);
if (m_offsetsLayout->rowCount() > 1)
m_btnRemoveOffset->setEnabled(true);
else
m_btnRemoveOffset->setDisabled(true);
}
void DlgAddWatchEntry::removePointerOffset()
{
m_offsetsLayout->removeRow(m_offsetsLayout->rowCount() - 1);
m_offsetsWidgets.removeLast();
m_entry->removeOffset();
updateValuePreview();
if (m_offsetsLayout->rowCount() == 1)
m_btnRemoveOffset->setDisabled(true);
}
void DlgAddWatchEntry::onOffsetChanged()
{
QLineEdit* theLineEdit = static_cast<QLineEdit*>(sender());
int index = 0;
QFormLayout::ItemRole itemRole;
m_offsetsLayout->getWidgetPosition(theLineEdit, &index, &itemRole);
if (validateAndSetOffset(index))
{
updateValuePreview();
}
}
void DlgAddWatchEntry::onTypeChange(int index)
{
Common::MemType theType = static_cast<Common::MemType>(index);
if (theType == Common::MemType::type_string || theType == Common::MemType::type_byteArray)
m_lengtWidget->show();
else
m_lengtWidget->hide();
m_entry->setType(theType);
if (validateAndSetAddress())
updateValuePreview();
}
void DlgAddWatchEntry::accept()
{
if (!validateAndSetAddress())
{
QString errorMsg = QString(
"The address you entered is invalid, make sure it is an "
"hexadecimal number between 0x80000000 and 0x817FFFFF");
if (DolphinComm::DolphinAccessor::isMem2Enabled())
{
errorMsg.append(" or between 0x90000000 and 0x93FFFFFF");
}
QMessageBox* errorBox = new QMessageBox(QMessageBox::Critical, QString("Invalid address"),
errorMsg, QMessageBox::Ok, this);
errorBox->exec();
}
else
{
if (m_chkBoundToPointer->isChecked())
{
bool allOffsetsValid = true;
int i = 0;
for (i; i < m_offsetsWidgets.count(); ++i)
{
allOffsetsValid = validateAndSetOffset(i);
if (!allOffsetsValid)
break;
}
if (!allOffsetsValid)
{
QMessageBox* errorBox = new QMessageBox(
QMessageBox::Critical, "Invalid offset",
QString::fromStdString("The offset you entered for the level " + std::to_string(i + 1) +
" is invalid, make sure it is an "
"hexadecimal number"),
QMessageBox::Ok, this);
errorBox->exec();
return;
}
}
if (m_txbLabel->text() == "")
m_entry->setLabel("No label");
else
m_entry->setLabel(m_txbLabel->text().toStdString());
m_entry->setBase(Common::MemBase::base_decimal);
m_entry->setSignedUnsigned(false);
setResult(QDialog::Accepted);
hide();
}
}
bool DlgAddWatchEntry::validateAndSetAddress()
{
std::string addressStr = m_txbAddress->text().toStdString();
std::stringstream ss(addressStr);
ss >> std::hex;
u32 address = 0;
ss >> address;
if (!ss.fail())
{
if (DolphinComm::DolphinAccessor::isValidConsoleAddress(address))
{
m_entry->setConsoleAddress(address);
return true;
}
}
return false;
}
bool DlgAddWatchEntry::validateAndSetOffset(int index)
{
std::string offsetStr = m_offsetsWidgets[index]->text().toStdString();
std::stringstream ss(offsetStr);
ss >> std::hex;
int offset = 0;
ss >> offset;
if (!ss.fail())
{
m_entry->setPointerOffset(offset, index);
return true;
}
return false;
}
void DlgAddWatchEntry::onAddressChanged()
{
if (validateAndSetAddress())
{
updateValuePreview();
}
else
{
m_lblValuePreview->setText("???");
}
}
void DlgAddWatchEntry::updateValuePreview()
{
m_entry->readMemoryFromRAM();
m_lblValuePreview->setText(QString::fromStdString(m_entry->getStringFromMemory()));
}
void DlgAddWatchEntry::onLengthChanged()
{
m_entry->setLength(m_spnLength->value());
if (validateAndSetAddress())
updateValuePreview();
}
void DlgAddWatchEntry::onIsPointerChanged()
{
if (m_chkBoundToPointer->isChecked())
m_pointerWidget->show();
else
m_pointerWidget->hide();
m_entry->setBoundToPointer(m_chkBoundToPointer->isChecked());
updateValuePreview();
}
MemWatchEntry* DlgAddWatchEntry::getEntry() const
{
return m_entry;
}<|endoftext|> |
<commit_before>/*===================================================================
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 "mitkFileReaderWriterBase.h"
#include "mitkCoreServices.h"
#include "mitkIMimeTypeProvider.h"
#include "mitkIOMimeTypes.h"
#include "mitkLogMacros.h"
#include <usGetModuleContext.h>
#include <usLDAPProp.h>
namespace mitk
{
FileReaderWriterBase::FileReaderWriterBase() : m_Ranking(0), m_MimeTypePrefix(IOMimeTypes::DEFAULT_BASE_NAME() + ".")
{
}
FileReaderWriterBase::~FileReaderWriterBase() { this->UnregisterMimeType(); }
FileReaderWriterBase::FileReaderWriterBase(const FileReaderWriterBase &other)
: m_Description(other.m_Description),
m_Ranking(other.m_Ranking),
m_MimeTypePrefix(other.m_MimeTypePrefix),
m_Options(other.m_Options),
m_DefaultOptions(other.m_DefaultOptions),
m_CustomMimeType(other.m_CustomMimeType->Clone())
{
}
FileReaderWriterBase::Options FileReaderWriterBase::GetOptions() const
{
Options options = m_Options;
options.insert(m_DefaultOptions.begin(), m_DefaultOptions.end());
return options;
}
us::Any FileReaderWriterBase::GetOption(const std::string &name) const
{
auto iter = m_Options.find(name);
if (iter != m_Options.end())
{
return iter->second;
}
iter = m_DefaultOptions.find(name);
if (iter != m_DefaultOptions.end())
{
return iter->second;
}
return us::Any();
}
void FileReaderWriterBase::SetOptions(const FileReaderWriterBase::Options &options)
{
for (const auto &option : options)
{
this->SetOption(option.first, option.second);
}
}
void FileReaderWriterBase::SetOption(const std::string &name, const us::Any &value)
{
if (m_DefaultOptions.find(name) == m_DefaultOptions.end())
{
MITK_WARN << "Ignoring unknown IFileReader option '" << name << "'";
}
else
{
if (value.Empty())
{
// an empty Any signals 'reset to default value'
m_Options.erase(name);
}
else
{
m_Options[name] = value;
}
}
}
void FileReaderWriterBase::SetDefaultOptions(const FileReaderWriterBase::Options &defaultOptions)
{
m_DefaultOptions = defaultOptions;
}
FileReaderWriterBase::Options FileReaderWriterBase::GetDefaultOptions() const { return m_DefaultOptions; }
void FileReaderWriterBase::SetRanking(int ranking) { m_Ranking = ranking; }
int FileReaderWriterBase::GetRanking() const { return m_Ranking; }
void FileReaderWriterBase::SetMimeType(const CustomMimeType &mimeType) { m_CustomMimeType.reset(mimeType.Clone()); }
const CustomMimeType *FileReaderWriterBase::GetMimeType() const { return m_CustomMimeType.get(); }
CustomMimeType *FileReaderWriterBase::GetMimeType() { return m_CustomMimeType.get(); }
MimeType FileReaderWriterBase::GetRegisteredMimeType() const
{
MimeType result;
if (!m_MimeTypeReg)
{
if (!m_CustomMimeType->GetName().empty())
{
CoreServicePointer<IMimeTypeProvider> mimeTypeProvider(
CoreServices::GetMimeTypeProvider(us::GetModuleContext()));
return mimeTypeProvider->GetMimeTypeForName(m_CustomMimeType->GetName());
}
return result;
}
us::ServiceReferenceU reference = m_MimeTypeReg.GetReference();
try
{
int rank = 0;
us::Any rankProp = reference.GetProperty(us::ServiceConstants::SERVICE_RANKING());
if (!rankProp.Empty())
{
rank = us::any_cast<int>(rankProp);
}
auto id = us::any_cast<long>(reference.GetProperty(us::ServiceConstants::SERVICE_ID()));
result = MimeType(*m_CustomMimeType, rank, id);
}
catch (const us::BadAnyCastException &e)
{
MITK_WARN << "Unexpected exception: " << e.what();
}
return result;
}
void FileReaderWriterBase::SetMimeTypePrefix(const std::string &prefix) { m_MimeTypePrefix = prefix; }
std::string FileReaderWriterBase::GetMimeTypePrefix() const { return m_MimeTypePrefix; }
void FileReaderWriterBase::SetDescription(const std::string &description) { m_Description = description; }
std::string FileReaderWriterBase::GetDescription() const { return m_Description; }
void FileReaderWriterBase::AddProgressCallback(const FileReaderWriterBase::ProgressCallback &callback)
{
m_ProgressMessage += callback;
}
void FileReaderWriterBase::RemoveProgressCallback(const FileReaderWriterBase::ProgressCallback &callback)
{
m_ProgressMessage -= callback;
}
us::ServiceRegistration<CustomMimeType> FileReaderWriterBase::RegisterMimeType(us::ModuleContext *context)
{
if (context == nullptr)
throw std::invalid_argument("The context argument must not be nullptr.");
CoreServicePointer<IMimeTypeProvider> mimeTypeProvider(CoreServices::GetMimeTypeProvider(context));
const std::vector<std::string> extensions = m_CustomMimeType->GetExtensions();
// If the mime type name is set and the list of extensions is empty,
// look up the mime type in the registry and print a warning if
// there is none
if (!m_CustomMimeType->GetName().empty() && extensions.empty())
{
if (!mimeTypeProvider->GetMimeTypeForName(m_CustomMimeType->GetName()).IsValid())
{
MITK_WARN << "Registering a MITK reader or writer with an unknown MIME type " << m_CustomMimeType->GetName();
}
return m_MimeTypeReg;
}
// If the mime type name and extensions list is empty, print a warning
if (m_CustomMimeType->GetName().empty() && extensions.empty())
{
MITK_WARN << "Trying to register a MITK reader or writer with an empty mime type name and empty extension list.";
return m_MimeTypeReg;
}
// extensions is not empty
if (m_CustomMimeType->GetName().empty())
{
// Create a synthetic mime type name from the
// first extension in the list
m_CustomMimeType->SetName(m_MimeTypePrefix + extensions.front());
}
// Register a new mime type
// us::ServiceProperties props;
// props["name"] = m_CustomMimeType.GetName();
// props["extensions"] = m_CustomMimeType.GetExtensions();
m_MimeTypeReg = context->RegisterService<CustomMimeType>(m_CustomMimeType.get());
return m_MimeTypeReg;
}
void FileReaderWriterBase::UnregisterMimeType()
{
if (m_MimeTypeReg)
{
try
{
m_MimeTypeReg.Unregister();
}
catch (const std::logic_error &)
{
// service already unregistered
}
}
}
}
<commit_msg>Add possibility to fix up mime type names<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 "mitkFileReaderWriterBase.h"
#include "mitkCoreServices.h"
#include "mitkIMimeTypeProvider.h"
#include "mitkIOMimeTypes.h"
#include "mitkLogMacros.h"
#include <usGetModuleContext.h>
#include <usLDAPProp.h>
namespace mitk
{
FileReaderWriterBase::FileReaderWriterBase() : m_Ranking(0), m_MimeTypePrefix(IOMimeTypes::DEFAULT_BASE_NAME() + ".")
{
}
FileReaderWriterBase::~FileReaderWriterBase() { this->UnregisterMimeType(); }
FileReaderWriterBase::FileReaderWriterBase(const FileReaderWriterBase &other)
: m_Description(other.m_Description),
m_Ranking(other.m_Ranking),
m_MimeTypePrefix(other.m_MimeTypePrefix),
m_Options(other.m_Options),
m_DefaultOptions(other.m_DefaultOptions),
m_CustomMimeType(other.m_CustomMimeType->Clone())
{
}
FileReaderWriterBase::Options FileReaderWriterBase::GetOptions() const
{
Options options = m_Options;
options.insert(m_DefaultOptions.begin(), m_DefaultOptions.end());
return options;
}
us::Any FileReaderWriterBase::GetOption(const std::string &name) const
{
auto iter = m_Options.find(name);
if (iter != m_Options.end())
{
return iter->second;
}
iter = m_DefaultOptions.find(name);
if (iter != m_DefaultOptions.end())
{
return iter->second;
}
return us::Any();
}
void FileReaderWriterBase::SetOptions(const FileReaderWriterBase::Options &options)
{
for (const auto &option : options)
{
this->SetOption(option.first, option.second);
}
}
void FileReaderWriterBase::SetOption(const std::string &name, const us::Any &value)
{
if (m_DefaultOptions.find(name) == m_DefaultOptions.end())
{
MITK_WARN << "Ignoring unknown IFileReader option '" << name << "'";
}
else
{
if (value.Empty())
{
// an empty Any signals 'reset to default value'
m_Options.erase(name);
}
else
{
m_Options[name] = value;
}
}
}
void FileReaderWriterBase::SetDefaultOptions(const FileReaderWriterBase::Options &defaultOptions)
{
m_DefaultOptions = defaultOptions;
}
FileReaderWriterBase::Options FileReaderWriterBase::GetDefaultOptions() const { return m_DefaultOptions; }
void FileReaderWriterBase::SetRanking(int ranking) { m_Ranking = ranking; }
int FileReaderWriterBase::GetRanking() const { return m_Ranking; }
void FileReaderWriterBase::SetMimeType(const CustomMimeType &mimeType) { m_CustomMimeType.reset(mimeType.Clone()); }
const CustomMimeType *FileReaderWriterBase::GetMimeType() const { return m_CustomMimeType.get(); }
CustomMimeType *FileReaderWriterBase::GetMimeType() { return m_CustomMimeType.get(); }
MimeType FileReaderWriterBase::GetRegisteredMimeType() const
{
MimeType result;
if (!m_MimeTypeReg)
{
if (!m_CustomMimeType->GetName().empty())
{
CoreServicePointer<IMimeTypeProvider> mimeTypeProvider(
CoreServices::GetMimeTypeProvider(us::GetModuleContext()));
return mimeTypeProvider->GetMimeTypeForName(m_CustomMimeType->GetName());
}
return result;
}
us::ServiceReferenceU reference = m_MimeTypeReg.GetReference();
try
{
int rank = 0;
us::Any rankProp = reference.GetProperty(us::ServiceConstants::SERVICE_RANKING());
if (!rankProp.Empty())
{
rank = us::any_cast<int>(rankProp);
}
auto id = us::any_cast<long>(reference.GetProperty(us::ServiceConstants::SERVICE_ID()));
result = MimeType(*m_CustomMimeType, rank, id);
}
catch (const us::BadAnyCastException &e)
{
MITK_WARN << "Unexpected exception: " << e.what();
}
return result;
}
void FileReaderWriterBase::SetMimeTypePrefix(const std::string &prefix) { m_MimeTypePrefix = prefix; }
std::string FileReaderWriterBase::GetMimeTypePrefix() const { return m_MimeTypePrefix; }
void FileReaderWriterBase::SetDescription(const std::string &description) { m_Description = description; }
std::string FileReaderWriterBase::GetDescription() const { return m_Description; }
void FileReaderWriterBase::AddProgressCallback(const FileReaderWriterBase::ProgressCallback &callback)
{
m_ProgressMessage += callback;
}
void FileReaderWriterBase::RemoveProgressCallback(const FileReaderWriterBase::ProgressCallback &callback)
{
m_ProgressMessage -= callback;
}
us::ServiceRegistration<CustomMimeType> FileReaderWriterBase::RegisterMimeType(us::ModuleContext *context)
{
if (context == nullptr)
throw std::invalid_argument("The context argument must not be nullptr.");
CoreServicePointer<IMimeTypeProvider> mimeTypeProvider(CoreServices::GetMimeTypeProvider(context));
const std::vector<std::string> extensions = m_CustomMimeType->GetExtensions();
// If the mime type name is set and the list of extensions is empty,
// look up the mime type in the registry and print a warning if
// there is none
/*if (!m_CustomMimeType->GetName().empty() && extensions.empty())
{
if (!mimeTypeProvider->GetMimeTypeForName(m_CustomMimeType->GetName()).IsValid())
{
MITK_WARN << "Registering a MITK reader or writer with an unknown MIME type " << m_CustomMimeType->GetName();
}
return m_MimeTypeReg;
}*/
// If the mime type name and extensions list is empty, print a warning
if (m_CustomMimeType->GetName().empty() && extensions.empty())
{
MITK_WARN << "Trying to register a MITK reader or writer with an empty mime type name and empty extension list.";
return m_MimeTypeReg;
}
// extensions is not empty
if (m_CustomMimeType->GetName().empty())
{
// Create a synthetic mime type name from the
// first extension in the list
m_CustomMimeType->SetName(m_MimeTypePrefix + extensions.front());
}
// Register a new mime type
// us::ServiceProperties props;
// props["name"] = m_CustomMimeType.GetName();
// props["extensions"] = m_CustomMimeType.GetExtensions();
m_MimeTypeReg = context->RegisterService<CustomMimeType>(m_CustomMimeType.get());
return m_MimeTypeReg;
}
void FileReaderWriterBase::UnregisterMimeType()
{
if (m_MimeTypeReg)
{
try
{
m_MimeTypeReg.Unregister();
}
catch (const std::logic_error &)
{
// service already unregistered
}
}
}
}
<|endoftext|> |
<commit_before>/// HEADER
#include "import_ros.h"
/// COMPONENT
#include <csapex_ros/ros_handler.h>
#include <csapex_ros/ros_message_conversion.h>
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/factory/message_factory.h>
#include <csapex/utility/stream_interceptor.h>
#include <csapex/msg/message.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/param/set_parameter.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_ros/time_stamp_message.h>
#include <csapex/utility/timer.h>
#include <csapex/msg/any_message.h>
#include <csapex/utility/interlude.hpp>
/// SYSTEM
#include <yaml-cpp/eventhandler.h>
CSAPEX_REGISTER_CLASS(csapex::ImportRos, csapex::Node)
using namespace csapex;
const std::string ImportRos::no_topic_("-----");
namespace {
ros::Time rosTime(u_int64_t stamp_micro_seconds) {
ros::Time t;
t.fromNSec(stamp_micro_seconds * 1e3);
return t;
}
}
ImportRos::ImportRos()
: connector_(nullptr), retries_(0), buffer_size_(1024), running_(true)
{
}
void ImportRos::setup(NodeModifier& node_modifier)
{
input_time_ = node_modifier.addOptionalInput<connection_types::TimeStampMessage>("time");
connector_ = node_modifier.addOutput<connection_types::AnyMessage>("Something");
}
void ImportRos::setupParameters(Parameterizable& parameters)
{
std::vector<std::string> set;
set.push_back(no_topic_);
parameters.addParameter(csapex::param::ParameterFactory::declareParameterStringSet("topic", set),
std::bind(&ImportRos::update, this));
parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("refresh"),
std::bind(&ImportRos::refresh, this));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("rate", 0.1, 100.0, 60.0, 0.1),
std::bind(&ImportRos::updateRate, this));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("queue", 0, 30, 1, 1),
std::bind(&ImportRos::updateSubscriber, this));
parameters.addParameter(csapex::param::ParameterFactory::declareBool("latch", false));
std::function<bool()> connected_condition = [&]() { return msg::isConnected(input_time_); };
csapex::param::Parameter::Ptr buffer_p = csapex::param::ParameterFactory::declareRange("buffer/length", 0.0, 10.0, 1.0, 0.1);
parameters.addConditionalParameter(buffer_p, connected_condition);
csapex::param::Parameter::Ptr max_wait_p = csapex::param::ParameterFactory::declareRange("buffer/max_wait", 0.0, 10.0, 1.0, 0.1);
parameters.addConditionalParameter(max_wait_p, connected_condition);
}
void ImportRos::setupROS()
{
refresh();
}
void ImportRos::refresh()
{
ROSHandler& rh = getRosHandler();
if(rh.nh()) {
std::string old_topic = readParameter<std::string>("topic");
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
param::SetParameter::Ptr setp = std::dynamic_pointer_cast<param::SetParameter>(getParameter("topic"));
if(setp) {
node_modifier_->setNoError();
bool found = false;
std::vector<std::string> topics_str;
topics_str.push_back(no_topic_);
for(ros::master::V_TopicInfo::const_iterator it = topics.begin(); it != topics.end(); ++it) {
topics_str.push_back(it->name);
if(it->name == old_topic) {
found = true;
}
}
if(!found) {
topics_str.push_back(old_topic);
}
setp->setSet(topics_str);
if(old_topic != no_topic_) {
setp->set(old_topic);
}
return;
}
}
node_modifier_->setWarning("no ROS connection");
}
void ImportRos::update()
{
retries_ = 5;
if(modifier_->isProcessingEnabled()) {
waitForTopic();
}
}
void ImportRos::updateRate()
{
setTickFrequency(readParameter<double>("rate"));
}
void ImportRos::updateSubscriber()
{
if(!current_topic_.name.empty()) {
current_subscriber = RosMessageConversion::instance().subscribe(current_topic_, readParameter<int>("queue"), std::bind(&ImportRos::callback, this, std::placeholders::_1));
}
}
bool ImportRos::doSetTopic()
{
getRosHandler().refresh();
if(!getRosHandler().isConnected()) {
node_modifier_->setError("no connection to ROS");
return false;
}
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
std::string topic = readParameter<std::string>("topic");
if(topic == no_topic_) {
return true;
}
for(ros::master::V_TopicInfo::iterator it = topics.begin(); it != topics.end(); ++it) {
if(it->name == topic) {
setTopic(*it);
retries_ = 0;
return true;
}
}
std::stringstream ss;
ss << "cannot set topic, " << topic << " doesn't exist";
if(retries_ > 0) {
ss << ", " << retries_ << " retries left";
}
ss << ".";
node_modifier_->setWarning(ss.str());
return false;
}
void ImportRos::processROS()
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
INTERLUDE("process");
// first check if connected -> if not connected, we only use tick
if(!msg::isConnected(input_time_)) {
return;
}
// now that we are connected, check that we have a valid message
if(!msg::hasMessage(input_time_)) {
return;
}
// INPUT CONNECTED
connection_types::TimeStampMessage::ConstPtr time = msg::getMessage<connection_types::TimeStampMessage>(input_time_);
if(msgs_.empty()) {
return;
}
if(time->value == ros::Time(0)) {
node_modifier_->setWarning("incoming time is 0, using default behaviour");
publishLatestMessage();
return;
}
if(rosTime(msgs_.back()->stamp_micro_seconds) == ros::Time(0)) {
node_modifier_->setWarning("buffered time is 0, using default behaviour");
publishLatestMessage();
return;
}
// drop old messages
ros::Duration keep_duration(readParameter<double>("buffer/length"));
while(!msgs_.empty() && rosTime(msgs_.front()->stamp_micro_seconds) + keep_duration < time->value) {
msgs_.pop_front();
}
if(!msgs_.empty()) {
if(rosTime(msgs_.front()->stamp_micro_seconds) > time->value) {
// aerr << "time stamp " << time->value << " is too old, oldest buffered is " << rosTime(msgs_.front()->stamp_micro_seconds) << std::endl;
// return;
}
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.front()->stamp_micro_seconds) + max_wait_duration < time->value) {
// aerr << "[1] time stamp " << time->value << " is too new" << std::endl;
// return;
}
}
// wait until we have a message
if(!isStampCovered(time->value)) {
ros::Rate r(10);
while(!isStampCovered(time->value) && running_) {
r.sleep();
ros::spinOnce();
if(!msgs_.empty()) {
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp_micro_seconds) + max_wait_duration < time->value) {
aerr << "[2] time stamp " << time->value << " is too new, latest stamp is " << rosTime(msgs_.back()->stamp_micro_seconds) << std::endl;
return;
}
}
}
}
if(msgs_.empty()) {
node_modifier_->setWarning("No messages received");
return;
}
std::deque<connection_types::Message::ConstPtr>::iterator first_after = msgs_.begin();
while(rosTime((*first_after)->stamp_micro_seconds) < time->value) {
++first_after;
}
if(first_after == msgs_.begin()) {
msg::publish(connector_, *first_after);
return;
} else if(first_after == msgs_.end()) {
assert(false);
node_modifier_->setWarning("Should not happen.....");
return;
} else {
std::deque<connection_types::Message::ConstPtr>::iterator last_before = first_after - 1;
ros::Duration diff1 = rosTime((*first_after)->stamp_micro_seconds) - time->value;
ros::Duration diff2 = rosTime((*last_before)->stamp_micro_seconds) - time->value;
if(diff1 < diff2) {
msg::publish(connector_, *first_after);
} else {
msg::publish(connector_, *last_before);
}
}
}
bool ImportRos::isStampCovered(const ros::Time &stamp)
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
return rosTime(msgs_.back()->stamp_micro_seconds) >= stamp;
}
void ImportRos::waitForTopic()
{
INTERLUDE("wait");
ros::WallDuration poll_wait(0.5);
while(retries_ --> 0) {
bool topic_exists = doSetTopic();
if(topic_exists) {
return;
} else {
ROS_WARN_STREAM("waiting for topic " << readParameter<std::string>("topic"));
poll_wait.sleep();
}
}
}
bool ImportRos::canTick()
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
return !msg::isConnected(input_time_) && !msgs_.empty();
}
void ImportRos::tickROS()
{
INTERLUDE("tick");
if(retries_ > 0) {
waitForTopic();
}
if(msg::isConnected(input_time_)) {
return;
}
// NO INPUT CONNECTED -> ONLY KEEP CURRENT MESSAGE
{
INTERLUDE("pop");
while(msgs_.size() > 1) {
msgs_.pop_front();
}
}
if(!current_topic_.name.empty()) {
publishLatestMessage();
}
}
void ImportRos::publishLatestMessage()
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
INTERLUDE("publish");
if(msgs_.empty()) {
INTERLUDE("wait for message");
ros::WallRate r(10);
while(msgs_.empty() && running_) {
r.sleep();
ros::spinOnce();
}
if(!running_) {
return;
}
}
msg::publish(connector_, msgs_.back());
if(!readParameter<bool>("latch")) {
msgs_.clear();
}
}
// FIXME: this can be still called after the object is destroyed!
void ImportRos::callback(ConnectionTypeConstPtr message)
{
connection_types::Message::ConstPtr msg = std::dynamic_pointer_cast<connection_types::Message const>(message);
if(msg) {
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
if(!msgs_.empty() && msg->stamp_micro_seconds < msgs_.front()->stamp_micro_seconds) {
awarn << "detected time anomaly -> reset";
msgs_.clear();
}
if(!msg::isConnected(input_time_)) {
msgs_.clear();
}
msgs_.push_back(msg);
while((int) msgs_.size() > buffer_size_) {
msgs_.pop_front();
}
}
}
void ImportRos::setTopic(const ros::master::TopicInfo &topic)
{
if(topic.name == current_topic_.name) {
return;
}
current_subscriber.shutdown();
//if(RosMessageConversion::instance().isTopicTypeRegistered(topic)) {
node_modifier_->setNoError();
current_topic_ = topic;
updateSubscriber();
// } else {
// node_modifier_->setError(std::string("cannot import topic of type ") + topic.datatype);
// return;
// }
}
void ImportRos::setParameterState(Memento::Ptr memento)
{
Node::setParameterState(memento);
}
void ImportRos::abort()
{
running_ = false;
}
<commit_msg>buildfix<commit_after>/// HEADER
#include "import_ros.h"
/// COMPONENT
#include <csapex_ros/ros_handler.h>
#include <csapex_ros/ros_message_conversion.h>
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/factory/message_factory.h>
#include <csapex/utility/stream_interceptor.h>
#include <csapex/msg/message.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/param/set_parameter.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_ros/time_stamp_message.h>
#include <csapex/utility/timer.h>
#include <csapex/msg/any_message.h>
#include <csapex/utility/interlude.hpp>
/// SYSTEM
#include <yaml-cpp/eventhandler.h>
CSAPEX_REGISTER_CLASS(csapex::ImportRos, csapex::Node)
using namespace csapex;
const std::string ImportRos::no_topic_("-----");
namespace {
ros::Time rosTime(u_int64_t stamp_micro_seconds) {
ros::Time t;
t.fromNSec(stamp_micro_seconds * 1e3);
return t;
}
}
ImportRos::ImportRos()
: connector_(nullptr), retries_(0), buffer_size_(1024), running_(true)
{
}
void ImportRos::setup(NodeModifier& node_modifier)
{
input_time_ = node_modifier.addOptionalInput<connection_types::TimeStampMessage>("time");
connector_ = node_modifier.addOutput<connection_types::AnyMessage>("Something");
}
void ImportRos::setupParameters(Parameterizable& parameters)
{
std::vector<std::string> set;
set.push_back(no_topic_);
parameters.addParameter(csapex::param::ParameterFactory::declareParameterStringSet("topic", set),
std::bind(&ImportRos::update, this));
parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("refresh"),
std::bind(&ImportRos::refresh, this));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("rate", 0.1, 100.0, 60.0, 0.1),
std::bind(&ImportRos::updateRate, this));
parameters.addParameter(csapex::param::ParameterFactory::declareRange("queue", 0, 30, 1, 1),
std::bind(&ImportRos::updateSubscriber, this));
parameters.addParameter(csapex::param::ParameterFactory::declareBool("latch", false));
std::function<bool()> connected_condition = [&]() { return msg::isConnected(input_time_); };
csapex::param::Parameter::Ptr buffer_p = csapex::param::ParameterFactory::declareRange("buffer/length", 0.0, 10.0, 1.0, 0.1);
parameters.addConditionalParameter(buffer_p, connected_condition);
csapex::param::Parameter::Ptr max_wait_p = csapex::param::ParameterFactory::declareRange("buffer/max_wait", 0.0, 10.0, 1.0, 0.1);
parameters.addConditionalParameter(max_wait_p, connected_condition);
}
void ImportRos::setupROS()
{
refresh();
}
void ImportRos::refresh()
{
ROSHandler& rh = getRosHandler();
if(rh.nh()) {
std::string old_topic = readParameter<std::string>("topic");
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
param::SetParameter::Ptr setp = std::dynamic_pointer_cast<param::SetParameter>(getParameter("topic"));
if(setp) {
node_modifier_->setNoError();
bool found = false;
std::vector<std::string> topics_str;
topics_str.push_back(no_topic_);
for(ros::master::V_TopicInfo::const_iterator it = topics.begin(); it != topics.end(); ++it) {
topics_str.push_back(it->name);
if(it->name == old_topic) {
found = true;
}
}
if(!found) {
topics_str.push_back(old_topic);
}
setp->setSet(topics_str);
if(old_topic != no_topic_) {
setp->set(old_topic);
}
return;
}
}
node_modifier_->setWarning("no ROS connection");
}
void ImportRos::update()
{
retries_ = 5;
if(node_modifier_->isProcessingEnabled()) {
waitForTopic();
}
}
void ImportRos::updateRate()
{
setTickFrequency(readParameter<double>("rate"));
}
void ImportRos::updateSubscriber()
{
if(!current_topic_.name.empty()) {
current_subscriber = RosMessageConversion::instance().subscribe(current_topic_, readParameter<int>("queue"), std::bind(&ImportRos::callback, this, std::placeholders::_1));
}
}
bool ImportRos::doSetTopic()
{
getRosHandler().refresh();
if(!getRosHandler().isConnected()) {
node_modifier_->setError("no connection to ROS");
return false;
}
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
std::string topic = readParameter<std::string>("topic");
if(topic == no_topic_) {
return true;
}
for(ros::master::V_TopicInfo::iterator it = topics.begin(); it != topics.end(); ++it) {
if(it->name == topic) {
setTopic(*it);
retries_ = 0;
return true;
}
}
std::stringstream ss;
ss << "cannot set topic, " << topic << " doesn't exist";
if(retries_ > 0) {
ss << ", " << retries_ << " retries left";
}
ss << ".";
node_modifier_->setWarning(ss.str());
return false;
}
void ImportRos::processROS()
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
INTERLUDE("process");
// first check if connected -> if not connected, we only use tick
if(!msg::isConnected(input_time_)) {
return;
}
// now that we are connected, check that we have a valid message
if(!msg::hasMessage(input_time_)) {
return;
}
// INPUT CONNECTED
connection_types::TimeStampMessage::ConstPtr time = msg::getMessage<connection_types::TimeStampMessage>(input_time_);
if(msgs_.empty()) {
return;
}
if(time->value == ros::Time(0)) {
node_modifier_->setWarning("incoming time is 0, using default behaviour");
publishLatestMessage();
return;
}
if(rosTime(msgs_.back()->stamp_micro_seconds) == ros::Time(0)) {
node_modifier_->setWarning("buffered time is 0, using default behaviour");
publishLatestMessage();
return;
}
// drop old messages
ros::Duration keep_duration(readParameter<double>("buffer/length"));
while(!msgs_.empty() && rosTime(msgs_.front()->stamp_micro_seconds) + keep_duration < time->value) {
msgs_.pop_front();
}
if(!msgs_.empty()) {
if(rosTime(msgs_.front()->stamp_micro_seconds) > time->value) {
// aerr << "time stamp " << time->value << " is too old, oldest buffered is " << rosTime(msgs_.front()->stamp_micro_seconds) << std::endl;
// return;
}
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.front()->stamp_micro_seconds) + max_wait_duration < time->value) {
// aerr << "[1] time stamp " << time->value << " is too new" << std::endl;
// return;
}
}
// wait until we have a message
if(!isStampCovered(time->value)) {
ros::Rate r(10);
while(!isStampCovered(time->value) && running_) {
r.sleep();
ros::spinOnce();
if(!msgs_.empty()) {
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp_micro_seconds) + max_wait_duration < time->value) {
aerr << "[2] time stamp " << time->value << " is too new, latest stamp is " << rosTime(msgs_.back()->stamp_micro_seconds) << std::endl;
return;
}
}
}
}
if(msgs_.empty()) {
node_modifier_->setWarning("No messages received");
return;
}
std::deque<connection_types::Message::ConstPtr>::iterator first_after = msgs_.begin();
while(rosTime((*first_after)->stamp_micro_seconds) < time->value) {
++first_after;
}
if(first_after == msgs_.begin()) {
msg::publish(connector_, *first_after);
return;
} else if(first_after == msgs_.end()) {
assert(false);
node_modifier_->setWarning("Should not happen.....");
return;
} else {
std::deque<connection_types::Message::ConstPtr>::iterator last_before = first_after - 1;
ros::Duration diff1 = rosTime((*first_after)->stamp_micro_seconds) - time->value;
ros::Duration diff2 = rosTime((*last_before)->stamp_micro_seconds) - time->value;
if(diff1 < diff2) {
msg::publish(connector_, *first_after);
} else {
msg::publish(connector_, *last_before);
}
}
}
bool ImportRos::isStampCovered(const ros::Time &stamp)
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
return rosTime(msgs_.back()->stamp_micro_seconds) >= stamp;
}
void ImportRos::waitForTopic()
{
INTERLUDE("wait");
ros::WallDuration poll_wait(0.5);
while(retries_ --> 0) {
bool topic_exists = doSetTopic();
if(topic_exists) {
return;
} else {
ROS_WARN_STREAM("waiting for topic " << readParameter<std::string>("topic"));
poll_wait.sleep();
}
}
}
bool ImportRos::canTick()
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
return !msg::isConnected(input_time_) && !msgs_.empty();
}
void ImportRos::tickROS()
{
INTERLUDE("tick");
if(retries_ > 0) {
waitForTopic();
}
if(msg::isConnected(input_time_)) {
return;
}
// NO INPUT CONNECTED -> ONLY KEEP CURRENT MESSAGE
{
INTERLUDE("pop");
while(msgs_.size() > 1) {
msgs_.pop_front();
}
}
if(!current_topic_.name.empty()) {
publishLatestMessage();
}
}
void ImportRos::publishLatestMessage()
{
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
INTERLUDE("publish");
if(msgs_.empty()) {
INTERLUDE("wait for message");
ros::WallRate r(10);
while(msgs_.empty() && running_) {
r.sleep();
ros::spinOnce();
}
if(!running_) {
return;
}
}
msg::publish(connector_, msgs_.back());
if(!readParameter<bool>("latch")) {
msgs_.clear();
}
}
// FIXME: this can be still called after the object is destroyed!
void ImportRos::callback(ConnectionTypeConstPtr message)
{
connection_types::Message::ConstPtr msg = std::dynamic_pointer_cast<connection_types::Message const>(message);
if(msg) {
std::unique_lock<std::recursive_mutex> lock(msgs_mtx_);
if(!msgs_.empty() && msg->stamp_micro_seconds < msgs_.front()->stamp_micro_seconds) {
awarn << "detected time anomaly -> reset";
msgs_.clear();
}
if(!msg::isConnected(input_time_)) {
msgs_.clear();
}
msgs_.push_back(msg);
while((int) msgs_.size() > buffer_size_) {
msgs_.pop_front();
}
}
}
void ImportRos::setTopic(const ros::master::TopicInfo &topic)
{
if(topic.name == current_topic_.name) {
return;
}
current_subscriber.shutdown();
//if(RosMessageConversion::instance().isTopicTypeRegistered(topic)) {
node_modifier_->setNoError();
current_topic_ = topic;
updateSubscriber();
// } else {
// node_modifier_->setError(std::string("cannot import topic of type ") + topic.datatype);
// return;
// }
}
void ImportRos::setParameterState(Memento::Ptr memento)
{
Node::setParameterState(memento);
}
void ImportRos::abort()
{
running_ = false;
}
<|endoftext|> |
<commit_before><commit_msg>Fix XDK code so that it uses size_t instead of int.<commit_after><|endoftext|> |
<commit_before>#include "agfsio.hpp"
#include <endian.h>
#include <unistd.h>
int agfs_write_cmd(int fd, cmd_t cmd)
{
cmd = htobe16(cmd);
return write(fd, &cmd, sizeof(cmd_t));
}
int agfs_read_cmd(int fd, cmd_t& cmd)
{
int err = read(fd, &cmd, sizeof(cmd_t));
cmd = be16toh(cmd);
return err;
}
struct agfs_stat {
agdev_t st_dev;
agmode_t st_mode;
agsize_t st_size;
};
int agfs_write_stat(int fd, struct stat& buf)
{
struct agfs_stat result;
memset(&result, 0, sizeof(struct agfs_stat));
result.st_dev = buf.st_dev;
result.st_mode = buf.st_mode;
result.size = buf.st_size;
return write(fd, &result, sizeof(struct stat));
}
int agfs_read_stat(int fd, struct stat& buf)
{
struct agfs_stat result;
memset(&result, 0, sizeof(struct agfs_stat));
//Switch the bytes of all the fields around.
int err = 0;
if ((err = read(fd, &result, sizeof(struct agfs_stat))) >= 0) {
memset(&buf, 0, sizeof(struct stat));
buf.st_dev = be64toh(result.st_dev);
buf.st_mode = be32toh(result.st_mode);
buf.st_size = be64toh(result.st_size);
}
return err;
}
<commit_msg>Modified the write and read stat functions to write/read values from the underlying stream, rather than indirectly write/read to/from a struct.<commit_after>#include "agfsio.hpp"
#include <endian.h>
#include <unistd.h>
int agfs_write_cmd(int fd, cmd_t cmd)
{
cmd = htobe16(cmd);
return write(fd, &cmd, sizeof(cmd_t));
}
int agfs_read_cmd(int fd, cmd_t& cmd)
{
int err = read(fd, &cmd, sizeof(cmd_t));
cmd = be16toh(cmd);
return err;
}
struct agfs_stat {
agdev_t st_dev;
agmode_t st_mode;
agsize_t st_size;
};
int agfs_write_stat(int fd, struct stat& buf)
{
int temp, total_written;
agdev_t dev = buf.st_dev;
if ((temp = write(fd, &dev, sizeof(agdev_t))) < 0) {
return temp;
}
total_written += temp;
agmode_t mode = buf.st_mode;
if ((temp = write(fd, &mode, sizeof(agmode_t))) < 0) {
return temp;
}
total_written += temp;
agsize_t size = buf.st_size;
if ((temp = write(fd, &size, sizeof(agsize_t))) < 0) {
return temp;
}
total_written += temp;
return total_written;
}
int agfs_read_stat(int fd, struct stat& buf)
{
int temp, total_read;
memset(&buf, 0, sizeof(struct stat));
agdev_t dev;
if ((temp = write(fd, &dev, sizeof(agdev_t))) < 0) {
return temp;
}
total_read += temp;
agmode_t mode;
if ((temp = read(fd, &mode, sizeof(agmode_t))) < 0) {
return temp;
}
total_read += temp;
agsize_t size;
if ((temp = write(fd, &size, sizeof(agsize_t))) < 0) {
return temp;
}
total_read += temp;
buf.st_size = size;
buf.st_mode = mode;
buf.st_dev = dev;
return total_read;
}
<|endoftext|> |
<commit_before>#include "generated/cpp/ApplicationBase.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"
#include "json/JSONIterator.h"
#include "rubyext/WebView.h"
#ifdef RHODES_EMULATOR
#define RHO_APPS_DIR ""
#else
#define RHO_APPS_DIR "apps/"
#endif
extern "C" void rho_sys_app_exit();
extern "C" void rho_title_change(const int tabIndex, const char* strTitle);
namespace rho {
#ifdef OS_ANDROID
void rho_impl_setNativeMenu(const Vector<String>& menu);
String rho_impl_getNativeMenu();
#endif
using namespace apiGenerator;
using namespace common;
class CApplicationImpl: public CApplicationSingletonBase
{
public:
CApplicationImpl(): CApplicationSingletonBase(){}
virtual void getAppBundleFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/") );
}
virtual void getAppsBundleFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
}
virtual void getBundleFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_native_rhopath() );
}
virtual void getUserFolder(rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_MACOSX
oResult.set( CFilePath::join( rho_native_rhouserpath(), RHO_APPS_DIR) );
#else
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
#endif
}
virtual void getConfigPath(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getConfFilePath() );
}
virtual void getModelsManifestPath(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app_manifest.txt") );
}
virtual void getDatabaseBlobFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/db-files") );
}
virtual void getPublicFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"public") );
}
virtual void getStartURI(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("start_path") );
}
virtual void setStartURI( const rho::String& startURI, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("start_path", startURI, false );
}
virtual void getSettingsPageURI(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("options_path") );
}
virtual void setSettingsPageURI( const rho::String& settingsPageURI, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("options_path", settingsPageURI, false );
}
virtual void getSplash(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("splash_screen") );
}
virtual void getVersion(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("app_version") );
}
virtual void getTitle(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("title_text") );
}
virtual void setTitle( const rho::String& title, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("title_text", title, false);
#if defined(OS_WINCE) || defined (OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR)
rho_title_change(0, title.c_str());
#endif
}
virtual void getAppName(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHODESAPP().getAppName() );
}
virtual void getNativeMenu(rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_ANDROID
oResult.setJSON(rho_impl_getNativeMenu());
#else
rho::Vector< Hashtable<String, String> > arRes;
RHODESAPP().getAppMenu().getMenuItemsEx(arRes);
oResult.set(arRes);
#endif
}
virtual void setNativeMenu( const rho::Vector<rho::String>& value, rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_ANDROID
rho_impl_setNativeMenu(value);
RHODESAPP().getAppMenu().setAppBackUrlWithJSONItems(value);
#else
RHODESAPP().getAppMenu().setAppMenuJSONItemsEx(value);
#if defined (_WIN32_WCE)
rho_webview_update_menu(1);
#endif
#endif
}
virtual void getBadLinkURI(rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_WINCE
oResult.set( RHOCONF().getString("Application.BadLinkURI") );
#endif
}
virtual void modelFolderPath( const rho::String& name, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/" + name + "/") );
}
virtual void databaseFilePath( const rho::String& partitionName, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/syncdb" + partitionName + ".sqlite") );
}
virtual void expandDatabaseBlobFilePath( const rho::String& relativePath, rho::apiGenerator::CMethodResult& oResult)
{
if ( String_startsWith(relativePath, "file://") )
oResult.set(relativePath);
else
{
String dbRootFolder = CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR);
if ( !String_startsWith(relativePath, dbRootFolder) )
oResult.set( CFilePath::join( dbRootFolder, relativePath ) );
else {
oResult.set(relativePath);
}
}
}
virtual void relativeDatabaseBlobFilePath( const rho::String& absolutePath, rho::apiGenerator::CMethodResult& oResult)
{
String dbRootFolder = CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR);
if ( String_startsWith(absolutePath, "file://") )
dbRootFolder = "file://" + dbRootFolder;
if ( String_startsWith(absolutePath, dbRootFolder) )
oResult.set( absolutePath.substr( dbRootFolder.length(), absolutePath.length()-dbRootFolder.length()) );
else
oResult.set( absolutePath );
}
virtual void quit(rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_app_exit();
}
virtual void minimize(rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().getExtManager().minimizeApp();
}
virtual void restore(rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().getExtManager().restoreApp();
}
virtual void getSecurityTokenNotPassed(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHODESAPP().isSecurityTokenNotPassed() );
}
virtual void getInvalidSecurityTokenStartPath(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("invalid_security_token_start_path") );
}
virtual void setInvalidSecurityTokenStartPath( const rho::String& invalidSecurityTokenStartPath, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("invalid_security_token_start_path", invalidSecurityTokenStartPath, false );
}
virtual void setApplicationNotify(rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().setApplicationEventHandler(oResult);
}
virtual void getRhoPlatformVersion(rho::apiGenerator::CMethodResult& oResult)
{
//TODO: getRhoPlatformVersion
}
};
////////////////////////////////////////////////////////////////////////
class CApplicationFactory: public CApplicationFactoryBase
{
public:
~CApplicationFactory(){}
IApplicationSingleton* createModuleSingleton()
{
return new CApplicationImpl();
}
};
}
extern "C" void Init_Application()
{
rho::CApplicationFactory::setInstance( new rho::CApplicationFactory() );
rho::Init_Application_API();
RHODESAPP().getExtManager().requireRubyFile("RhoApplicationApi");
}
<commit_msg>all: adding getRhoPlatformVersion<commit_after>#include "generated/cpp/ApplicationBase.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"
#include "json/JSONIterator.h"
#include "rubyext/WebView.h"
#ifdef RHODES_EMULATOR
#define RHO_APPS_DIR ""
#else
#define RHO_APPS_DIR "apps/"
#endif
extern "C" void rho_sys_app_exit();
extern "C" void rho_title_change(const int tabIndex, const char* strTitle);
namespace rho {
#ifdef OS_ANDROID
void rho_impl_setNativeMenu(const Vector<String>& menu);
String rho_impl_getNativeMenu();
#endif
using namespace apiGenerator;
using namespace common;
class CApplicationImpl: public CApplicationSingletonBase
{
public:
CApplicationImpl(): CApplicationSingletonBase(){}
virtual void getAppBundleFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/") );
}
virtual void getAppsBundleFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
}
virtual void getBundleFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_native_rhopath() );
}
virtual void getUserFolder(rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_MACOSX
oResult.set( CFilePath::join( rho_native_rhouserpath(), RHO_APPS_DIR) );
#else
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR) );
#endif
}
virtual void getConfigPath(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getConfFilePath() );
}
virtual void getModelsManifestPath(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app_manifest.txt") );
}
virtual void getDatabaseBlobFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/db-files") );
}
virtual void getPublicFolder(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"public") );
}
virtual void getStartURI(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("start_path") );
}
virtual void setStartURI( const rho::String& startURI, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("start_path", startURI, false );
}
virtual void getSettingsPageURI(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("options_path") );
}
virtual void setSettingsPageURI( const rho::String& settingsPageURI, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("options_path", settingsPageURI, false );
}
virtual void getSplash(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("splash_screen") );
}
virtual void getVersion(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("app_version") );
}
virtual void getTitle(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("title_text") );
}
virtual void setTitle( const rho::String& title, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("title_text", title, false);
#if defined(OS_WINCE) || defined (OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR)
rho_title_change(0, title.c_str());
#endif
}
virtual void getAppName(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHODESAPP().getAppName() );
}
virtual void getNativeMenu(rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_ANDROID
oResult.setJSON(rho_impl_getNativeMenu());
#else
rho::Vector< Hashtable<String, String> > arRes;
RHODESAPP().getAppMenu().getMenuItemsEx(arRes);
oResult.set(arRes);
#endif
}
virtual void setNativeMenu( const rho::Vector<rho::String>& value, rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_ANDROID
rho_impl_setNativeMenu(value);
RHODESAPP().getAppMenu().setAppBackUrlWithJSONItems(value);
#else
RHODESAPP().getAppMenu().setAppMenuJSONItemsEx(value);
#if defined (_WIN32_WCE)
rho_webview_update_menu(1);
#endif
#endif
}
virtual void getBadLinkURI(rho::apiGenerator::CMethodResult& oResult)
{
#ifdef OS_WINCE
oResult.set( RHOCONF().getString("Application.BadLinkURI") );
#endif
}
virtual void modelFolderPath( const rho::String& name, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhopath(), RHO_APPS_DIR"app/" + name + "/") );
}
virtual void databaseFilePath( const rho::String& partitionName, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR"/db/syncdb" + partitionName + ".sqlite") );
}
virtual void expandDatabaseBlobFilePath( const rho::String& relativePath, rho::apiGenerator::CMethodResult& oResult)
{
if ( String_startsWith(relativePath, "file://") )
oResult.set(relativePath);
else
{
String dbRootFolder = CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR);
if ( !String_startsWith(relativePath, dbRootFolder) )
oResult.set( CFilePath::join( dbRootFolder, relativePath ) );
else {
oResult.set(relativePath);
}
}
}
virtual void relativeDatabaseBlobFilePath( const rho::String& absolutePath, rho::apiGenerator::CMethodResult& oResult)
{
String dbRootFolder = CFilePath::join( rho_native_rhodbpath(), RHO_EMULATOR_DIR);
if ( String_startsWith(absolutePath, "file://") )
dbRootFolder = "file://" + dbRootFolder;
if ( String_startsWith(absolutePath, dbRootFolder) )
oResult.set( absolutePath.substr( dbRootFolder.length(), absolutePath.length()-dbRootFolder.length()) );
else
oResult.set( absolutePath );
}
virtual void quit(rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_app_exit();
}
virtual void minimize(rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().getExtManager().minimizeApp();
}
virtual void restore(rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().getExtManager().restoreApp();
}
virtual void getSecurityTokenNotPassed(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHODESAPP().isSecurityTokenNotPassed() );
}
virtual void getInvalidSecurityTokenStartPath(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(RHOCONF().getString("invalid_security_token_start_path"));
}
virtual void setInvalidSecurityTokenStartPath( const rho::String& invalidSecurityTokenStartPath, rho::apiGenerator::CMethodResult& oResult)
{
RHOCONF().setString("invalid_security_token_start_path", invalidSecurityTokenStartPath, false );
}
virtual void setApplicationNotify(rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().setApplicationEventHandler(oResult);
}
virtual void getRhoPlatformVersion(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(RHOCONF().getString("rhodes_gem_version"));
}
};
////////////////////////////////////////////////////////////////////////
class CApplicationFactory: public CApplicationFactoryBase
{
public:
~CApplicationFactory(){}
IApplicationSingleton* createModuleSingleton()
{
return new CApplicationImpl();
}
};
}
extern "C" void Init_Application()
{
rho::CApplicationFactory::setInstance( new rho::CApplicationFactory() );
rho::Init_Application_API();
RHODESAPP().getExtManager().requireRubyFile("RhoApplicationApi");
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief player クラス
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include "core/glcore.hpp"
#include "gui_test.hpp"
#include "widgets/widget_utils.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_slider.hpp"
#include "widgets/widget_check.hpp"
#include "widgets/widget_radio.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_image.hpp"
#include "widgets/widget_text.hpp"
#include "widgets/widget_tree.hpp"
#include "widgets/widget_filer.hpp"
namespace app {
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void gui_test::initialize()
{
gl::core& core = gl::core::get_instance();
using namespace gui;
widget_director& wd = director_.at().widget_director_;
if(1) { // ラジオボタンのテスト
widget::param wpr(vtx::srect(20, 20, 130, 130), 0);
widget_null::param wpr_;
widget* root = wd.add_widget<widget_null>(wpr, wpr_);
root->set_state(widget::state::POSITION_LOCK);
widget::param wp(vtx::srect(0, 0, 130, 30), root);
widget_radio::param wp_("Enable");
wd.add_widget<widget_radio>(wp, wp_);
wp.rect_.org.y += 40;
wd.add_widget<widget_radio>(wp, wp_);
wp.rect_.org.y += 40;
wp_.check_ = true;
wd.add_widget<widget_radio>(wp, wp_);
}
if(1) { // イメージのテスト
widget::param wp(vtx::srect(400, 20, 500, 250));
img::paint pa;
pa.set_fore_color(img::rgba8(0, 255, 0));
pa.create(vtx::spos(500, 250), true);
pa.fill(img::rgba8(255, 100, 100));
pa.alpha_blend();
pa.fill_circle(vtx::spos(250), 220);
vtx::sposs ss;
ss.push_back(vtx::spos(10, 10));
ss.push_back(vtx::spos(100, 100));
ss.push_back(vtx::spos(50, 200));
pa.set_fore_color(img::rgba8(240, 40, 50));
// pa.fill_polygon(ss);
widget_image::param wp_(&pa);
image_ = wd.add_widget<widget_image>(wp, wp_);
}
if(1) { // テキストのテスト
widget::param wp(vtx::srect(40, 50, 200, 250), image_);
widget_text::param wp_;
wp_.text_param_.text_ = "日本の美しい漢字\n吉野家qwertyuiop\n𩸽zxcvbnm";
wp_.text_param_.placement_.vpt = vtx::placement::vertical::CENTER;
wd.add_widget<widget_text>(wp, wp_);
}
if(1) { // ダイアログのテスト
widget::param wp(vtx::srect(300, 300, 300, 200));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::param::style::CANCEL_OK;
dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
dialog_->set_text("ああああ\nうううう\nいいいい\n漢字\n日本");
}
if(1) { // ボタンのテスト(ファイラー開始ボタン)
widget::param wp(vtx::srect(30, 150, 100, 40));
widget_button::param wp_("Filer");
filer_open_ = wd.add_widget<widget_button>(wp, wp_);
filer_open_->at_local_param().text_param_.alias_ = "ファイラー";
filer_open_->at_local_param().text_param_.alias_enable_ = true;
}
if(1) { // ボタンのテスト(メニュー開始ボタン)
widget::param wp(vtx::srect(30, 200, 100, 40));
widget_button::param wp_("Menu");
menu_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // ボタンのテスト(ダイアログ開始ボタン)
widget::param wp(vtx::srect(30, 250, 100, 40));
widget_button::param wp_("Daialog");
dialog_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // ラベルのテスト
widget::param wp(vtx::srect(30, 300, 150, 40));
widget_label::param wp_("Asdfg", false);
label_ = wd.add_widget<widget_label>(wp, wp_);
}
if(1) { // チェックボックスのテスト
widget::param wp(vtx::srect(20, 350, 150, 40));
widget_check::param wp_("Disable-g");
check_ = wd.add_widget<widget_check>(wp, wp_);
}
if(1) { // リストのテスト
widget::param wp(vtx::srect(30, 400, 150, 40), 0);
widget_list::param wp_("List Box");
wp_.text_list_.push_back("abc");
wp_.text_list_.push_back("1234");
wp_.text_list_.push_back("qwert");
wd.add_widget<widget_list>(wp, wp_);
}
if(1) { // スライダーのテスト
widget::param wp(vtx::srect(30, 450, 180, 20));
widget_slider::param wp_;
slider_ = wd.add_widget<widget_slider>(wp, wp_);
}
if(1) { // メニューのテスト
widget::param wp(vtx::srect(10, 10, 180, 30));
widget_menu::param wp_;
// wp_.round_ = false;
wp_.text_list_.push_back("First");
wp_.text_list_.push_back("Second");
wp_.text_list_.push_back("Third");
wp_.text_list_.push_back("Force");
menu_ = wd.add_widget<widget_menu>(wp, wp_);
}
if(1) { // フレームのテスト
widget::param wp(vtx::srect(200, 20, 100, 80));
widget_frame::param wp_;
frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
if(1) { // ファイラーのテスト
widget::param wp(vtx::srect(10, 30, 300, 200));
widget_filer::param wp_(core.get_current_path(), "", true);
filer_ = wd.add_widget<widget_filer>(wp, wp_);
filer_->enable(false);
}
if(1) { // ツリーのテスト
{
widget::param wp(vtx::srect(400, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
tree_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
widget::param wp(vtx::srect(0), tree_frame_);
widget_tree::param wp_;
tree_core_ = wd.add_widget<widget_tree>(wp, wp_);
tree_core_->set_state(widget::state::CLIP_PARENTS);
/// tree_core_->set_state(widget::state::POSITION_LOCK);
tree_core_->set_state(widget::state::RESIZE_ROOT);
tree_core_->set_state(widget::state::MOVE_ROOT, false);
widget_tree::tree_unit& tu = tree_core_->at_tree_unit();
tu.make_directory("/root0");
tu.make_directory("/root1");
tu.set_current_path("/root0");
{
widget_tree::value v;
v.data_ = "AAA";
tu.install("sub0", v);
}
{
widget_tree::value v;
v.data_ = "BBB";
tu.install("sub1", v);
}
tu.make_directory("sub2");
tu.set_current_path("sub2");
{
widget_tree::value v;
v.data_ = "CCC";
tu.install("sub-sub", v);
}
tu.set_current_path("/root1");
{
widget_tree::value v;
v.data_ = "ASDFG";
tu.install("sub_A", v);
}
{
widget_tree::value v;
v.data_ = "ZXCVB";
tu.install("sub_B", v);
}
// tu.list("/root");
// tu.list();
}
if(1) { // ターミナルのテスト
{
widget::param wp(vtx::srect(700, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::srect(0), terminal_frame_);
widget_terminal::param wp_;
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
}
}
// プリファレンスの取得
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->load(pre);
}
if(label_) {
label_->load(pre);
}
if(slider_) {
slider_->load(pre);
}
if(check_) {
check_->load(pre);
}
if(frame_) {
frame_->load(pre);
}
if(tree_frame_) {
tree_frame_->load(pre);
}
if(terminal_frame_) {
terminal_frame_->load(pre);
}
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void gui_test::update()
{
gui::widget_director& wd = director_.at().widget_director_;
if(dialog_open_) {
if(dialog_open_->get_selected()) {
if(dialog_) {
dialog_->enable();
}
}
}
if(filer_open_) {
if(filer_open_->get_selected()) {
if(filer_) {
filer_->enable(!filer_->get_state(gui::widget::state::ENABLE));
}
}
}
if(filer_) {
if(filer_id_ != filer_->get_select_file_id()) {
filer_id_ = filer_->get_select_file_id();
std::cout << "Filer: '" << filer_->get_file() << "'" << std::endl;
std::cout << std::flush;
}
}
if(menu_open_) {
if(menu_open_->get_selected()) {
if(menu_) {
menu_->enable(!menu_->get_state(gui::widget::state::ENABLE));
if(menu_->get_state(gui::widget::state::ENABLE)) {
// menu_->at_rect().org =
}
}
}
}
// メニューが選択された!
if(menu_) {
if(menu_id_ != menu_->get_select_id()) {
menu_id_ = menu_->get_select_id();
std::cout << "Menu: " << menu_->get_select_text() << std::endl;
}
}
/// if(terminal_core_) {
/// static wchar_t ch = ' ';
/// terminal_core_->output(ch);
/// ++ch;
/// if(ch >= 0x7f) ch = ' ';
/// }
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void gui_test::render()
{
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void gui_test::destroy()
{
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->save(pre);
}
if(terminal_frame_) {
terminal_frame_->save(pre);
}
if(tree_frame_) {
tree_frame_->save(pre);
}
if(check_) {
check_->save(pre);
}
if(slider_) {
slider_->save(pre);
}
if(label_) {
label_->save(pre);
}
if(frame_) {
frame_->save(pre);
}
}
}
<commit_msg>update widget select_func test<commit_after>//=====================================================================//
/*! @file
@brief player クラス
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include "core/glcore.hpp"
#include "gui_test.hpp"
#include "widgets/widget_utils.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_slider.hpp"
#include "widgets/widget_check.hpp"
#include "widgets/widget_radio.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_image.hpp"
#include "widgets/widget_text.hpp"
#include "widgets/widget_tree.hpp"
#include "widgets/widget_filer.hpp"
namespace app {
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void gui_test::initialize()
{
gl::core& core = gl::core::get_instance();
using namespace gui;
widget_director& wd = director_.at().widget_director_;
if(1) { // ラジオボタンのテスト
widget::param wpr(vtx::srect(20, 20, 130, 130), 0);
widget_null::param wpr_;
widget* root = wd.add_widget<widget_null>(wpr, wpr_);
root->set_state(widget::state::POSITION_LOCK);
widget::param wp(vtx::srect(0, 0, 130, 30), root);
widget_radio::param wp_("Enable");
for(int i = 0; i < 3; ++i) {
if(i == 2) wp_.check_ = true;
widget_radio* w = wd.add_widget<widget_radio>(wp, wp_);
w->at_local_param().select_func_ = [this](bool f, int n) {
std::cout << "Radio button: " << static_cast<int>(f) << " (" << n << ")" << std::endl;
};
wp.rect_.org.y += 40;
}
}
if(1) { // イメージのテスト
widget::param wp(vtx::srect(400, 20, 500, 250));
img::paint pa;
pa.set_fore_color(img::rgba8(0, 255, 0));
pa.create(vtx::spos(500, 250), true);
pa.fill(img::rgba8(255, 100, 100));
pa.alpha_blend();
pa.fill_circle(vtx::spos(250), 220);
vtx::sposs ss;
ss.push_back(vtx::spos(10, 10));
ss.push_back(vtx::spos(100, 100));
ss.push_back(vtx::spos(50, 200));
pa.set_fore_color(img::rgba8(240, 40, 50));
// pa.fill_polygon(ss);
widget_image::param wp_(&pa);
image_ = wd.add_widget<widget_image>(wp, wp_);
}
if(1) { // テキストのテスト
widget::param wp(vtx::srect(40, 50, 200, 250), image_);
widget_text::param wp_;
wp_.text_param_.text_ = "日本の美しい漢字\n吉野家qwertyuiop\n𩸽zxcvbnm";
wp_.text_param_.placement_.vpt = vtx::placement::vertical::CENTER;
wd.add_widget<widget_text>(wp, wp_);
}
if(1) { // ダイアログのテスト
widget::param wp(vtx::srect(300, 300, 300, 200));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::param::style::CANCEL_OK;
dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
dialog_->set_text("ああああ\nうううう\nいいいい\n漢字\n日本");
}
if(1) { // ボタンのテスト(ファイラー開始ボタン)
widget::param wp(vtx::srect(30, 150, 100, 40));
widget_button::param wp_("Filer");
filer_open_ = wd.add_widget<widget_button>(wp, wp_);
filer_open_->at_local_param().text_param_.alias_ = "ファイラー";
filer_open_->at_local_param().text_param_.alias_enable_ = true;
}
if(1) { // ボタンのテスト(メニュー開始ボタン)
widget::param wp(vtx::srect(30, 200, 100, 40));
widget_button::param wp_("Menu");
menu_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // ボタンのテスト(ダイアログ開始ボタン)
widget::param wp(vtx::srect(30, 250, 100, 40));
widget_button::param wp_("Daialog");
dialog_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // ラベルのテスト
widget::param wp(vtx::srect(30, 300, 150, 40));
widget_label::param wp_("Asdfg", false);
label_ = wd.add_widget<widget_label>(wp, wp_);
label_->at_local_param().select_func_ = [this](const std::string& t) {
std::cout << "Label: " << t << std::endl << std::flush;
};
}
if(1) { // チェックボックスのテスト
widget::param wp(vtx::srect(20, 350, 150, 40));
widget_check::param wp_("Disable-g");
check_ = wd.add_widget<widget_check>(wp, wp_);
check_->at_local_param().select_func_ = [this](bool f) {
std::cout << "Check: " << static_cast<int>(f) << std::endl;
};
}
if(1) { // リストのテスト
widget::param wp(vtx::srect(30, 400, 150, 40), 0);
widget_list::param wp_("List Box");
wp_.text_list_.push_back("abc");
wp_.text_list_.push_back("1234");
wp_.text_list_.push_back("qwert");
wd.add_widget<widget_list>(wp, wp_);
}
if(1) { // スライダーのテスト
widget::param wp(vtx::srect(30, 450, 180, 20));
widget_slider::param wp_;
slider_ = wd.add_widget<widget_slider>(wp, wp_);
}
if(1) { // メニューのテスト
widget::param wp(vtx::srect(10, 10, 180, 30));
widget_menu::param wp_;
// wp_.round_ = false;
wp_.text_list_.push_back("First");
wp_.text_list_.push_back("Second");
wp_.text_list_.push_back("Third");
wp_.text_list_.push_back("Force");
menu_ = wd.add_widget<widget_menu>(wp, wp_);
}
if(1) { // フレームのテスト
widget::param wp(vtx::srect(200, 20, 100, 80));
widget_frame::param wp_;
frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
if(1) { // ファイラーのテスト
widget::param wp(vtx::srect(10, 30, 300, 200));
widget_filer::param wp_(core.get_current_path(), "", true);
filer_ = wd.add_widget<widget_filer>(wp, wp_);
filer_->enable(false);
}
if(1) { // ツリーのテスト
{
widget::param wp(vtx::srect(400, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
tree_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
widget::param wp(vtx::srect(0), tree_frame_);
widget_tree::param wp_;
tree_core_ = wd.add_widget<widget_tree>(wp, wp_);
tree_core_->set_state(widget::state::CLIP_PARENTS);
/// tree_core_->set_state(widget::state::POSITION_LOCK);
tree_core_->set_state(widget::state::RESIZE_ROOT);
tree_core_->set_state(widget::state::MOVE_ROOT, false);
widget_tree::tree_unit& tu = tree_core_->at_tree_unit();
tu.make_directory("/root0");
tu.make_directory("/root1");
tu.set_current_path("/root0");
{
widget_tree::value v;
v.data_ = "AAA";
tu.install("sub0", v);
}
{
widget_tree::value v;
v.data_ = "BBB";
tu.install("sub1", v);
}
tu.make_directory("sub2");
tu.set_current_path("sub2");
{
widget_tree::value v;
v.data_ = "CCC";
tu.install("sub-sub", v);
}
tu.set_current_path("/root1");
{
widget_tree::value v;
v.data_ = "ASDFG";
tu.install("sub_A", v);
}
{
widget_tree::value v;
v.data_ = "ZXCVB";
tu.install("sub_B", v);
}
// tu.list("/root");
// tu.list();
}
if(1) { // ターミナルのテスト
{
widget::param wp(vtx::srect(700, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::srect(0), terminal_frame_);
widget_terminal::param wp_;
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
}
}
// プリファレンスの取得
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->load(pre);
}
if(label_) {
label_->load(pre);
}
if(slider_) {
slider_->load(pre);
}
if(check_) {
check_->load(pre);
}
if(frame_) {
frame_->load(pre);
}
if(tree_frame_) {
tree_frame_->load(pre);
}
if(terminal_frame_) {
terminal_frame_->load(pre);
}
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void gui_test::update()
{
gui::widget_director& wd = director_.at().widget_director_;
if(dialog_open_) {
if(dialog_open_->get_selected()) {
if(dialog_) {
dialog_->enable();
}
}
}
if(filer_open_) {
if(filer_open_->get_selected()) {
if(filer_) {
filer_->enable(!filer_->get_state(gui::widget::state::ENABLE));
}
}
}
if(filer_) {
if(filer_id_ != filer_->get_select_file_id()) {
filer_id_ = filer_->get_select_file_id();
std::cout << "Filer: '" << filer_->get_file() << "'" << std::endl;
std::cout << std::flush;
}
}
if(menu_open_) {
if(menu_open_->get_selected()) {
if(menu_) {
menu_->enable(!menu_->get_state(gui::widget::state::ENABLE));
if(menu_->get_state(gui::widget::state::ENABLE)) {
// menu_->at_rect().org =
}
}
}
}
// メニューが選択された!
if(menu_) {
if(menu_id_ != menu_->get_select_id()) {
menu_id_ = menu_->get_select_id();
std::cout << "Menu: " << menu_->get_select_text() << std::endl;
}
}
/// if(terminal_core_) {
/// static wchar_t ch = ' ';
/// terminal_core_->output(ch);
/// ++ch;
/// if(ch >= 0x7f) ch = ' ';
/// }
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void gui_test::render()
{
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void gui_test::destroy()
{
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->save(pre);
}
if(terminal_frame_) {
terminal_frame_->save(pre);
}
if(tree_frame_) {
tree_frame_->save(pre);
}
if(check_) {
check_->save(pre);
}
if(slider_) {
slider_->save(pre);
}
if(label_) {
label_->save(pre);
}
if(frame_) {
frame_->save(pre);
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include "parser/parser.hpp"
#include "serializer/serializer.hpp"
#include "serializerHtml/serializerHtml.hpp"
using namespace std;
using namespace webss;
enum class ErrorType { NONE, FATAL, PARSE, SERIALIZE, PARSE_AFTER_SERIALIZATION, EQUALITY, TEST };
string makeCompleteFilenameIn(string filename);
string makeCompleteFilenameOut(string filename);
ErrorType test(string filename, function<void(const Document& doc)> checkResult);
void testDictionary();
void testTemplateStandard();
ErrorType testSerializerHtml();
char inChar;
int main()
{
//#define TEST_PERFORMANCE
#ifdef TEST_PERFORMANCE
for (int i = 0; i < 2000; ++i)
#else
do
#endif
{
vector<string> filenames { "strings", "expandTuple", "templateBlock", "namespace", "enum",
"list", "tuple", "names-keywords", "multiline-string-options",
"option" };
for (const auto& filename : filenames)
{
test(filename, [](const Document&) {});
cout << endl;
}
#ifdef TEST_PERFORMANCE
}
#else
testDictionary();
cout << endl;
testTemplateStandard();
cout << endl;
testSerializerHtml();
cin >> inChar;
} while (inChar != 'q');
#endif
return 0;
}
string makeCompleteFilenameIn(string filename)
{
return "files-in/" + filename + ".wbsn";
}
string makeCompleteFilenameOut(string filename)
{
return filename + ".wbsnout";
}
//"SOFt assERT
void sofert(bool condition, string errorMsg = "")
{
if (condition)
return;
throw logic_error(errorMsg == "" ? "assert failed" : errorMsg.c_str());
}
ErrorType tryParse(string filenameIn, Document& doc)
{
ifstream fileIn(filenameIn, ios::binary);
if (fileIn.fail())
{
cout << "Error: failed to open file \"" << filenameIn << "\"" << endl;
return ErrorType::FATAL;
}
try
{
doc = Parser(fileIn).parseDocument();
}
catch (const exception& e)
{
cout << "Parse failed: " << e.what() << endl;
return ErrorType::PARSE;
}
return ErrorType::NONE;
}
template <class Serializer>
ErrorType trySerialize(string filenameOut, string& output, const Document& doc)
{
ofstream fileOut(filenameOut, ios::binary);
if (fileOut.fail())
{
cout << "Error: failed to open file \"" << filenameOut << "\"" << endl;
return ErrorType::FATAL;
}
try
{
output = Serializer::serialize(doc);
fileOut << output;
fileOut.flush();
}
catch (const exception& e)
{
cout << "Serialization failed: " << e.what() << endl;
return ErrorType::SERIALIZE;
}
return ErrorType::NONE;
}
//you have to first verify that the parsed stuff is good
//then serialize it, parse the result, and make sure it
//equals the first parse
ErrorType test(string filename, function<void(const Document& doc)> checkResult)
{
string filenameOut(makeCompleteFilenameOut(filename));
cout << "Input: " << filename << endl;
Document doc;
ErrorType errorParse = tryParse(makeCompleteFilenameIn(filename), doc);
if (errorParse != ErrorType::NONE)
return errorParse;
cout << "No errors while parsing" << endl;
string output;
ErrorType errorSerialize = trySerialize<Serializer>(makeCompleteFilenameOut(filename), output, doc);
if (errorSerialize != ErrorType::NONE)
return errorSerialize;
cout << "No errors while serializing" << endl;
Document newDoc;
try
{
newDoc = Parser(output).parseDocument();
}
catch (const exception& e)
{
cout << "Parse after serialization failed: " << e.what() << endl;
return ErrorType::PARSE_AFTER_SERIALIZATION;
}
if (newDoc != doc)
{
cout << "Equality failed: serialized document not equal to parsed doc" << endl;
return ErrorType::EQUALITY;
}
try
{
checkResult(doc);
}
catch (const exception& e)
{
cout << "Test failed: " << e.what() << endl;
return ErrorType::TEST;
}
cout << "No errors while testing" << endl;
return ErrorType::NONE;
}
void testDictionary()
{
test("dictionary", [](const Document& doc)
{
const auto& webssDict = doc.getData()[0];
sofert(webssDict.isDictionary());
const auto& dict = webssDict.getDictionary();
sofert(dict.size() == 4);
sofert(dict.has("a_list"));
sofert(dict.has("key1"));
sofert(dict.has("key2"));
sofert(dict.has("other-dict"));
sofert(dict["a_list"].isList() && dict["a_list"].getList().size() == 4);
sofert((int)dict["a_list"][0] == 0 && (int)dict["a_list"][1] == 1 && (int)dict["a_list"][2] == 2 && (int)dict["a_list"][3] == 3);
sofert(dict["key1"].isInt() && dict["key1"].getInt() == 2);
sofert(dict["key2"].isString() && dict["key2"].getString() == "text");
sofert(dict["other-dict"].isDictionary() && dict["other-dict"].getDictionary().has("key") && dict["other-dict"]["key"].isBool() && dict["other-dict"]["key"].getBool() == true);
});
}
void testTemplateStandard()
{
test("templateStandard", [](const Document& doc)
{
sofert(doc.size() == 5);
sofert(doc.has("template1") && doc.has("template2"));
const auto& templ1 = doc["template1"];
const auto& templ2 = doc["template2"];
sofert(templ1 == doc[0] && templ2 == doc[1]);
sofert(templ1 == templ2);
{
sofert(templ1.isList());
const auto& list = templ1.getList();
sofert(list.size() == 2);
sofert(list[0].isTuple());
sofert(list[1].isTuple());
{
const auto& tuple = list[0].getTuple();
sofert(tuple.size() == 3);
sofert(tuple[0].isString() && tuple[0].getString() == "First");
sofert(tuple[1].isString() && tuple[1].getString() == "Last");
sofert(tuple[2].isInt() && tuple[2].getInt() == 38);
sofert(tuple.has("firstName") && tuple.has("lastName") && tuple.has("age"));
sofert(tuple["firstName"].isString() && tuple["firstName"].getString() == "First");
sofert(tuple["lastName"].isString() && tuple["lastName"].getString() == "Last");
sofert(tuple["age"].isInt() && tuple["age"].getInt() == 38);
}
{
const auto& tuple = list[1].getTuple();
sofert(tuple.size() == 3);
sofert(tuple[0].isString() && tuple[0].getString() == "Second");
sofert(tuple[1].isString() && tuple[1].getString() == "Third");
sofert(tuple[2].isInt() && tuple[2].getInt() == 47);
sofert(tuple.has("firstName") && tuple.has("lastName") && tuple.has("age"));
sofert(tuple["firstName"].isString() && tuple["firstName"].getString() == "Second");
sofert(tuple["lastName"].isString() && tuple["lastName"].getString() == "Third");
sofert(tuple["age"].isInt() && tuple["age"].getInt() == 47);
}
}
Tuple tupleTempl3;
const auto& templ3 = doc[2];
{
sofert(templ3.isTuple());
const auto& tuple = templ3.getTuple();
sofert(tuple.size() == 2);
sofert(tuple[0].isString() && tuple[0].getString() == "default1");
sofert(tuple[1].isString() && tuple[1].getString() == "default2");
sofert(tuple.has("val1") && tuple.has("val2"));
sofert(tuple["val1"].isString() && tuple["val1"].getString() == "default1");
sofert(tuple["val2"].isString() && tuple["val2"].getString() == "default2");
tupleTempl3 = tuple;
}
const auto& templ4 = doc[3];
sofert(templ4.isList() && templ4.getList().empty());
const auto& templ5 = doc[4];
{
sofert(templ5.isList());
const auto& list = templ5.getList();
sofert(list.size() == 1);
sofert(list[0].isTuple());
sofert(tupleTempl3 == list[0].getTuple());
}
});
}
ErrorType testSerializerHtml()
{
string filename("test-serializer-html");
string filenameIn("files-serializer-html/" + filename + ".wbsn");
string filenameOut(filename + ".wbsnout"); //not html as not yet in .gitignore
cout << "Input: " << filename << endl;
Document doc;
ErrorType errorParse = tryParse(filenameIn, doc);
if (errorParse != ErrorType::NONE)
return errorParse;
cout << "No errors while parsing" << endl;
string output;
ErrorType errorSerialize = trySerialize<SerializerHtml>(filenameOut, output, doc);
if (errorSerialize != ErrorType::NONE)
return errorSerialize;
cout << "No errors while serializing" << endl;
return ErrorType::NONE;
}<commit_msg>Tests sofert puts line of code<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include "parser/parser.hpp"
#include "serializer/serializer.hpp"
#include "serializerHtml/serializerHtml.hpp"
using namespace std;
using namespace webss;
enum class ErrorType { NONE, FATAL, PARSE, SERIALIZE, PARSE_AFTER_SERIALIZATION, EQUALITY, TEST };
string makeCompleteFilenameIn(string filename);
string makeCompleteFilenameOut(string filename);
ErrorType test(string filename, function<void(const Document& doc)> checkResult);
void testDictionary();
void testTemplateStandard();
ErrorType testSerializerHtml();
char inChar;
int main()
{
//#define TEST_PERFORMANCE
#ifdef TEST_PERFORMANCE
for (int i = 0; i < 2000; ++i)
#else
do
#endif
{
vector<string> filenames { "strings", "expandTuple", "templateBlock", "namespace", "enum",
"list", "tuple", "names-keywords", "multiline-string-options",
"option" };
for (const auto& filename : filenames)
{
test(filename, [](const Document&) {});
cout << endl;
}
#ifdef TEST_PERFORMANCE
}
#else
testDictionary();
cout << endl;
testTemplateStandard();
cout << endl;
testSerializerHtml();
cin >> inChar;
} while (inChar != 'q');
#endif
return 0;
}
string makeCompleteFilenameIn(string filename)
{
return "files-in/" + filename + ".wbsn";
}
string makeCompleteFilenameOut(string filename)
{
return filename + ".wbsnout";
}
void softAssert(bool condition, unsigned int line)
{
if (condition)
return;
throw logic_error(string("[ln ") + to_string(line) + "] assert failed");
}
//SOFt assERT
#define sofert(condition) { softAssert(condition, __LINE__); }
ErrorType tryParse(string filenameIn, Document& doc)
{
ifstream fileIn(filenameIn, ios::binary);
if (fileIn.fail())
{
cout << "Error: failed to open file \"" << filenameIn << "\"" << endl;
return ErrorType::FATAL;
}
try
{
doc = Parser(fileIn).parseDocument();
}
catch (const exception& e)
{
cout << "Parse failed: " << e.what() << endl;
return ErrorType::PARSE;
}
return ErrorType::NONE;
}
template <class Serializer>
ErrorType trySerialize(string filenameOut, string& output, const Document& doc)
{
ofstream fileOut(filenameOut, ios::binary);
if (fileOut.fail())
{
cout << "Error: failed to open file \"" << filenameOut << "\"" << endl;
return ErrorType::FATAL;
}
try
{
output = Serializer::serialize(doc);
fileOut << output;
fileOut.flush();
}
catch (const exception& e)
{
cout << "Serialization failed: " << e.what() << endl;
return ErrorType::SERIALIZE;
}
return ErrorType::NONE;
}
//you have to first verify that the parsed stuff is good
//then serialize it, parse the result, and make sure it
//equals the first parse
ErrorType test(string filename, function<void(const Document& doc)> checkResult)
{
string filenameOut(makeCompleteFilenameOut(filename));
cout << "Input: " << filename << endl;
Document doc;
ErrorType errorParse = tryParse(makeCompleteFilenameIn(filename), doc);
if (errorParse != ErrorType::NONE)
return errorParse;
cout << "No errors while parsing" << endl;
string output;
ErrorType errorSerialize = trySerialize<Serializer>(makeCompleteFilenameOut(filename), output, doc);
if (errorSerialize != ErrorType::NONE)
return errorSerialize;
cout << "No errors while serializing" << endl;
Document newDoc;
try
{
newDoc = Parser(output).parseDocument();
}
catch (const exception& e)
{
cout << "Parse after serialization failed: " << e.what() << endl;
return ErrorType::PARSE_AFTER_SERIALIZATION;
}
if (newDoc != doc)
{
cout << "Equality failed: serialized document not equal to parsed doc" << endl;
return ErrorType::EQUALITY;
}
try
{
checkResult(doc);
}
catch (const exception& e)
{
cout << "Test failed: " << e.what() << endl;
return ErrorType::TEST;
}
cout << "No errors while testing" << endl;
return ErrorType::NONE;
}
void testDictionary()
{
test("dictionary", [](const Document& doc)
{
const auto& webssDict = doc.getData()[0];
sofert(webssDict.isDictionary());
const auto& dict = webssDict.getDictionary();
sofert(dict.size() == 4);
sofert(dict.has("a_list"));
sofert(dict.has("key1"));
sofert(dict.has("key2"));
sofert(dict.has("other-dict"));
sofert(dict["a_list"].isList() && dict["a_list"].getList().size() == 4);
sofert((int)dict["a_list"][0] == 0 && (int)dict["a_list"][1] == 1 && (int)dict["a_list"][2] == 2 && (int)dict["a_list"][3] == 3);
sofert(dict["key1"].isInt() && dict["key1"].getInt() == 2);
sofert(dict["key2"].isString() && dict["key2"].getString() == "text");
sofert(dict["other-dict"].isDictionary() && dict["other-dict"].getDictionary().has("key") && dict["other-dict"]["key"].isBool() && dict["other-dict"]["key"].getBool() == true);
});
}
void testTemplateStandard()
{
test("templateStandard", [](const Document& doc)
{
sofert(doc.size() == 5);
sofert(doc.has("template1") && doc.has("template2"));
const auto& templ1 = doc["template1"];
const auto& templ2 = doc["template2"];
sofert(templ1 == doc[0] && templ2 == doc[1]);
sofert(templ1 == templ2);
{
sofert(templ1.isList());
const auto& list = templ1.getList();
sofert(list.size() == 2);
sofert(list[0].isTuple());
sofert(list[1].isTuple());
{
const auto& tuple = list[0].getTuple();
sofert(tuple.size() == 3);
sofert(tuple[0].isString() && tuple[0].getString() == "First");
sofert(tuple[1].isString() && tuple[1].getString() == "Last");
sofert(tuple[2].isInt() && tuple[2].getInt() == 38);
sofert(tuple.has("firstName") && tuple.has("lastName") && tuple.has("age"));
sofert(tuple["firstName"].isString() && tuple["firstName"].getString() == "First");
sofert(tuple["lastName"].isString() && tuple["lastName"].getString() == "Last");
sofert(tuple["age"].isInt() && tuple["age"].getInt() == 38);
}
{
const auto& tuple = list[1].getTuple();
sofert(tuple.size() == 3);
sofert(tuple[0].isString() && tuple[0].getString() == "Second");
sofert(tuple[1].isString() && tuple[1].getString() == "Third");
sofert(tuple[2].isInt() && tuple[2].getInt() == 47);
sofert(tuple.has("firstName") && tuple.has("lastName") && tuple.has("age"));
sofert(tuple["firstName"].isString() && tuple["firstName"].getString() == "Second");
sofert(tuple["lastName"].isString() && tuple["lastName"].getString() == "Third");
sofert(tuple["age"].isInt() && tuple["age"].getInt() == 47);
}
}
Tuple tupleTempl3;
const auto& templ3 = doc[2];
{
sofert(templ3.isTuple());
const auto& tuple = templ3.getTuple();
sofert(tuple.size() == 2);
sofert(tuple[0].isString() && tuple[0].getString() == "default1");
sofert(tuple[1].isString() && tuple[1].getString() == "default2");
sofert(tuple.has("val1") && tuple.has("val2"));
sofert(tuple["val1"].isString() && tuple["val1"].getString() == "default1");
sofert(tuple["val2"].isString() && tuple["val2"].getString() == "default2");
tupleTempl3 = tuple;
}
const auto& templ4 = doc[3];
sofert(templ4.isList() && templ4.getList().empty());
const auto& templ5 = doc[4];
{
sofert(templ5.isList());
const auto& list = templ5.getList();
sofert(list.size() == 1);
sofert(list[0].isTuple());
sofert(tupleTempl3 == list[0].getTuple());
}
});
}
ErrorType testSerializerHtml()
{
string filename("test-serializer-html");
string filenameIn("files-serializer-html/" + filename + ".wbsn");
string filenameOut(filename + ".wbsnout"); //not html as not yet in .gitignore
cout << "Input: " << filename << endl;
Document doc;
ErrorType errorParse = tryParse(filenameIn, doc);
if (errorParse != ErrorType::NONE)
return errorParse;
cout << "No errors while parsing" << endl;
string output;
ErrorType errorSerialize = trySerialize<SerializerHtml>(filenameOut, output, doc);
if (errorSerialize != ErrorType::NONE)
return errorSerialize;
cout << "No errors while serializing" << endl;
return ErrorType::NONE;
}<|endoftext|> |
<commit_before>/*
* BatteryTech
* Copyright (c) 2010 Battery Powered Games LLC.
*
* This code is a component of BatteryTech and is subject to the 'BatteryTech
* End User License Agreement'. Among other important provisions, this
* license prohibits the distribution of source code to anyone other than
* authorized parties. If you have any questions or would like an additional
* copy of the license, please contact: [email protected]
*/
//============================================================================
// Name : androidgeneral.cpp
// Description : Android platform general functions
// Usage : See platformgeneral.h for usage
//============================================================================
#ifndef LINUXGENERAL_CPP_
#define LINUXGENERAL_CPP_
#if defined(linux)
#include "../platformgeneral.h"
#include "linuxgeneral.h"
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "../../primitives.h"
#include "../../audio/AudioManager.h"
#include <errno.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <string.h>
#include <iostream>
#include "LinuxAudioGW.h"
using namespace BatteryTech;
using namespace std;
LinuxAudioGW *audioGW;
void _convert_filename(char *filename);
void _platform_log(const char* message) {
cout << message << endl;
}
unsigned char* _platform_load_internal_asset(const char *filename, S32 *size) {
//char *myFilename;
//strcpy(myFilename, filename);
//_convert_filename(myFilename);
char myFilename[255];
strcpy(myFilename, "assets/");
strcat(myFilename, filename);
_platform_convert_path(myFilename, myFilename);
//cout << "trying " << myFilename << endl;
FILE *handle;
unsigned char *data = 0;
handle = fopen(myFilename, "rb");
if (!handle) {
cout << "File not found: " << myFilename << endl;
return 0;
}
fseek(handle, 0L, SEEK_END);
*size = ftell(handle);
//fseek(handle, 0L, SEEK_SET);
rewind(handle);
data = (unsigned char*) malloc(sizeof(unsigned char) * *size);
if (data) {
int bytesRead = fread(data, sizeof(unsigned char), *size, handle);
// cout << "malloc success, " << bytesRead << " bytes read of " << *size << endl;
}
int error = ferror(handle);
if (error) {
cout << "IO error " << error << endl;
}
if (feof(handle)) {
cout << "EOF reached " << endl;
}
fclose(handle);
return data;
}
void _platform_free_asset(unsigned char *ptr) {
if (ptr) {
free(ptr);
}
}
S32 _platform_get_asset_length(const char *filename) {
char myFilename[255];
strcpy(myFilename, "assets/");
strcat(myFilename, filename);
_platform_convert_path(myFilename, myFilename);
FILE *handle;
handle = fopen(myFilename, "rb");
S32 size = 0;
if (!handle) {
cout << "No file handle" << endl;
} else {
fseek(handle, 0L, SEEK_END);
size = ftell(handle);
fclose(handle);
}
return size;
}
S32 _platform_read_asset_chunk(const char *filename, S32 offset, unsigned char *buffer, S32 bufferLength, BOOL32 *eof) {
char myFilename[255];
strcpy(myFilename, "assets/");
strcat(myFilename, filename);
_platform_convert_path(myFilename, myFilename);
FILE *handle;
handle = fopen(myFilename, "rb");
if (!handle) {
cout << "No file handle" << endl;
return 0;
} else {
fseek(handle, offset, SEEK_SET);
int bytesRead = fread(buffer, sizeof(unsigned char), bufferLength, handle);
int error = ferror(handle);
if (error) {
cout << "IO error " << error << endl;
}
if (feof(handle)) {
*eof = TRUE;
//cout << "EOF reached " << endl;
} else {
*eof = FALSE;
}
fclose(handle);
return bytesRead;
}
}
void _convert_filename(char *filename) {
int arrayLength = strlen(filename);
int i;
for (i = 0; i < arrayLength; i++) {
if (filename[i] == '\\') {
filename[i] = '/';
}
}
}
void _platform_init_sound(AudioManager *audioManager) {
audioGW = new LinuxAudioGW(audioManager);
audioGW->init();
}
void _platform_stop_sound() {
audioGW->release();
delete audioGW;
audioGW = NULL;
}
void _platform_get_external_storage_dir_name(char* buf, S32 buflen) {
// TODO - user home .dir
getcwd(buf, buflen);
}
void _platform_get_application_storage_dir_name(char* buf, S32 buflen) {
// TODO - user home .dir
getcwd(buf, buflen);
}
const char* _platform_get_path_separator() {
return "/";
}
BOOL32 _platform_path_exists(const char* path) {
return (access(path, F_OK) != -1);
}
BOOL32 _platform_path_can_read(const char* path) {
return (access(path, R_OK) != -1);
}
BOOL32 _platform_path_can_write(const char* path) {
return (access(path, W_OK) != -1);
}
BOOL32 _platform_path_create(const char* path) {
return (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
}
void _platform_play_vibration_effect(S32 effectId, F32 intensity) {
//cout << "Playing vibration effect " << effectId << " at " << intensity << endl;
}
void _platform_start_vibration_effect(S32 effectId, F32 intensity) {
//cout << "Starting vibration effect " << effectId << " at " << intensity << endl;
}
void _platform_stop_vibration_effect(S32 effectId) {
//cout << "Stopping vibration effect " << effectId << endl;
}
void _platform_stop_all_vibration_effects() {
//cout << "Stopping all vibration effects" << endl;
}
BOOL32 _platform_implements_soundpool() {
return FALSE;
}
void _platform_init_audiomanagement(S32 streams){}
void _platform_release_audiomanagement(){}
void _platform_load_sound(const char* asset){}
S32 _platform_play_sound(const char* asset, F32 leftVol, F32 rightVol, S32 loops, F32 rate){ return -1; }
void _platform_stop_sound(S32 streamId){}
void _platform_stop_sound(const char* asset){}
void _platform_stop_all_sounds(){}
void _platform_unload_sound(const char *asset){}
void _platform_sound_set_loops(S32 streamId, S32 loops){}
void _platform_sound_set_volume(S32 streamId, F32 leftVol, F32 rightVol){}
void _platform_sound_set_rate(S32 streamId, F32 rate){}
S32 _platform_play_streaming_sound(const char *assetName, S16 loops, F32 leftVol, F32 rightVol, F32 rate){ return -1; }
void _platform_stop_streaming_sound(const char *assetName){}
void _platform_show_keyboard(){}
void _platform_hide_keyboard(){}
void _platform_exit() {
// quit = TRUE;
}
void _platform_show_ad() {
// Call out to your windows ad integration piece here
}
void _platform_hide_ad() {
// Call out to your windows ad integration piece here
}
void _platform_hook(const char *hook, char *result, S32 resultLen) {
// Handle custom hooks here
}
BOOL32 _platform_has_special_key(BatteryTech::SpecialKey sKey) {
return FALSE;
}
void _platform_init_network() {}
void _platform_release_network() {}
void _platform_make_non_blocking(SOCKET socket) {
fcntl(socket, F_SETFL, O_NONBLOCK);
}
S32 _platform_get_socket_last_error() {
return errno;
}
char** _platform_get_ifaddrs(int *count) {
_platform_log("Getting host names");
*count = 0;
char** hostnames = NULL;
struct ifreq *ifr;
struct ifconf ifc;
int s, i;
int numif;
// find number of interfaces.
memset(&ifc, 0, sizeof(ifc));
ifc.ifc_ifcu.ifcu_req = NULL;
ifc.ifc_len = 0;
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return hostnames;
}
if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
return hostnames;
}
if ((ifr = (struct ifreq*) malloc(ifc.ifc_len)) == NULL) {
return hostnames;
}
ifc.ifc_ifcu.ifcu_req = ifr;
if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
return hostnames;
}
close(s);
numif = ifc.ifc_len / sizeof(struct ifreq);
*count = numif;
hostnames = new char*[numif];
for (i = 0; i < numif; i++) {
struct ifreq *r = &ifr[i];
struct sockaddr_in *sin = (struct sockaddr_in *)&r->ifr_addr;
hostnames[i] = new char[80];
strcpy(hostnames[i], inet_ntoa(sin->sin_addr));
}
free(ifr);
return hostnames;
}
void _platform_free_ifaddrs(char** ifaddrs, int count) {
for (S32 i = 0; i < count; i++) {
delete ifaddrs[i];
}
delete [] ifaddrs;
}
// Returns a time in nanoseconds, suitable for high resolution timing and profiling
U64 _platform_get_time_nanos() {
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000LL + (uint64_t)ts.tv_nsec;
}
#endif /* linux */
#endif /* LINUXGENERAL_CPP_ */
<commit_msg>BT - Linux proper storage dir support<commit_after>/*
* BatteryTech
* Copyright (c) 2010 Battery Powered Games LLC.
*
* This code is a component of BatteryTech and is subject to the 'BatteryTech
* End User License Agreement'. Among other important provisions, this
* license prohibits the distribution of source code to anyone other than
* authorized parties. If you have any questions or would like an additional
* copy of the license, please contact: [email protected]
*/
//============================================================================
// Name : androidgeneral.cpp
// Description : Android platform general functions
// Usage : See platformgeneral.h for usage
//============================================================================
#ifndef LINUXGENERAL_CPP_
#define LINUXGENERAL_CPP_
#if defined(linux)
#include "linuxgeneral.h"
#include "../platformgeneral.h"
#include "../../primitives.h"
#include "../../batterytech.h"
#include "../../Context.h"
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "../../audio/AudioManager.h"
#include <errno.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <string.h>
#include <iostream>
#include "LinuxAudioGW.h"
#include <sys/types.h>
#include <pwd.h>
#include <string.h>
using namespace BatteryTech;
using namespace std;
LinuxAudioGW *audioGW;
void _convert_filename(char *filename);
void _platform_log(const char* message) {
cout << message << endl;
}
unsigned char* _platform_load_internal_asset(const char *filename, S32 *size) {
//char *myFilename;
//strcpy(myFilename, filename);
//_convert_filename(myFilename);
char myFilename[255];
strcpy(myFilename, "assets/");
strcat(myFilename, filename);
_platform_convert_path(myFilename, myFilename);
//cout << "trying " << myFilename << endl;
FILE *handle;
unsigned char *data = 0;
handle = fopen(myFilename, "rb");
if (!handle) {
cout << "File not found: " << myFilename << endl;
return 0;
}
fseek(handle, 0L, SEEK_END);
*size = ftell(handle);
//fseek(handle, 0L, SEEK_SET);
rewind(handle);
data = (unsigned char*) malloc(sizeof(unsigned char) * *size);
if (data) {
int bytesRead = fread(data, sizeof(unsigned char), *size, handle);
// cout << "malloc success, " << bytesRead << " bytes read of " << *size << endl;
}
int error = ferror(handle);
if (error) {
cout << "IO error " << error << endl;
}
if (feof(handle)) {
cout << "EOF reached " << endl;
}
fclose(handle);
return data;
}
void _platform_free_asset(unsigned char *ptr) {
if (ptr) {
free(ptr);
}
}
S32 _platform_get_asset_length(const char *filename) {
char myFilename[255];
strcpy(myFilename, "assets/");
strcat(myFilename, filename);
_platform_convert_path(myFilename, myFilename);
FILE *handle;
handle = fopen(myFilename, "rb");
S32 size = 0;
if (!handle) {
cout << "No file handle" << endl;
} else {
fseek(handle, 0L, SEEK_END);
size = ftell(handle);
fclose(handle);
}
return size;
}
S32 _platform_read_asset_chunk(const char *filename, S32 offset, unsigned char *buffer, S32 bufferLength, BOOL32 *eof) {
char myFilename[255];
strcpy(myFilename, "assets/");
strcat(myFilename, filename);
_platform_convert_path(myFilename, myFilename);
FILE *handle;
handle = fopen(myFilename, "rb");
if (!handle) {
cout << "No file handle" << endl;
return 0;
} else {
fseek(handle, offset, SEEK_SET);
int bytesRead = fread(buffer, sizeof(unsigned char), bufferLength, handle);
int error = ferror(handle);
if (error) {
cout << "IO error " << error << endl;
}
if (feof(handle)) {
*eof = TRUE;
//cout << "EOF reached " << endl;
} else {
*eof = FALSE;
}
fclose(handle);
return bytesRead;
}
}
void _convert_filename(char *filename) {
int arrayLength = strlen(filename);
int i;
for (i = 0; i < arrayLength; i++) {
if (filename[i] == '\\') {
filename[i] = '/';
}
}
}
void _platform_init_sound(AudioManager *audioManager) {
audioGW = new LinuxAudioGW(audioManager);
audioGW->init();
}
void _platform_stop_sound() {
audioGW->release();
delete audioGW;
audioGW = NULL;
}
void _platform_get_external_storage_dir_name(char* buf, S32 buflen) {
// home/.dir/storage
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
const char *storageDir = btGetContext()->appProperties->get("storage_dir")->getValue();
char tmp[1024];
strcpy(tmp, storageDir);
char *loc = strchr(tmp, ' ');
while (loc) {
*loc = '_';
loc = strchr(loc, ' ');
}
snprintf(buf, buflen, "%s/.%s/storage", homedir, tmp);
}
void _platform_get_application_storage_dir_name(char* buf, S32 buflen) {
// home/.dir/data
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
const char *storageDir = btGetContext()->appProperties->get("storage_dir")->getValue();
char tmp[1024];
strcpy(tmp, storageDir);
char *loc = strchr(tmp, ' ');
while (loc) {
*loc = '_';
loc = strchr(loc, ' ');
}
snprintf(buf, buflen, "%s/.%s/data", homedir, tmp);
}
const char* _platform_get_path_separator() {
return "/";
}
BOOL32 _platform_path_exists(const char* path) {
return (access(path, F_OK) != -1);
}
BOOL32 _platform_path_can_read(const char* path) {
return (access(path, R_OK) != -1);
}
BOOL32 _platform_path_can_write(const char* path) {
return (access(path, W_OK) != -1);
}
BOOL32 _platform_path_create(const char* path) {
return (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
}
void _platform_play_vibration_effect(S32 effectId, F32 intensity) {
//cout << "Playing vibration effect " << effectId << " at " << intensity << endl;
}
void _platform_start_vibration_effect(S32 effectId, F32 intensity) {
//cout << "Starting vibration effect " << effectId << " at " << intensity << endl;
}
void _platform_stop_vibration_effect(S32 effectId) {
//cout << "Stopping vibration effect " << effectId << endl;
}
void _platform_stop_all_vibration_effects() {
//cout << "Stopping all vibration effects" << endl;
}
BOOL32 _platform_implements_soundpool() {
return FALSE;
}
void _platform_init_audiomanagement(S32 streams){}
void _platform_release_audiomanagement(){}
void _platform_load_sound(const char* asset){}
S32 _platform_play_sound(const char* asset, F32 leftVol, F32 rightVol, S32 loops, F32 rate){ return -1; }
void _platform_stop_sound(S32 streamId){}
void _platform_stop_sound(const char* asset){}
void _platform_stop_all_sounds(){}
void _platform_unload_sound(const char *asset){}
void _platform_sound_set_loops(S32 streamId, S32 loops){}
void _platform_sound_set_volume(S32 streamId, F32 leftVol, F32 rightVol){}
void _platform_sound_set_rate(S32 streamId, F32 rate){}
S32 _platform_play_streaming_sound(const char *assetName, S16 loops, F32 leftVol, F32 rightVol, F32 rate){ return -1; }
void _platform_stop_streaming_sound(const char *assetName){}
void _platform_show_keyboard(){}
void _platform_hide_keyboard(){}
void _platform_exit() {
// quit = TRUE;
}
void _platform_show_ad() {
// Call out to your windows ad integration piece here
}
void _platform_hide_ad() {
// Call out to your windows ad integration piece here
}
void _platform_hook(const char *hook, char *result, S32 resultLen) {
// Handle custom hooks here
}
BOOL32 _platform_has_special_key(BatteryTech::SpecialKey sKey) {
return FALSE;
}
void _platform_init_network() {}
void _platform_release_network() {}
void _platform_make_non_blocking(SOCKET socket) {
fcntl(socket, F_SETFL, O_NONBLOCK);
}
S32 _platform_get_socket_last_error() {
return errno;
}
char** _platform_get_ifaddrs(int *count) {
_platform_log("Getting host names");
*count = 0;
char** hostnames = NULL;
struct ifreq *ifr;
struct ifconf ifc;
int s, i;
int numif;
// find number of interfaces.
memset(&ifc, 0, sizeof(ifc));
ifc.ifc_ifcu.ifcu_req = NULL;
ifc.ifc_len = 0;
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return hostnames;
}
if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
return hostnames;
}
if ((ifr = (struct ifreq*) malloc(ifc.ifc_len)) == NULL) {
return hostnames;
}
ifc.ifc_ifcu.ifcu_req = ifr;
if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
return hostnames;
}
close(s);
numif = ifc.ifc_len / sizeof(struct ifreq);
*count = numif;
hostnames = new char*[numif];
for (i = 0; i < numif; i++) {
struct ifreq *r = &ifr[i];
struct sockaddr_in *sin = (struct sockaddr_in *)&r->ifr_addr;
hostnames[i] = new char[80];
strcpy(hostnames[i], inet_ntoa(sin->sin_addr));
}
free(ifr);
return hostnames;
}
void _platform_free_ifaddrs(char** ifaddrs, int count) {
for (S32 i = 0; i < count; i++) {
delete ifaddrs[i];
}
delete [] ifaddrs;
}
// Returns a time in nanoseconds, suitable for high resolution timing and profiling
U64 _platform_get_time_nanos() {
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000LL + (uint64_t)ts.tv_nsec;
}
#endif /* linux */
#endif /* LINUXGENERAL_CPP_ */
<|endoftext|> |
<commit_before>/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
#include <cstring>
#include <iostream>
#include "base64.hpp"
static const char * const base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
inline int strfnd(const char *str, char ch)
{
return static_cast<int>(strchr(str, ch) - str);
}
inline int strfnd(const char *str, char ch)
{
return static_cast<int>(strchr(str, ch) - str);
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = static_cast<int>(encoded_string.size());
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++) {
char_array_4[i] = strfnd(base64_chars, char_array_4[i]);
}
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = strfnd(base64_chars, char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
<commit_msg>bugfix<commit_after>/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
#include <cstring>
#include <iostream>
#include "base64.hpp"
static const char * const base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
inline int strfnd(const char *str, char ch)
{
return static_cast<int>(strchr(str, ch) - str);
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = static_cast<int>(encoded_string.size());
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++) {
char_array_4[i] = strfnd(base64_chars, char_array_4[i]);
}
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = strfnd(base64_chars, char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
<|endoftext|> |
<commit_before>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */
/* $Id$ */
/* Version: $Name$ */
/* */
/* Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 by the deal.II authors */
/* */
/* This file is subject to QPL and may not be distributed */
/* without copyright and license information. Please refer */
/* to the file deal.II/doc/license.html for the text and */
/* further information on this license. */
// @sect3{Include files}
// The first few files have already
// been covered in previous examples
// and will thus not be further
// commented on.
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <base/utilities.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/hp_dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>
#include <fstream>
#include <iostream>
#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <dofs/dof_constraints.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>
// Finally, this is as in previous
// programs:
using namespace dealii;
template <int dim>
class LaplaceProblem
{
public:
LaplaceProblem ();
~LaplaceProblem ();
void run ();
private:
void setup_system ();
void assemble_system ();
void solve ();
void refine_grid ();
void output_results (const unsigned int cycle) const;
Triangulation<dim> triangulation;
DoFHandler<dim> dof_handler;
FE_Q<dim> fe;
ConstraintMatrix hanging_node_constraints;
SparsityPattern sparsity_pattern;
SparseMatrix<double> system_matrix;
Vector<double> solution;
Vector<double> system_rhs;
};
template <int dim>
LaplaceProblem<dim>::LaplaceProblem () :
dof_handler (triangulation),
fe (2)
{}
template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
dof_handler.clear ();
}
template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
dof_handler.distribute_dofs (fe);
sparsity_pattern.reinit (dof_handler.n_dofs(),
dof_handler.n_dofs(),
dof_handler.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);
solution.reinit (dof_handler.n_dofs());
system_rhs.reinit (dof_handler.n_dofs());
hanging_node_constraints.clear ();
DoFTools::make_hanging_node_constraints (dof_handler,
hanging_node_constraints);
hanging_node_constraints.close ();
hanging_node_constraints.condense (sparsity_pattern);
sparsity_pattern.compress();
system_matrix.reinit (sparsity_pattern);
}
template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
const QGauss<dim> quadrature_formula(3);
FEValues<dim> fe_values (fe, quadrature_formula,
update_values | update_gradients |
update_q_points | update_JxW_values);
const unsigned int dofs_per_cell = fe.dofs_per_cell;
const unsigned int n_q_points = quadrature_formula.n_quadrature_points;
FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);
Vector<double> cell_rhs (dofs_per_cell);
std::vector<unsigned int> local_dof_indices (dofs_per_cell);
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (; cell!=endc; ++cell)
{
cell_matrix = 0;
cell_rhs = 0;
fe_values.reinit (cell);
for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
for (unsigned int j=0; j<dofs_per_cell; ++j)
cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *
fe_values.shape_grad(j,q_point) *
fe_values.JxW(q_point));
cell_rhs(i) += (fe_values.shape_value(i,q_point) *
1.0 *
fe_values.JxW(q_point));
}
cell->get_dof_indices (local_dof_indices);
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
for (unsigned int j=0; j<dofs_per_cell; ++j)
system_matrix.add (local_dof_indices[i],
local_dof_indices[j],
cell_matrix(i,j));
system_rhs(local_dof_indices[i]) += cell_rhs(i);
}
}
hanging_node_constraints.condense (system_matrix);
hanging_node_constraints.condense (system_rhs);
std::map<unsigned int,double> boundary_values;
VectorTools::interpolate_boundary_values (dof_handler,
0,
ZeroFunction<dim>(),
boundary_values);
MatrixTools::apply_boundary_values (boundary_values,
system_matrix,
solution,
system_rhs);
}
template <int dim>
void LaplaceProblem<dim>::solve ()
{
SolverControl solver_control (1000, 1e-12);
SolverCG<> cg (solver_control);
PreconditionSSOR<> preconditioner;
preconditioner.initialize(system_matrix, 1.2);
cg.solve (system_matrix, solution, system_rhs,
preconditioner);
hanging_node_constraints.distribute (solution);
}
template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
Vector<float> estimated_error_per_cell (triangulation.n_active_cells());
KellyErrorEstimator<dim>::estimate (dof_handler,
QGauss<dim-1>(3),
typename FunctionMap<dim>::type(),
solution,
estimated_error_per_cell);
GridRefinement::refine_and_coarsen_fixed_number (triangulation,
estimated_error_per_cell,
0.3, 0.03);
triangulation.execute_coarsening_and_refinement ();
}
template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
Assert (cycle < 10, ExcNotImplemented());
{
const std::string filename = "grid-" +
Utilities::int_to_string (cycle, 2) +
".eps";
std::ofstream output (filename.c_str());
GridOut grid_out;
grid_out.write_eps (triangulation, output);
}
{
const std::string filename = "solution-" +
Utilities::int_to_string (cycle, 2) +
".gnuplot";
DataOut<dim> data_out;
data_out.attach_dof_handler (dof_handler);
data_out.add_data_vector (solution, "solution");
data_out.build_patches ();
std::ofstream output (filename.c_str());
data_out.write_gnuplot (output);
}
}
void
create_coarse_grid (Triangulation<2> &coarse_grid)
{
const unsigned int dim = 2;
static const Point<2> vertices_1[]
= { Point<2> (-1., -1.),
Point<2> (-1./2, -1.),
Point<2> (0., -1.),
Point<2> (+1./2, -1.),
Point<2> (+1, -1.),
Point<2> (-1., -1./2.),
Point<2> (-1./2, -1./2.),
Point<2> (0., -1./2.),
Point<2> (+1./2, -1./2.),
Point<2> (+1, -1./2.),
Point<2> (-1., 0.),
Point<2> (-1./2, 0.),
Point<2> (+1./2, 0.),
Point<2> (+1, 0.),
Point<2> (-1., 1./2.),
Point<2> (-1./2, 1./2.),
Point<2> (0., 1./2.),
Point<2> (+1./2, 1./2.),
Point<2> (+1, 1./2.),
Point<2> (-1., 1.),
Point<2> (-1./2, 1.),
Point<2> (0., 1.),
Point<2> (+1./2, 1.),
Point<2> (+1, 1.) };
const unsigned int
n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);
const std::vector<Point<dim> > vertices (&vertices_1[0],
&vertices_1[n_vertices]);
static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]
= {{0, 1, 5, 6},
{1, 2, 6, 7},
{2, 3, 7, 8},
{3, 4, 8, 9},
{5, 6, 10, 11},
{8, 9, 12, 13},
{10, 11, 14, 15},
{12, 13, 17, 18},
{14, 15, 19, 20},
{15, 16, 20, 21},
{16, 17, 21, 22},
{17, 18, 22, 23}};
const unsigned int
n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);
std::vector<CellData<dim> > cells (n_cells, CellData<dim>());
for (unsigned int i=0; i<n_cells; ++i)
{
for (unsigned int j=0;
j<GeometryInfo<dim>::vertices_per_cell;
++j)
cells[i].vertices[j] = cell_vertices[i][j];
cells[i].material_id = 0;
}
coarse_grid.create_triangulation (vertices,
cells,
SubCellData());
coarse_grid.refine_global (1);
}
template <int dim>
void LaplaceProblem<dim>::run ()
{
for (unsigned int cycle=0; cycle<5; ++cycle)
{
std::cout << "Cycle " << cycle << ':' << std::endl;
if (cycle == 0)
create_coarse_grid (triangulation);
else
refine_grid ();
std::cout << " Number of active cells: "
<< triangulation.n_active_cells()
<< std::endl;
setup_system ();
std::cout << " Number of degrees of freedom: "
<< dof_handler.n_dofs()
<< std::endl;
assemble_system ();
solve ();
output_results (cycle);
}
}
int main ()
{
try
{
deallog.depth_console (0);
LaplaceProblem<2> laplace_problem_2d;
laplace_problem_2d.run ();
}
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
<commit_msg>hp-ify the code.<commit_after>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */
/* $Id$ */
/* Version: $Name$ */
/* */
/* Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 by the deal.II authors */
/* */
/* This file is subject to QPL and may not be distributed */
/* without copyright and license information. Please refer */
/* to the file deal.II/doc/license.html for the text and */
/* further information on this license. */
// @sect3{Include files}
// The first few files have already
// been covered in previous examples
// and will thus not be further
// commented on.
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <base/utilities.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/hp_dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/hp_fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>
#include <fstream>
#include <iostream>
#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <dofs/dof_constraints.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>
// Finally, this is as in previous
// programs:
using namespace dealii;
template <int dim>
class LaplaceProblem
{
public:
LaplaceProblem ();
~LaplaceProblem ();
void run ();
private:
void setup_system ();
void assemble_system ();
void solve ();
void refine_grid ();
void output_results (const unsigned int cycle) const;
Triangulation<dim> triangulation;
hp::DoFHandler<dim> dof_handler;
hp::FECollection<dim> fe_collection;
hp::QCollection<dim> quadrature_collection;
ConstraintMatrix hanging_node_constraints;
SparsityPattern sparsity_pattern;
SparseMatrix<double> system_matrix;
Vector<double> solution;
Vector<double> system_rhs;
};
template <int dim>
LaplaceProblem<dim>::LaplaceProblem () :
dof_handler (triangulation)
{
for (unsigned int degree=1; degree<5; ++degree)
{
fe_collection.push_back (FE_Q<dim>(degree));
quadrature_collection.push_back (QGauss<dim>(degree+2));
}
}
template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
dof_handler.clear ();
}
template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
dof_handler.distribute_dofs (fe_collection);
sparsity_pattern.reinit (dof_handler.n_dofs(),
dof_handler.n_dofs(),
dof_handler.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);
solution.reinit (dof_handler.n_dofs());
system_rhs.reinit (dof_handler.n_dofs());
hanging_node_constraints.clear ();
DoFTools::make_hanging_node_constraints (dof_handler,
hanging_node_constraints);
hanging_node_constraints.close ();
hanging_node_constraints.condense (sparsity_pattern);
sparsity_pattern.compress();
system_matrix.reinit (sparsity_pattern);
}
template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
hp::FEValues<dim> hp_fe_values (fe_collection,
quadrature_collection,
update_values | update_gradients |
update_q_points | update_JxW_values);
typename hp::DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (; cell!=endc; ++cell)
{
const unsigned int dofs_per_cell = cell->get_fe().dofs_per_cell;
FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);
Vector<double> cell_rhs (dofs_per_cell);
std::vector<unsigned int> local_dof_indices (dofs_per_cell);
cell_matrix = 0;
cell_rhs = 0;
hp_fe_values.reinit (cell);
const FEValues<dim> &fe_values = hp_fe_values.get_present_fe_values ();
for (unsigned int q_point=0; q_point<fe_values.n_quadrature_points; ++q_point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
for (unsigned int j=0; j<dofs_per_cell; ++j)
cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *
fe_values.shape_grad(j,q_point) *
fe_values.JxW(q_point));
cell_rhs(i) += (fe_values.shape_value(i,q_point) *
1.0 *
fe_values.JxW(q_point));
}
cell->get_dof_indices (local_dof_indices);
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
for (unsigned int j=0; j<dofs_per_cell; ++j)
system_matrix.add (local_dof_indices[i],
local_dof_indices[j],
cell_matrix(i,j));
system_rhs(local_dof_indices[i]) += cell_rhs(i);
}
}
hanging_node_constraints.condense (system_matrix);
hanging_node_constraints.condense (system_rhs);
std::map<unsigned int,double> boundary_values;
VectorTools::interpolate_boundary_values (dof_handler,
0,
ZeroFunction<dim>(),
boundary_values);
MatrixTools::apply_boundary_values (boundary_values,
system_matrix,
solution,
system_rhs);
}
template <int dim>
void LaplaceProblem<dim>::solve ()
{
SolverControl solver_control (1000, 1e-12);
SolverCG<> cg (solver_control);
PreconditionSSOR<> preconditioner;
preconditioner.initialize(system_matrix, 1.2);
cg.solve (system_matrix, solution, system_rhs,
preconditioner);
hanging_node_constraints.distribute (solution);
}
template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
Vector<float> estimated_error_per_cell (triangulation.n_active_cells());
KellyErrorEstimator<dim>::estimate (dof_handler,
QGauss<dim-1>(3),
typename FunctionMap<dim>::type(),
solution,
estimated_error_per_cell);
GridRefinement::refine_and_coarsen_fixed_number (triangulation,
estimated_error_per_cell,
0.3, 0.03);
triangulation.execute_coarsening_and_refinement ();
}
template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
Assert (cycle < 10, ExcNotImplemented());
{
const std::string filename = "grid-" +
Utilities::int_to_string (cycle, 2) +
".eps";
std::ofstream output (filename.c_str());
GridOut grid_out;
grid_out.write_eps (triangulation, output);
}
{
const std::string filename = "solution-" +
Utilities::int_to_string (cycle, 2) +
".gnuplot";
DataOut<dim,hp::DoFHandler<dim> > data_out;
data_out.attach_dof_handler (dof_handler);
data_out.add_data_vector (solution, "solution");
data_out.build_patches ();
std::ofstream output (filename.c_str());
data_out.write_gnuplot (output);
}
}
void
create_coarse_grid (Triangulation<2> &coarse_grid)
{
const unsigned int dim = 2;
static const Point<2> vertices_1[]
= { Point<2> (-1., -1.),
Point<2> (-1./2, -1.),
Point<2> (0., -1.),
Point<2> (+1./2, -1.),
Point<2> (+1, -1.),
Point<2> (-1., -1./2.),
Point<2> (-1./2, -1./2.),
Point<2> (0., -1./2.),
Point<2> (+1./2, -1./2.),
Point<2> (+1, -1./2.),
Point<2> (-1., 0.),
Point<2> (-1./2, 0.),
Point<2> (+1./2, 0.),
Point<2> (+1, 0.),
Point<2> (-1., 1./2.),
Point<2> (-1./2, 1./2.),
Point<2> (0., 1./2.),
Point<2> (+1./2, 1./2.),
Point<2> (+1, 1./2.),
Point<2> (-1., 1.),
Point<2> (-1./2, 1.),
Point<2> (0., 1.),
Point<2> (+1./2, 1.),
Point<2> (+1, 1.) };
const unsigned int
n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);
const std::vector<Point<dim> > vertices (&vertices_1[0],
&vertices_1[n_vertices]);
static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]
= {{0, 1, 5, 6},
{1, 2, 6, 7},
{2, 3, 7, 8},
{3, 4, 8, 9},
{5, 6, 10, 11},
{8, 9, 12, 13},
{10, 11, 14, 15},
{12, 13, 17, 18},
{14, 15, 19, 20},
{15, 16, 20, 21},
{16, 17, 21, 22},
{17, 18, 22, 23}};
const unsigned int
n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);
std::vector<CellData<dim> > cells (n_cells, CellData<dim>());
for (unsigned int i=0; i<n_cells; ++i)
{
for (unsigned int j=0;
j<GeometryInfo<dim>::vertices_per_cell;
++j)
cells[i].vertices[j] = cell_vertices[i][j];
cells[i].material_id = 0;
}
coarse_grid.create_triangulation (vertices,
cells,
SubCellData());
coarse_grid.refine_global (1);
}
template <int dim>
void LaplaceProblem<dim>::run ()
{
for (unsigned int cycle=0; cycle<5; ++cycle)
{
std::cout << "Cycle " << cycle << ':' << std::endl;
if (cycle == 0)
create_coarse_grid (triangulation);
else
refine_grid ();
std::cout << " Number of active cells: "
<< triangulation.n_active_cells()
<< std::endl;
setup_system ();
std::cout << " Number of degrees of freedom: "
<< dof_handler.n_dofs()
<< std::endl;
assemble_system ();
solve ();
output_results (cycle);
}
}
int main ()
{
try
{
deallog.depth_console (0);
LaplaceProblem<2> laplace_problem_2d;
laplace_problem_2d.run ();
}
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. 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 AUTHOR ``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 AUTHOR 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 "kml/base/time_util.h"
#include <cstddef> // NULL
#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
#include <time.h>
#else
#include <sys/time.h>
#endif
namespace kmlbase {
#ifdef WIN32
// http://forums.msdn.microsoft.com/en/vcgeneral/thread/430449b3-f6dd-4e18-84de-eebd26a8d668/
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
//
void gettimeofday(struct timeval* tv, void *) {
FILETIME file_time;
GetSystemTimeAsFileTime(&file_time);
// First covert file_time to a single 64 bit value.
unsigned __int64 file_time64 = 0;
file_time64 |= file_time.dwHighDateTime;
file_time64 <<= 32;
file_time64 |= file_time.dwLowDateTime;
/* Now convert file_time64 to unix time. */
file_time64 /= 10; /* Convert into microseconds. */
file_time64 -= DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (long)(file_time64 / 1000000UL);
tv->tv_usec = (long)(file_time64 % 1000000UL);
}
#endif
// This is here because Windows has no gettimeofday().
double GetMicroTime() {
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
// Make this one double with secs.microseconds.
return (double)now_tv.tv_sec + (double)now_tv.tv_usec/1000000;
}
} // end namespace kmlbase
<commit_msg>BUG: KML bug correction on Windows platform (redefinition of fd_set, etc... structures). Replace #include <winsock2.h> by #include <winsock.h> Bug reported on libkml google.<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. 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 AUTHOR ``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 AUTHOR 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 "kml/base/time_util.h"
#include <cstddef> // NULL
#ifdef WIN32
#include <windows.h>
// OTB Modifications (bug reported on libkml google issues
//#include <winsock2.h>
#include <winsock.h>
#include <time.h>
#else
#include <sys/time.h>
#endif
namespace kmlbase {
#ifdef WIN32
// http://forums.msdn.microsoft.com/en/vcgeneral/thread/430449b3-f6dd-4e18-84de-eebd26a8d668/
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
//
void gettimeofday(struct timeval* tv, void *) {
FILETIME file_time;
GetSystemTimeAsFileTime(&file_time);
// First covert file_time to a single 64 bit value.
unsigned __int64 file_time64 = 0;
file_time64 |= file_time.dwHighDateTime;
file_time64 <<= 32;
file_time64 |= file_time.dwLowDateTime;
/* Now convert file_time64 to unix time. */
file_time64 /= 10; /* Convert into microseconds. */
file_time64 -= DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (long)(file_time64 / 1000000UL);
tv->tv_usec = (long)(file_time64 % 1000000UL);
}
#endif
// This is here because Windows has no gettimeofday().
double GetMicroTime() {
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
// Make this one double with secs.microseconds.
return (double)now_tv.tv_sec + (double)now_tv.tv_usec/1000000;
}
} // end namespace kmlbase
<|endoftext|> |
<commit_before>//===-- MachineInstr.cpp --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Methods common to all machine instructions.
//
// FIXME: Now that MachineInstrs have parent pointers, they should always
// print themselves using their MachineFunction's TargetMachine.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Value.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>
using namespace llvm;
// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class TargetInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
namespace llvm {
extern const TargetInstrDescriptor *TargetInstrDescriptors;
}
// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(short opcode, unsigned numOperands)
: Opcode(opcode),
operands(numOperands, MachineOperand()),
parent(0) {
// Make sure that we get added to a machine basicblock
LeakDetector::addGarbageObject(this);
}
/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them. It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
: Opcode(opcode), parent(0) {
operands.reserve(numOperands);
// Make sure that we get added to a machine basicblock
LeakDetector::addGarbageObject(this);
}
/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
unsigned numOperands)
: Opcode(opcode), parent(0) {
assert(MBB && "Cannot use inserting ctor with null basic block!");
operands.reserve(numOperands);
// Make sure that we get added to a machine basicblock
LeakDetector::addGarbageObject(this);
MBB->push_back(this); // Add instruction to end of basic block!
}
/// MachineInstr ctor - Copies MachineInstr arg exactly
///
MachineInstr::MachineInstr(const MachineInstr &MI) {
Opcode = MI.getOpcode();
operands.reserve(MI.getNumOperands());
// Add operands
for (unsigned i = 0; i < MI.getNumOperands(); ++i)
operands.push_back(MachineOperand(MI.getOperand(i)));
// Set parent, next, and prev to null
parent = 0;
prev = 0;
next = 0;
}
MachineInstr::~MachineInstr() {
LeakDetector::removeGarbageObject(this);
}
/// clone - Create a copy of 'this' instruction that is identical in all ways
/// except the following: the new instruction has no parent and it has no name
///
MachineInstr* MachineInstr::clone() const {
return new MachineInstr(*this);
}
/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, and returns it, but does not delete it.
MachineInstr *MachineInstr::removeFromParent() {
assert(getParent() && "Not embedded in a basic block!");
getParent()->remove(this);
return this;
}
/// OperandComplete - Return true if it's illegal to add a new operand
///
bool MachineInstr::OperandsComplete() const {
int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
return true; // Broken: we have all the operands of this instruction!
return false;
}
void MachineInstr::SetMachineOperandVal(unsigned i,
MachineOperand::MachineOperandType opTy,
Value* V) {
assert(i < operands.size()); // may be explicit or implicit op
operands[i].opType = opTy;
operands[i].contents.value = V;
operands[i].extra.regNum = -1;
}
void
MachineInstr::SetMachineOperandConst(unsigned i,
MachineOperand::MachineOperandType opTy,
int intValue) {
assert(i < getNumOperands()); // must be explicit op
assert(TargetInstrDescriptors[Opcode].resultPos != (int) i &&
"immed. constant cannot be defined");
operands[i].opType = opTy;
operands[i].contents.value = NULL;
operands[i].contents.immedVal = intValue;
operands[i].extra.regNum = -1;
operands[i].flags = 0;
}
void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) {
assert(i < getNumOperands()); // must be explicit op
operands[i].opType = MachineOperand::MO_MachineRegister;
operands[i].contents.value = NULL;
operands[i].extra.regNum = regNum;
}
void MachineInstr::dump() const {
std::cerr << " " << *this;
}
static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
os << "(val ";
os << (void*) val; // print address always
if (val && val->hasName())
os << " " << val->getName(); // print name also, if available
os << ")";
return os;
}
static inline void OutputReg(std::ostream &os, unsigned RegNo,
const MRegisterInfo *MRI = 0) {
if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
if (MRI)
os << "%" << MRI->get(RegNo).Name;
else
os << "%mreg(" << RegNo << ")";
} else
os << "%reg" << RegNo;
}
static void print(const MachineOperand &MO, std::ostream &OS,
const TargetMachine *TM) {
const MRegisterInfo *MRI = 0;
if (TM) MRI = TM->getRegisterInfo();
bool CloseParen = true;
if (MO.isHiBits32())
OS << "%lm(";
else if (MO.isLoBits32())
OS << "%lo(";
else if (MO.isHiBits64())
OS << "%hh(";
else if (MO.isLoBits64())
OS << "%hm(";
else
CloseParen = false;
switch (MO.getType()) {
case MachineOperand::MO_VirtualRegister:
if (MO.getVRegValue()) {
OS << "%reg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg())
OS << "==";
}
if (MO.hasAllocatedReg())
OutputReg(OS, MO.getReg(), MRI);
break;
case MachineOperand::MO_CCRegister:
OS << "%ccreg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg()) {
OS << "==";
OutputReg(OS, MO.getReg(), MRI);
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(OS, MO.getMachineRegNum(), MRI);
break;
case MachineOperand::MO_SignExtendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp: {
const Value* opVal = MO.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
OS << opVal->getName();
else
OS << (const void*) opVal;
OS << ")";
break;
}
case MachineOperand::MO_MachineBasicBlock:
OS << "mbb<"
<< ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
<< "," << (void*)MO.getMachineBasicBlock() << ">";
break;
case MachineOperand::MO_FrameIndex:
OS << "<fi#" << MO.getFrameIndex() << ">";
break;
case MachineOperand::MO_ConstantPoolIndex:
OS << "<cp#" << MO.getConstantPoolIndex() << ">";
break;
case MachineOperand::MO_GlobalAddress:
OS << "<ga:" << ((Value*)MO.getGlobal())->getName();
if (MO.getOffset()) OS << "+" << MO.getOffset();
OS << ">";
break;
case MachineOperand::MO_ExternalSymbol:
OS << "<es:" << MO.getSymbolName();
if (MO.getOffset()) OS << "+" << MO.getOffset();
OS << ">";
break;
default:
assert(0 && "Unrecognized operand type");
}
if (CloseParen)
OS << ")";
}
void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
unsigned StartOp = 0;
// Specialize printing if op#0 is definition
if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
::print(getOperand(0), OS, TM);
OS << " = ";
++StartOp; // Don't print this operand again!
}
// Must check if Target machine is not null because machine BB could not
// be attached to a Machine function yet
if (TM)
OS << TM->getInstrInfo()->getName(getOpcode());
for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
const MachineOperand& mop = getOperand(i);
if (i != StartOp)
OS << ",";
OS << " ";
::print(mop, OS, TM);
if (mop.isDef())
if (mop.isUse())
OS << "<def&use>";
else
OS << "<def>";
}
OS << "\n";
}
namespace llvm {
std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
// If the instruction is embedded into a basic block, we can find the target
// info for the instruction.
if (const MachineBasicBlock *MBB = MI.getParent()) {
const MachineFunction *MF = MBB->getParent();
if (MF)
MI.print(os, &MF->getTarget());
else
MI.print(os, 0);
return os;
}
// Otherwise, print it out in the "raw" format without symbolic register names
// and such.
os << TargetInstrDescriptors[MI.getOpcode()].Name;
for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
os << "\t" << MI.getOperand(i);
if (MI.getOperand(i).isDef())
if (MI.getOperand(i).isUse())
os << "<d&u>";
else
os << "<d>";
}
return os << "\n";
}
std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
if (MO.isHiBits32())
OS << "%lm(";
else if (MO.isLoBits32())
OS << "%lo(";
else if (MO.isHiBits64())
OS << "%hh(";
else if (MO.isLoBits64())
OS << "%hm(";
switch (MO.getType()) {
case MachineOperand::MO_VirtualRegister:
if (MO.hasAllocatedReg())
OutputReg(OS, MO.getReg());
if (MO.getVRegValue()) {
if (MO.hasAllocatedReg()) OS << "==";
OS << "%vreg";
OutputValue(OS, MO.getVRegValue());
}
break;
case MachineOperand::MO_CCRegister:
OS << "%ccreg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg()) {
OS << "==";
OutputReg(OS, MO.getReg());
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(OS, MO.getMachineRegNum());
break;
case MachineOperand::MO_SignExtendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp: {
const Value* opVal = MO.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
OS << opVal->getName();
else
OS << (const void*) opVal;
OS << ")";
break;
}
case MachineOperand::MO_MachineBasicBlock:
OS << "<mbb:"
<< ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
<< "@" << (void*)MO.getMachineBasicBlock() << ">";
break;
case MachineOperand::MO_FrameIndex:
OS << "<fi#" << MO.getFrameIndex() << ">";
break;
case MachineOperand::MO_ConstantPoolIndex:
OS << "<cp#" << MO.getConstantPoolIndex() << ">";
break;
case MachineOperand::MO_GlobalAddress:
OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
break;
case MachineOperand::MO_ExternalSymbol:
OS << "<es:" << MO.getSymbolName() << ">";
break;
default:
assert(0 && "Unrecognized operand type");
break;
}
if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
OS << ")";
return OS;
}
}
<commit_msg>This field no longer exists<commit_after>//===-- MachineInstr.cpp --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Methods common to all machine instructions.
//
// FIXME: Now that MachineInstrs have parent pointers, they should always
// print themselves using their MachineFunction's TargetMachine.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Value.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>
using namespace llvm;
// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class TargetInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
namespace llvm {
extern const TargetInstrDescriptor *TargetInstrDescriptors;
}
// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(short opcode, unsigned numOperands)
: Opcode(opcode),
operands(numOperands, MachineOperand()),
parent(0) {
// Make sure that we get added to a machine basicblock
LeakDetector::addGarbageObject(this);
}
/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them. It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
: Opcode(opcode), parent(0) {
operands.reserve(numOperands);
// Make sure that we get added to a machine basicblock
LeakDetector::addGarbageObject(this);
}
/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
unsigned numOperands)
: Opcode(opcode), parent(0) {
assert(MBB && "Cannot use inserting ctor with null basic block!");
operands.reserve(numOperands);
// Make sure that we get added to a machine basicblock
LeakDetector::addGarbageObject(this);
MBB->push_back(this); // Add instruction to end of basic block!
}
/// MachineInstr ctor - Copies MachineInstr arg exactly
///
MachineInstr::MachineInstr(const MachineInstr &MI) {
Opcode = MI.getOpcode();
operands.reserve(MI.getNumOperands());
// Add operands
for (unsigned i = 0; i < MI.getNumOperands(); ++i)
operands.push_back(MachineOperand(MI.getOperand(i)));
// Set parent, next, and prev to null
parent = 0;
prev = 0;
next = 0;
}
MachineInstr::~MachineInstr() {
LeakDetector::removeGarbageObject(this);
}
/// clone - Create a copy of 'this' instruction that is identical in all ways
/// except the following: the new instruction has no parent and it has no name
///
MachineInstr* MachineInstr::clone() const {
return new MachineInstr(*this);
}
/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, and returns it, but does not delete it.
MachineInstr *MachineInstr::removeFromParent() {
assert(getParent() && "Not embedded in a basic block!");
getParent()->remove(this);
return this;
}
/// OperandComplete - Return true if it's illegal to add a new operand
///
bool MachineInstr::OperandsComplete() const {
int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
return true; // Broken: we have all the operands of this instruction!
return false;
}
void MachineInstr::SetMachineOperandVal(unsigned i,
MachineOperand::MachineOperandType opTy,
Value* V) {
assert(i < operands.size()); // may be explicit or implicit op
operands[i].opType = opTy;
operands[i].contents.value = V;
operands[i].extra.regNum = -1;
}
void
MachineInstr::SetMachineOperandConst(unsigned i,
MachineOperand::MachineOperandType opTy,
int intValue) {
assert(i < getNumOperands()); // must be explicit op
operands[i].opType = opTy;
operands[i].contents.value = NULL;
operands[i].contents.immedVal = intValue;
operands[i].extra.regNum = -1;
operands[i].flags = 0;
}
void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) {
assert(i < getNumOperands()); // must be explicit op
operands[i].opType = MachineOperand::MO_MachineRegister;
operands[i].contents.value = NULL;
operands[i].extra.regNum = regNum;
}
void MachineInstr::dump() const {
std::cerr << " " << *this;
}
static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
os << "(val ";
os << (void*) val; // print address always
if (val && val->hasName())
os << " " << val->getName(); // print name also, if available
os << ")";
return os;
}
static inline void OutputReg(std::ostream &os, unsigned RegNo,
const MRegisterInfo *MRI = 0) {
if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
if (MRI)
os << "%" << MRI->get(RegNo).Name;
else
os << "%mreg(" << RegNo << ")";
} else
os << "%reg" << RegNo;
}
static void print(const MachineOperand &MO, std::ostream &OS,
const TargetMachine *TM) {
const MRegisterInfo *MRI = 0;
if (TM) MRI = TM->getRegisterInfo();
bool CloseParen = true;
if (MO.isHiBits32())
OS << "%lm(";
else if (MO.isLoBits32())
OS << "%lo(";
else if (MO.isHiBits64())
OS << "%hh(";
else if (MO.isLoBits64())
OS << "%hm(";
else
CloseParen = false;
switch (MO.getType()) {
case MachineOperand::MO_VirtualRegister:
if (MO.getVRegValue()) {
OS << "%reg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg())
OS << "==";
}
if (MO.hasAllocatedReg())
OutputReg(OS, MO.getReg(), MRI);
break;
case MachineOperand::MO_CCRegister:
OS << "%ccreg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg()) {
OS << "==";
OutputReg(OS, MO.getReg(), MRI);
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(OS, MO.getMachineRegNum(), MRI);
break;
case MachineOperand::MO_SignExtendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp: {
const Value* opVal = MO.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
OS << opVal->getName();
else
OS << (const void*) opVal;
OS << ")";
break;
}
case MachineOperand::MO_MachineBasicBlock:
OS << "mbb<"
<< ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
<< "," << (void*)MO.getMachineBasicBlock() << ">";
break;
case MachineOperand::MO_FrameIndex:
OS << "<fi#" << MO.getFrameIndex() << ">";
break;
case MachineOperand::MO_ConstantPoolIndex:
OS << "<cp#" << MO.getConstantPoolIndex() << ">";
break;
case MachineOperand::MO_GlobalAddress:
OS << "<ga:" << ((Value*)MO.getGlobal())->getName();
if (MO.getOffset()) OS << "+" << MO.getOffset();
OS << ">";
break;
case MachineOperand::MO_ExternalSymbol:
OS << "<es:" << MO.getSymbolName();
if (MO.getOffset()) OS << "+" << MO.getOffset();
OS << ">";
break;
default:
assert(0 && "Unrecognized operand type");
}
if (CloseParen)
OS << ")";
}
void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
unsigned StartOp = 0;
// Specialize printing if op#0 is definition
if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
::print(getOperand(0), OS, TM);
OS << " = ";
++StartOp; // Don't print this operand again!
}
// Must check if Target machine is not null because machine BB could not
// be attached to a Machine function yet
if (TM)
OS << TM->getInstrInfo()->getName(getOpcode());
for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
const MachineOperand& mop = getOperand(i);
if (i != StartOp)
OS << ",";
OS << " ";
::print(mop, OS, TM);
if (mop.isDef())
if (mop.isUse())
OS << "<def&use>";
else
OS << "<def>";
}
OS << "\n";
}
namespace llvm {
std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
// If the instruction is embedded into a basic block, we can find the target
// info for the instruction.
if (const MachineBasicBlock *MBB = MI.getParent()) {
const MachineFunction *MF = MBB->getParent();
if (MF)
MI.print(os, &MF->getTarget());
else
MI.print(os, 0);
return os;
}
// Otherwise, print it out in the "raw" format without symbolic register names
// and such.
os << TargetInstrDescriptors[MI.getOpcode()].Name;
for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
os << "\t" << MI.getOperand(i);
if (MI.getOperand(i).isDef())
if (MI.getOperand(i).isUse())
os << "<d&u>";
else
os << "<d>";
}
return os << "\n";
}
std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
if (MO.isHiBits32())
OS << "%lm(";
else if (MO.isLoBits32())
OS << "%lo(";
else if (MO.isHiBits64())
OS << "%hh(";
else if (MO.isLoBits64())
OS << "%hm(";
switch (MO.getType()) {
case MachineOperand::MO_VirtualRegister:
if (MO.hasAllocatedReg())
OutputReg(OS, MO.getReg());
if (MO.getVRegValue()) {
if (MO.hasAllocatedReg()) OS << "==";
OS << "%vreg";
OutputValue(OS, MO.getVRegValue());
}
break;
case MachineOperand::MO_CCRegister:
OS << "%ccreg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg()) {
OS << "==";
OutputReg(OS, MO.getReg());
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(OS, MO.getMachineRegNum());
break;
case MachineOperand::MO_SignExtendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp: {
const Value* opVal = MO.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
OS << opVal->getName();
else
OS << (const void*) opVal;
OS << ")";
break;
}
case MachineOperand::MO_MachineBasicBlock:
OS << "<mbb:"
<< ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
<< "@" << (void*)MO.getMachineBasicBlock() << ">";
break;
case MachineOperand::MO_FrameIndex:
OS << "<fi#" << MO.getFrameIndex() << ">";
break;
case MachineOperand::MO_ConstantPoolIndex:
OS << "<cp#" << MO.getConstantPoolIndex() << ">";
break;
case MachineOperand::MO_GlobalAddress:
OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
break;
case MachineOperand::MO_ExternalSymbol:
OS << "<es:" << MO.getSymbolName() << ">";
break;
default:
assert(0 && "Unrecognized operand type");
break;
}
if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
OS << ")";
return OS;
}
}
<|endoftext|> |
<commit_before>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/logic/system/graphics/render/distance.h"
using namespace pb;
DistanceRenderSystem::DistanceRenderSystem(float distance)
: _Distance(distance)
{
}
Uid DistanceRenderSystem::GetStaticType()
{
return RenderSystem::GetStaticType();
}
void DistanceRenderSystem::Render(Scene* scene, Viewport* viewport)
{
glm::vec3 cameraPosition = viewport->GetCamera()->Position;
cameraPosition.z = 0;
for (RenderableSet::iterator it = _Renderables.begin(); it != _Renderables.end(); ++it)
{
glm::vec4 position = (*it)->GetWorldMatrix()[3];
if (glm::distance(cameraPosition, glm::vec3(position.x, position.y, 0)) < _Distance)
RenderItem(*it);
}
}
void DistanceRenderSystem::AddItem(Renderable* renderable)
{
_Renderables.insert(renderable);
}
void DistanceRenderSystem::RemoveItem(Renderable* renderable)
{
_Renderables.erase(renderable);
}
<commit_msg>Fix issue with particles not appearing with distance render system<commit_after>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/logic/system/graphics/render/distance.h"
using namespace pb;
DistanceRenderSystem::DistanceRenderSystem(float distance)
: _Distance(distance)
{
}
Uid DistanceRenderSystem::GetStaticType()
{
return RenderSystem::GetStaticType();
}
void DistanceRenderSystem::Render(Scene* scene, Viewport* viewport)
{
glm::vec3 cameraPosition = viewport->GetCamera()->Position;
cameraPosition.z = 0;
for (RenderableSet::iterator it = _Renderables.begin(); it != _Renderables.end(); ++it)
{
glm::vec4 position = (*it)->GetWorldMatrix()[3];
if ((*it)->GetRenderableType() == TypeHash("particle")|| glm::distance(cameraPosition, glm::vec3(position.x, position.y, 0)) < _Distance)
RenderItem(*it);
}
}
void DistanceRenderSystem::AddItem(Renderable* renderable)
{
_Renderables.insert(renderable);
}
void DistanceRenderSystem::RemoveItem(Renderable* renderable)
{
_Renderables.erase(renderable);
}
<|endoftext|> |
<commit_before>AliAnalysisTask *AddTask_jbook_JPsi(TString config="1",
Bool_t gridconf=kFALSE,
Bool_t hasMC=kFALSE,
ULong64_t triggers=AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_jbook_JPsi", "No analysis manager found.");
return 0;
}
//Do we have an MC handler?
TString list = gSystem->Getenv("LIST");
if(!list.IsNull()) {
if( list.Contains("LHC10h") || list.Contains("LHC11h") ) hasMC=kFALSE;
if( list.Contains("LHC11a10") || list.Contains("LHC12a17") ) hasMC=kTRUE;
}
//Do we have an AOD handler?
Bool_t isAOD=(mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class() ? kTRUE : kFALSE);
// set AOD debug levels
if(isAOD) {
mgr->AddClassDebug("AliAODTrack", AliLog::kFatal);
mgr->AddClassDebug("AliAODpidUtil", AliLog::kInfo);
}
//set config file name
TString configFile("");
printf("%s \n",gSystem->pwd());
TString trainRoot=gSystem->Getenv("TRAIN_ROOT");
// gsi config
if (!trainRoot.IsNull()) configFile="$TRAIN_ROOT/jbook_jpsi/ConfigJpsi_jb_PbPb.C";
// alien config
else if(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C .")) {
gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
configFile=Form("%s/ConfigJpsi_jb_PbPb.C",gSystem->pwd());
}
else {
printf("ERROR: couldn't copy file %s from grid \n",
"alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C");
return;
}
// aliroot config
if(!gridconf && trainRoot.IsNull())
configFile="$ALICE_ROOT/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C"; // aliroot config
//create task
AliAnalysisTaskMultiDielectron *task;
// trigger selection
ULong64_t triggerSets[]={AliVEvent::kCentral , AliVEvent::kSemiCentral , AliVEvent::kMB,
AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB};
const char* triggerNames[]={"Central","SemiCentral","MB","ALL"};
const char* onlineRejection[]={"","CCENT","",""};
// find out the configured triggers
Int_t j=0;
for(j=0; j<4; j++) {
if(triggers!=triggerSets[j]) continue;
else break;
}
// print overall configuration
printf("production: %s MC: %d \n", list.Data(),hasMC);
printf("triggers: %s \n", triggerNames[j] );
printf("config: %s Grid: %d \n",configFile.Data(),gridconf);
//load dielectron configuration file (only once)
TString checkconfig="ConfigJpsi_jb_PbPb";
if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
gROOT->LoadMacro(configFile.Data());
//define default output container
TString containerName = "JPSI.root";
//add dielectron analysis with different cuts to the task
for (Int_t i=0; i<nDie; ++i) { //nDie defined in config file
//only configs switched ON will pass
if(config.Length()<=i || config(i,1)!="1") { printf(" %d switched OFF \n",i); continue; }
// load configuration
AliDielectron *jpsi=ConfigJpsi_jb_PbPb(i,hasMC,triggers);
if(!jpsi) continue;
// create unique title
TString unitit = Form("%s_%s",triggerNames[j],jpsi->GetName());
// create single tasks instead of one multi task (decreasing size of CF container)
task = new AliAnalysisTaskMultiDielectron(Form("MultiDieJB_%s",unitit.Data()));
task->SetBeamEnergy(1380.);
task->SetTriggerMask(triggers);
if(strlen(onlineRejection[j])) task->SetFiredTriggerName(onlineRejection[j],kTRUE);
if(!hasMC) task->UsePhysicsSelection();
// add dielectron to the task and manager
task->AddDielectron(jpsi);
mgr->AddTask(task);
//create output sub containers
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer(Form("jbook_QA_%s",unitit.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer(Form("jbook_CF_%s",unitit.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer(Form("jbook_EventStat_%s",unitit.Data()),
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
// mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
printf(" %s added\n",jpsi->GetName());
}
return task;
}
<commit_msg>-update<commit_after>AliAnalysisTask *AddTask_jbook_JPsi(TString config="1",
Bool_t gridconf=kFALSE,
Bool_t hasMC=kFALSE,
ULong64_t triggers=AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_jbook_JPsi", "No analysis manager found.");
return 0;
}
//Do we have an MC handler?
TString list = gSystem->Getenv("LIST");
if(!list.IsNull()) {
if( list.Contains("LHC10h") || list.Contains("LHC11h") ) hasMC=kFALSE;
if( list.Contains("LHC11a10") || list.Contains("LHC12a17") ) hasMC=kTRUE;
}
//Do we have an AOD handler?
Bool_t isAOD=(mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class() ? kTRUE : kFALSE);
// set AOD debug levels
if(isAOD) {
mgr->AddClassDebug("AliAODTrack", AliLog::kFatal);
mgr->AddClassDebug("AliAODpidUtil", AliLog::kInfo);
}
//set config file name
TString configFile("");
printf("%s \n",gSystem->pwd());
TString trainRoot=gSystem->Getenv("TRAIN_ROOT");
// gsi config
if (!trainRoot.IsNull()) configFile="$TRAIN_ROOT/jbook_jpsi/ConfigJpsi_jb_PbPb.C";
// alien config
else if(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C .")) {
gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
configFile=Form("%s/ConfigJpsi_jb_PbPb.C",gSystem->pwd());
}
else {
printf("ERROR: couldn't copy file %s from grid \n",
"alien:///alice/cern.ch/user/j/jbook/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C");
return;
}
// aliroot config
if(!gridconf && trainRoot.IsNull())
configFile="$ALICE_ROOT/PWGDQ/dielectron/macrosJPSI/ConfigJpsi_jb_PbPb.C"; // aliroot config
//create task
AliAnalysisTaskMultiDielectron *task;
// trigger selection
ULong64_t triggerSets[]={AliVEvent::kCentral , AliVEvent::kSemiCentral , AliVEvent::kMB,
AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB};
const char* triggerNames[]={"Central","SemiCentral","MB","ALL"};
const char* onlineRejection[]={"","CCENT","",""};
// find out the configured triggers
Int_t j=0;
for(j=0; j<4; j++) {
if(triggers!=triggerSets[j]) continue;
else break;
}
// print overall configuration
printf("production: %s MC: %d \n", list.Data(),hasMC);
printf("triggers: %s \n", triggerNames[j] );
printf("config: %s Grid: %d \n",configFile.Data(),gridconf);
//load dielectron configuration file (only once)
TString checkconfig="ConfigJpsi_jb_PbPb";
if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
gROOT->LoadMacro(configFile.Data());
//define default output container
TString containerName = "JPSI.root";
//add dielectron analysis with different cuts to the task
for (Int_t i=0; i<nDie; ++i) { //nDie defined in config file
//only configs switched ON will pass
if(config.Length()<=i || config(i,1)!="1") { printf(" %d switched OFF \n",i); continue; }
// load configuration
AliDielectron *jpsi=ConfigJpsi_jb_PbPb(i,hasMC,triggers);
if(!jpsi) continue;
// create unique title
TString unitit = Form("%s_%s",triggerNames[j],jpsi->GetName());
// create single tasks instead of one multi task (decreasing size of CF container)
task = new AliAnalysisTaskMultiDielectron(Form("MultiDieJB_%s",unitit.Data()));
task->SetBeamEnergy(1380.);
task->SetTriggerMask(triggers);
if(strlen(onlineRejection[j])) task->SetFiredTriggerName(onlineRejection[j],kTRUE);
if(!hasMC) task->UsePhysicsSelection();
// event filter
AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("vertex","vertex");
if(isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
eventCuts->SetRequireVertex();
eventCuts->SetMinVtxContributors(1);
eventCuts->SetVertexZ(-10.,+10.);
eventCuts->SetCentralityRange(0,90.);
eventCuts->Print();
task->SetEventFilter(eventCuts);
// add dielectron to the task and manager
task->AddDielectron(jpsi);
mgr->AddTask(task);
//create output sub containers
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer(Form("jbook_QA_%s",unitit.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer(Form("jbook_CF_%s",unitit.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer(Form("jbook_EventStat_%s",unitit.Data()),
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
// mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
printf(" %s added\n",jpsi->GetName());
}
return task;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Ford Motor Company
* 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 Ford Motor Company 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 "application_manager/commands/hmi/get_urls.h"
#include "application_manager/message.h"
#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"
namespace application_manager {
namespace commands {
GetUrls::GetUrls(const MessageSharedPtr& message,
ApplicationManager& application_manager)
: RequestFromHMI(message, application_manager) {}
GetUrls::~GetUrls() {}
void GetUrls::Run() {
LOG4CXX_AUTO_TRACE(logger_);
namespace Common_Result = hmi_apis::Common_Result;
using policy::EndpointUrls;
if (!application_manager_.GetPolicyHandler().PolicyEnabled()) {
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
const uint32_t service_to_check =
(*message_)[strings::msg_params][hmi_request::service].asUInt();
EndpointUrls endpoints;
application_manager_.GetPolicyHandler().GetUpdateUrls(service_to_check,
endpoints);
if (endpoints.empty()) {
LOG4CXX_ERROR(logger_, "No URLs for service " << service_to_check);
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
#ifdef EXTENDED_POLICY
const uint32_t policy_service = 7;
if (policy_service == service_to_check) {
ProcessPolicyServiceURLs(endpoints);
return;
}
#endif // EXTENDED_POLICY
ProcessServiceURLs(endpoints);
}
void GetUrls::ProcessServiceURLs(const policy::EndpointUrls& endpoints) {
namespace Common_Result = hmi_apis::Common_Result;
using smart_objects::SmartObject;
(*message_)[strings::msg_params].erase(hmi_request::service);
SmartObject& urls = (*message_)[strings::msg_params][hmi_response::urls];
size_t index = 0;
for (size_t e = 0; e < endpoints.size(); ++e) {
for (size_t u = 0; u < endpoints[e].url.size(); ++u, ++index) {
const std::string app_url = endpoints[e].url[u];
SmartObject& service_info = urls[index];
service_info[strings::url] = app_url;
if (policy::kDefaultId != endpoints[e].app_id) {
#ifndef EXTENDED_PROPRIETARY
service_info[hmi_response::policy_app_id] = endpoints[e].app_id;
#else // EXTENDED_PROPRIETARY
ApplicationSharedPtr app =
application_manager_.application_by_policy_id(endpoints[e].app_id);
if (!app) {
LOG4CXX_ERROR(logger_,
"Can't find application with policy id "
<< endpoints[e].app_id
<< " URLs adding for this appliation is skipped.");
continue;
}
service_info[strings::app_id] = app->hmi_app_id();
#endif // EXTENDED_PROPRIETARY
}
}
}
SendResponseToHMI(Common_Result::SUCCESS);
}
void GetUrls::SendResponseToHMI(hmi_apis::Common_Result::eType result) {
(*message_)[strings::params][strings::message_type] = MessageType::kResponse;
(*message_)[strings::params][hmi_response::code] = result;
application_manager_.ManageHMICommand(message_);
}
#ifdef EXTENDED_POLICY
struct PolicyAppIdComparator {
PolicyAppIdComparator(const std::string& policy_app_id)
: policy_app_id_(policy_app_id) {}
bool operator()(const policy::EndpointData& data) {
return data.app_id == policy_app_id_;
}
std::string policy_app_id_;
};
void FillSODefaultUrls(smart_objects::SmartObject& urls,
const policy::EndpointUrls& endpoints) {
using smart_objects::SmartObject;
PolicyAppIdComparator comparator(policy::kDefaultId);
policy::EndpointUrls::const_iterator it =
std::find_if(endpoints.begin(), endpoints.end(), comparator);
if (it == endpoints.end()) {
return;
}
SmartObject service_info = SmartObject(smart_objects::SmartType_Map);
for (size_t i = 0; i < (*it).url.size(); ++i) {
service_info[strings::url] = (*it).url[i];
urls[i] = service_info;
}
}
void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace smart_objects;
using namespace application_manager;
using namespace strings;
using namespace hmi_apis;
const uint32_t app_id_to_send_to =
application_manager_.GetPolicyHandler().GetAppIdForSending();
if (!app_id_to_send_to) {
LOG4CXX_ERROR(logger_,
"There are no available applications for processing.");
SmartObject urls(SmartType_Array);
FillSODefaultUrls(urls, endpoints);
if (!urls.empty()) {
(*message_)[msg_params][hmi_response::urls] = urls;
}
(*message_).erase(hmi_request::service);
SendResponseToHMI(Common_Result::SUCCESS);
return;
}
ApplicationSharedPtr app =
application_manager_.application(app_id_to_send_to);
if (!app.valid()) {
LOG4CXX_WARN(logger_,
"There is no registered application with "
"connection key '"
<< app_id_to_send_to << "'");
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
SmartObject& object = *message_;
object[msg_params].erase(hmi_request::service);
object[msg_params][hmi_response::urls] = SmartObject(SmartType_Array);
SmartObject& urls = object[msg_params][hmi_response::urls];
const std::string mobile_app_id = app->policy_app_id();
std::string default_url = "URL is not found";
// Will use only one URL for particular application if it will be found
// Otherwise URL from default section will used
SmartObject service_info = SmartObject(SmartType_Map);
for (size_t e = 0; e < endpoints.size(); ++e) {
if (mobile_app_id == endpoints[e].app_id) {
if (endpoints[e].url.size()) {
service_info[url] = endpoints[e].url[0];
SendResponseToHMI(Common_Result::SUCCESS);
return;
}
}
if (policy::kDefaultId == endpoints[e].app_id) {
if (endpoints[e].url.size()) {
default_url = endpoints[e].url[0];
}
}
}
service_info[strings::app_id] = app->app_id();
service_info[strings::url] = default_url;
urls[0] = service_info;
// TODO(AOleynik): Issue with absent policy_app_id. Need to fix later on.
// Possibly related to smart schema
SendResponseToHMI(Common_Result::SUCCESS);
return;
}
#endif // EXTENDED_POLICY
} // namespace commands
} // namespace application_manager
<commit_msg>Fux int\uint mistmatch<commit_after>/*
* Copyright (c) 2016, Ford Motor Company
* 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 Ford Motor Company 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 "application_manager/commands/hmi/get_urls.h"
#include "application_manager/message.h"
#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"
namespace application_manager {
namespace commands {
GetUrls::GetUrls(const MessageSharedPtr& message,
ApplicationManager& application_manager)
: RequestFromHMI(message, application_manager) {}
GetUrls::~GetUrls() {}
void GetUrls::Run() {
LOG4CXX_AUTO_TRACE(logger_);
namespace Common_Result = hmi_apis::Common_Result;
using policy::EndpointUrls;
if (!application_manager_.GetPolicyHandler().PolicyEnabled()) {
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
const uint32_t service_to_check =
(*message_)[strings::msg_params][hmi_request::service].asUInt();
EndpointUrls endpoints;
application_manager_.GetPolicyHandler().GetUpdateUrls(service_to_check,
endpoints);
if (endpoints.empty()) {
LOG4CXX_ERROR(logger_, "No URLs for service " << service_to_check);
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
#ifdef EXTENDED_POLICY
const uint32_t policy_service = 7u;
if (policy_service == service_to_check) {
ProcessPolicyServiceURLs(endpoints);
return;
}
#endif // EXTENDED_POLICY
ProcessServiceURLs(endpoints);
}
void GetUrls::ProcessServiceURLs(const policy::EndpointUrls& endpoints) {
namespace Common_Result = hmi_apis::Common_Result;
using smart_objects::SmartObject;
(*message_)[strings::msg_params].erase(hmi_request::service);
SmartObject& urls = (*message_)[strings::msg_params][hmi_response::urls];
size_t index = 0;
for (size_t e = 0; e < endpoints.size(); ++e) {
for (size_t u = 0; u < endpoints[e].url.size(); ++u, ++index) {
const std::string app_url = endpoints[e].url[u];
SmartObject& service_info = urls[index];
service_info[strings::url] = app_url;
if (policy::kDefaultId != endpoints[e].app_id) {
#ifndef EXTENDED_PROPRIETARY
service_info[hmi_response::policy_app_id] = endpoints[e].app_id;
#else // EXTENDED_PROPRIETARY
ApplicationSharedPtr app =
application_manager_.application_by_policy_id(endpoints[e].app_id);
if (!app) {
LOG4CXX_ERROR(logger_,
"Can't find application with policy id "
<< endpoints[e].app_id
<< " URLs adding for this appliation is skipped.");
continue;
}
service_info[strings::app_id] = app->hmi_app_id();
#endif // EXTENDED_PROPRIETARY
}
}
}
SendResponseToHMI(Common_Result::SUCCESS);
}
void GetUrls::SendResponseToHMI(hmi_apis::Common_Result::eType result) {
(*message_)[strings::params][strings::message_type] = MessageType::kResponse;
(*message_)[strings::params][hmi_response::code] = result;
application_manager_.ManageHMICommand(message_);
}
#ifdef EXTENDED_POLICY
struct PolicyAppIdComparator {
PolicyAppIdComparator(const std::string& policy_app_id)
: policy_app_id_(policy_app_id) {}
bool operator()(const policy::EndpointData& data) {
return data.app_id == policy_app_id_;
}
std::string policy_app_id_;
};
void FillSODefaultUrls(smart_objects::SmartObject& urls,
const policy::EndpointUrls& endpoints) {
using smart_objects::SmartObject;
PolicyAppIdComparator comparator(policy::kDefaultId);
policy::EndpointUrls::const_iterator it =
std::find_if(endpoints.begin(), endpoints.end(), comparator);
if (it == endpoints.end()) {
return;
}
SmartObject service_info = SmartObject(smart_objects::SmartType_Map);
for (size_t i = 0; i < (*it).url.size(); ++i) {
service_info[strings::url] = (*it).url[i];
urls[i] = service_info;
}
}
void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace smart_objects;
using namespace application_manager;
using namespace strings;
using namespace hmi_apis;
const uint32_t app_id_to_send_to =
application_manager_.GetPolicyHandler().GetAppIdForSending();
if (!app_id_to_send_to) {
LOG4CXX_ERROR(logger_,
"There are no available applications for processing.");
SmartObject urls(SmartType_Array);
FillSODefaultUrls(urls, endpoints);
if (!urls.empty()) {
(*message_)[msg_params][hmi_response::urls] = urls;
}
(*message_).erase(hmi_request::service);
SendResponseToHMI(Common_Result::SUCCESS);
return;
}
ApplicationSharedPtr app =
application_manager_.application(app_id_to_send_to);
if (!app.valid()) {
LOG4CXX_WARN(logger_,
"There is no registered application with "
"connection key '"
<< app_id_to_send_to << "'");
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
SmartObject& object = *message_;
object[msg_params].erase(hmi_request::service);
object[msg_params][hmi_response::urls] = SmartObject(SmartType_Array);
SmartObject& urls = object[msg_params][hmi_response::urls];
const std::string mobile_app_id = app->policy_app_id();
std::string default_url = "URL is not found";
// Will use only one URL for particular application if it will be found
// Otherwise URL from default section will used
SmartObject service_info = SmartObject(SmartType_Map);
for (size_t e = 0; e < endpoints.size(); ++e) {
if (mobile_app_id == endpoints[e].app_id) {
if (endpoints[e].url.size()) {
service_info[url] = endpoints[e].url[0];
SendResponseToHMI(Common_Result::SUCCESS);
return;
}
}
if (policy::kDefaultId == endpoints[e].app_id) {
if (endpoints[e].url.size()) {
default_url = endpoints[e].url[0];
}
}
}
service_info[strings::app_id] = app->app_id();
service_info[strings::url] = default_url;
urls[0] = service_info;
// TODO(AOleynik): Issue with absent policy_app_id. Need to fix later on.
// Possibly related to smart schema
SendResponseToHMI(Common_Result::SUCCESS);
return;
}
#endif // EXTENDED_POLICY
} // namespace commands
} // namespace application_manager
<|endoftext|> |
<commit_before> AliAnalysisPseudoRapidityDensityTemp* AddTaskTemp(const char* taskname, const char* option){
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
AliAnalysisPseudoRapidityDensityTemp *task = new AliAnalysisPseudoRapidityDensityTemp(taskname, option);
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput = mgr->CreateContainer("output", TList::Class(), AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
mgr->AddTask(task);
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput);
return task;
}
<commit_msg>Update AddTaskPseudoRapidityDensity.C<commit_after> AliAnalysisPseudoRapidityDensity* AddTaskPseudoRapidityDensity(const char* taskname, const char* option){
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
AliAnalysisPseudoRapidityDensity *task = new AliAnalysisPseudoRapidityDensity(taskname, option);
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput = mgr->CreateContainer("output", TList::Class(), AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
mgr->AddTask(task);
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput);
return task;
}
<|endoftext|> |
<commit_before>//===--- InstructionUtils.cpp - Utilities for SIL instructions ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-inst-utils"
#include "swift/SIL/InstructionUtils.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILVisitor.h"
using namespace swift;
/// Strip off casts/indexing insts/address projections from V until there is
/// nothing left to strip.
/// FIXME: Why don't we strip projections after stripping indexes?
SILValue swift::getUnderlyingObject(SILValue V) {
while (true) {
SILValue V2 = stripIndexingInsts(stripAddressProjections(stripCasts(V)));
if (V2 == V)
return V2;
V = V2;
}
}
SILValue swift::getUnderlyingAddressRoot(SILValue V) {
while (true) {
SILValue V2 = stripIndexingInsts(stripCasts(V));
switch (V2->getKind()) {
case ValueKind::StructElementAddrInst:
case ValueKind::TupleElementAddrInst:
case ValueKind::UncheckedTakeEnumDataAddrInst:
V2 = cast<SingleValueInstruction>(V2)->getOperand(0);
break;
default:
break;
}
if (V2 == V)
return V2;
V = V2;
}
}
SILValue swift::getUnderlyingObjectStopAtMarkDependence(SILValue V) {
while (true) {
SILValue V2 = stripIndexingInsts(stripAddressProjections(stripCastsWithoutMarkDependence(V)));
if (V2 == V)
return V2;
V = V2;
}
}
static bool isRCIdentityPreservingCast(ValueKind Kind) {
switch (Kind) {
case ValueKind::UpcastInst:
case ValueKind::UncheckedRefCastInst:
case ValueKind::UnconditionalCheckedCastInst:
case ValueKind::UnconditionalCheckedCastValueInst:
case ValueKind::RefToBridgeObjectInst:
case ValueKind::BridgeObjectToRefInst:
return true;
default:
return false;
}
}
/// Return the underlying SILValue after stripping off identity SILArguments if
/// we belong to a BB with one predecessor.
SILValue swift::stripSinglePredecessorArgs(SILValue V) {
while (true) {
auto *A = dyn_cast<SILArgument>(V);
if (!A)
return V;
SILBasicBlock *BB = A->getParent();
// First try and grab the single predecessor of our parent BB. If we don't
// have one, bail.
SILBasicBlock *Pred = BB->getSinglePredecessorBlock();
if (!Pred)
return V;
// Then grab the terminator of Pred...
TermInst *PredTI = Pred->getTerminator();
// And attempt to find our matching argument.
//
// *NOTE* We can only strip things here if we know that there is no semantic
// change in terms of upcasts/downcasts/enum extraction since this is used
// by other routines here. This means that we can only look through
// cond_br/br.
//
// For instance, routines that use stripUpcasts() do not want to strip off a
// downcast that results from checked_cast_br.
if (auto *BI = dyn_cast<BranchInst>(PredTI)) {
V = BI->getArg(A->getIndex());
continue;
}
if (auto *CBI = dyn_cast<CondBranchInst>(PredTI)) {
if (SILValue Arg = CBI->getArgForDestBB(BB, A)) {
V = Arg;
continue;
}
}
return V;
}
}
SILValue swift::stripCastsWithoutMarkDependence(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
auto K = V->getKind();
if (isRCIdentityPreservingCast(K) ||
K == ValueKind::UncheckedTrivialBitCastInst) {
V = cast<SingleValueInstruction>(V)->getOperand(0);
continue;
}
return V;
}
}
SILValue swift::stripCasts(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
auto K = V->getKind();
if (isRCIdentityPreservingCast(K)
|| K == ValueKind::UncheckedTrivialBitCastInst
|| K == ValueKind::MarkDependenceInst) {
V = cast<SingleValueInstruction>(V)->getOperand(0);
continue;
}
return V;
}
}
SILValue swift::stripUpCasts(SILValue V) {
assert(V->getType().isClassOrClassMetatype() &&
"Expected class or class metatype!");
V = stripSinglePredecessorArgs(V);
while (auto upcast = dyn_cast<UpcastInst>(V))
V = stripSinglePredecessorArgs(upcast->getOperand());
return V;
}
SILValue swift::stripClassCasts(SILValue V) {
while (true) {
if (auto *UI = dyn_cast<UpcastInst>(V)) {
V = UI->getOperand();
continue;
}
if (auto *UCCI = dyn_cast<UnconditionalCheckedCastInst>(V)) {
V = UCCI->getOperand();
continue;
}
return V;
}
}
SILValue swift::stripAddressProjections(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
if (!Projection::isAddressProjection(V))
return V;
V = cast<SingleValueInstruction>(V)->getOperand(0);
}
}
SILValue swift::stripUnaryAddressProjections(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
if (!Projection::isAddressProjection(V))
return V;
auto *Inst = cast<SingleValueInstruction>(V);
if (Inst->getNumOperands() > 1)
return V;
V = Inst->getOperand(0);
}
}
SILValue swift::stripValueProjections(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
if (!Projection::isObjectProjection(V))
return V;
V = cast<SingleValueInstruction>(V)->getOperand(0);
}
}
SILValue swift::stripIndexingInsts(SILValue V) {
while (true) {
if (!isa<IndexingInst>(V))
return V;
V = cast<IndexingInst>(V)->getBase();
}
}
SILValue swift::stripExpectIntrinsic(SILValue V) {
auto *BI = dyn_cast<BuiltinInst>(V);
if (!BI)
return V;
if (BI->getIntrinsicInfo().ID != llvm::Intrinsic::expect)
return V;
return BI->getArguments()[0];
}
SILValue swift::stripBorrow(SILValue V) {
if (auto *BBI = dyn_cast<BeginBorrowInst>(V))
return BBI->getOperand();
return V;
}
namespace {
enum class OwnershipQualifiedKind {
NotApplicable,
Qualified,
Unqualified,
};
struct OwnershipQualifiedKindVisitor : SILInstructionVisitor<OwnershipQualifiedKindVisitor, OwnershipQualifiedKind> {
OwnershipQualifiedKind visitSILInstruction(SILInstruction *I) {
return OwnershipQualifiedKind::NotApplicable;
}
#define QUALIFIED_INST(CLASS) \
OwnershipQualifiedKind visit ## CLASS(CLASS *I) { \
return OwnershipQualifiedKind::Qualified; \
}
QUALIFIED_INST(EndBorrowInst)
QUALIFIED_INST(LoadBorrowInst)
QUALIFIED_INST(CopyValueInst)
QUALIFIED_INST(CopyUnownedValueInst)
QUALIFIED_INST(DestroyValueInst)
#undef QUALIFIED_INST
OwnershipQualifiedKind visitLoadInst(LoadInst *LI) {
if (LI->getOwnershipQualifier() == LoadOwnershipQualifier::Unqualified)
return OwnershipQualifiedKind::Unqualified;
return OwnershipQualifiedKind::Qualified;
}
OwnershipQualifiedKind visitStoreInst(StoreInst *SI) {
if (SI->getOwnershipQualifier() == StoreOwnershipQualifier::Unqualified)
return OwnershipQualifiedKind::Unqualified;
return OwnershipQualifiedKind::Qualified;
}
};
} // end anonymous namespace
bool FunctionOwnershipEvaluator::evaluate(SILInstruction *I) {
assert(I->getFunction() == F.get() && "Can not evaluate function ownership "
"implications of an instruction that "
"does not belong to the instruction "
"that we are evaluating");
switch (OwnershipQualifiedKindVisitor().visit(I)) {
case OwnershipQualifiedKind::Unqualified: {
// If we already know that the function has unqualified ownership, just
// return early.
if (!F.get()->hasQualifiedOwnership())
return true;
// Ok, so we know at this point that we have qualified ownership. If we have
// seen any instructions with qualified ownership, we have an error since
// the function mixes qualified and unqualified instructions.
if (HasOwnershipQualifiedInstruction)
return false;
// Otherwise, set the function to have unqualified ownership. This will
// ensure that no more Qualified instructions can be added to the given
// function.
F.get()->setUnqualifiedOwnership();
return true;
}
case OwnershipQualifiedKind::Qualified: {
// First check if our function has unqualified ownership. If we already do
// have unqualified ownership, then we know that we have already seen an
// unqualified ownership instruction. This means the function has both
// qualified and unqualified instructions. =><=.
if (!F.get()->hasQualifiedOwnership())
return false;
// Ok, at this point we know that we are still qualified. Since functions
// start as qualified, we need to set the HasOwnershipQualifiedInstructions
// so we do not need to look back through the function if we see an
// unqualified instruction later on.
HasOwnershipQualifiedInstruction = true;
return true;
}
case OwnershipQualifiedKind::NotApplicable: {
// Not Applicable instr
return true;
}
}
llvm_unreachable("Unhandled OwnershipQualifiedKind in switch.");
}
<commit_msg>Comment getUnderlyingAddressRoot.<commit_after>//===--- InstructionUtils.cpp - Utilities for SIL instructions ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-inst-utils"
#include "swift/SIL/InstructionUtils.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILVisitor.h"
using namespace swift;
/// Strip off casts/indexing insts/address projections from V until there is
/// nothing left to strip.
/// FIXME: Why don't we strip projections after stripping indexes?
SILValue swift::getUnderlyingObject(SILValue V) {
while (true) {
SILValue V2 = stripIndexingInsts(stripAddressProjections(stripCasts(V)));
if (V2 == V)
return V2;
V = V2;
}
}
/// Strip off casts and address projections into the interior of a value. Unlike
/// getUnderlyingObject, this does not find the root of a heap object--a class
/// property is itself an address root.
SILValue swift::getUnderlyingAddressRoot(SILValue V) {
while (true) {
SILValue V2 = stripIndexingInsts(stripCasts(V));
switch (V2->getKind()) {
case ValueKind::StructElementAddrInst:
case ValueKind::TupleElementAddrInst:
case ValueKind::UncheckedTakeEnumDataAddrInst:
V2 = cast<SingleValueInstruction>(V2)->getOperand(0);
break;
default:
break;
}
if (V2 == V)
return V2;
V = V2;
}
}
SILValue swift::getUnderlyingObjectStopAtMarkDependence(SILValue V) {
while (true) {
SILValue V2 = stripIndexingInsts(stripAddressProjections(stripCastsWithoutMarkDependence(V)));
if (V2 == V)
return V2;
V = V2;
}
}
static bool isRCIdentityPreservingCast(ValueKind Kind) {
switch (Kind) {
case ValueKind::UpcastInst:
case ValueKind::UncheckedRefCastInst:
case ValueKind::UnconditionalCheckedCastInst:
case ValueKind::UnconditionalCheckedCastValueInst:
case ValueKind::RefToBridgeObjectInst:
case ValueKind::BridgeObjectToRefInst:
return true;
default:
return false;
}
}
/// Return the underlying SILValue after stripping off identity SILArguments if
/// we belong to a BB with one predecessor.
SILValue swift::stripSinglePredecessorArgs(SILValue V) {
while (true) {
auto *A = dyn_cast<SILArgument>(V);
if (!A)
return V;
SILBasicBlock *BB = A->getParent();
// First try and grab the single predecessor of our parent BB. If we don't
// have one, bail.
SILBasicBlock *Pred = BB->getSinglePredecessorBlock();
if (!Pred)
return V;
// Then grab the terminator of Pred...
TermInst *PredTI = Pred->getTerminator();
// And attempt to find our matching argument.
//
// *NOTE* We can only strip things here if we know that there is no semantic
// change in terms of upcasts/downcasts/enum extraction since this is used
// by other routines here. This means that we can only look through
// cond_br/br.
//
// For instance, routines that use stripUpcasts() do not want to strip off a
// downcast that results from checked_cast_br.
if (auto *BI = dyn_cast<BranchInst>(PredTI)) {
V = BI->getArg(A->getIndex());
continue;
}
if (auto *CBI = dyn_cast<CondBranchInst>(PredTI)) {
if (SILValue Arg = CBI->getArgForDestBB(BB, A)) {
V = Arg;
continue;
}
}
return V;
}
}
SILValue swift::stripCastsWithoutMarkDependence(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
auto K = V->getKind();
if (isRCIdentityPreservingCast(K) ||
K == ValueKind::UncheckedTrivialBitCastInst) {
V = cast<SingleValueInstruction>(V)->getOperand(0);
continue;
}
return V;
}
}
SILValue swift::stripCasts(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
auto K = V->getKind();
if (isRCIdentityPreservingCast(K)
|| K == ValueKind::UncheckedTrivialBitCastInst
|| K == ValueKind::MarkDependenceInst) {
V = cast<SingleValueInstruction>(V)->getOperand(0);
continue;
}
return V;
}
}
SILValue swift::stripUpCasts(SILValue V) {
assert(V->getType().isClassOrClassMetatype() &&
"Expected class or class metatype!");
V = stripSinglePredecessorArgs(V);
while (auto upcast = dyn_cast<UpcastInst>(V))
V = stripSinglePredecessorArgs(upcast->getOperand());
return V;
}
SILValue swift::stripClassCasts(SILValue V) {
while (true) {
if (auto *UI = dyn_cast<UpcastInst>(V)) {
V = UI->getOperand();
continue;
}
if (auto *UCCI = dyn_cast<UnconditionalCheckedCastInst>(V)) {
V = UCCI->getOperand();
continue;
}
return V;
}
}
SILValue swift::stripAddressProjections(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
if (!Projection::isAddressProjection(V))
return V;
V = cast<SingleValueInstruction>(V)->getOperand(0);
}
}
SILValue swift::stripUnaryAddressProjections(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
if (!Projection::isAddressProjection(V))
return V;
auto *Inst = cast<SingleValueInstruction>(V);
if (Inst->getNumOperands() > 1)
return V;
V = Inst->getOperand(0);
}
}
SILValue swift::stripValueProjections(SILValue V) {
while (true) {
V = stripSinglePredecessorArgs(V);
if (!Projection::isObjectProjection(V))
return V;
V = cast<SingleValueInstruction>(V)->getOperand(0);
}
}
SILValue swift::stripIndexingInsts(SILValue V) {
while (true) {
if (!isa<IndexingInst>(V))
return V;
V = cast<IndexingInst>(V)->getBase();
}
}
SILValue swift::stripExpectIntrinsic(SILValue V) {
auto *BI = dyn_cast<BuiltinInst>(V);
if (!BI)
return V;
if (BI->getIntrinsicInfo().ID != llvm::Intrinsic::expect)
return V;
return BI->getArguments()[0];
}
SILValue swift::stripBorrow(SILValue V) {
if (auto *BBI = dyn_cast<BeginBorrowInst>(V))
return BBI->getOperand();
return V;
}
namespace {
enum class OwnershipQualifiedKind {
NotApplicable,
Qualified,
Unqualified,
};
struct OwnershipQualifiedKindVisitor : SILInstructionVisitor<OwnershipQualifiedKindVisitor, OwnershipQualifiedKind> {
OwnershipQualifiedKind visitSILInstruction(SILInstruction *I) {
return OwnershipQualifiedKind::NotApplicable;
}
#define QUALIFIED_INST(CLASS) \
OwnershipQualifiedKind visit ## CLASS(CLASS *I) { \
return OwnershipQualifiedKind::Qualified; \
}
QUALIFIED_INST(EndBorrowInst)
QUALIFIED_INST(LoadBorrowInst)
QUALIFIED_INST(CopyValueInst)
QUALIFIED_INST(CopyUnownedValueInst)
QUALIFIED_INST(DestroyValueInst)
#undef QUALIFIED_INST
OwnershipQualifiedKind visitLoadInst(LoadInst *LI) {
if (LI->getOwnershipQualifier() == LoadOwnershipQualifier::Unqualified)
return OwnershipQualifiedKind::Unqualified;
return OwnershipQualifiedKind::Qualified;
}
OwnershipQualifiedKind visitStoreInst(StoreInst *SI) {
if (SI->getOwnershipQualifier() == StoreOwnershipQualifier::Unqualified)
return OwnershipQualifiedKind::Unqualified;
return OwnershipQualifiedKind::Qualified;
}
};
} // end anonymous namespace
bool FunctionOwnershipEvaluator::evaluate(SILInstruction *I) {
assert(I->getFunction() == F.get() && "Can not evaluate function ownership "
"implications of an instruction that "
"does not belong to the instruction "
"that we are evaluating");
switch (OwnershipQualifiedKindVisitor().visit(I)) {
case OwnershipQualifiedKind::Unqualified: {
// If we already know that the function has unqualified ownership, just
// return early.
if (!F.get()->hasQualifiedOwnership())
return true;
// Ok, so we know at this point that we have qualified ownership. If we have
// seen any instructions with qualified ownership, we have an error since
// the function mixes qualified and unqualified instructions.
if (HasOwnershipQualifiedInstruction)
return false;
// Otherwise, set the function to have unqualified ownership. This will
// ensure that no more Qualified instructions can be added to the given
// function.
F.get()->setUnqualifiedOwnership();
return true;
}
case OwnershipQualifiedKind::Qualified: {
// First check if our function has unqualified ownership. If we already do
// have unqualified ownership, then we know that we have already seen an
// unqualified ownership instruction. This means the function has both
// qualified and unqualified instructions. =><=.
if (!F.get()->hasQualifiedOwnership())
return false;
// Ok, at this point we know that we are still qualified. Since functions
// start as qualified, we need to set the HasOwnershipQualifiedInstructions
// so we do not need to look back through the function if we see an
// unqualified instruction later on.
HasOwnershipQualifiedInstruction = true;
return true;
}
case OwnershipQualifiedKind::NotApplicable: {
// Not Applicable instr
return true;
}
}
llvm_unreachable("Unhandled OwnershipQualifiedKind in switch.");
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief base class for input-output tasks from sockets
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "SocketTask.h"
#include <errno.h>
#include "Basics/MutexLocker.h"
#include "Basics/StringBuffer.h"
#include "Basics/logging.h"
#include "Basics/socket-utils.h"
#include "Scheduler/Scheduler.h"
using namespace triagens::basics;
using namespace triagens::rest;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new task with a given socket
////////////////////////////////////////////////////////////////////////////////
SocketTask::SocketTask (TRI_socket_t socket, double keepAliveTimeout)
: Task("SocketTask"),
keepAliveWatcher(0),
readWatcher(0),
writeWatcher(0),
watcher(0),
_commSocket(socket),
_keepAliveTimeout(keepAliveTimeout),
_writeBuffer(nullptr),
#ifdef TRI_ENABLE_FIGURES
_writeBufferStatistics(0),
#endif
ownBuffer(true),
writeLength(0),
_readBuffer(nullptr),
tid(0),
_clientClosed(false) {
_readBuffer = new StringBuffer(TRI_UNKNOWN_MEM_ZONE);
ConnectionStatisticsAgent::acquire();
ConnectionStatisticsAgentSetStart(this);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief deletes a socket task
///
/// This method will close the underlying socket.
////////////////////////////////////////////////////////////////////////////////
SocketTask::~SocketTask () {
if (TRI_isvalidsocket(_commSocket)) {
TRI_CLOSE_SOCKET(_commSocket);
TRI_invalidatesocket(&_commSocket);
}
if (_writeBuffer != nullptr && ownBuffer) {
delete _writeBuffer;
}
#ifdef TRI_ENABLE_FIGURES
if (_writeBufferStatistics != 0) {
TRI_ReleaseRequestStatistics(_writeBufferStatistics);
}
#endif
delete _readBuffer;
ConnectionStatisticsAgentSetEnd(this);
ConnectionStatisticsAgent::release();
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
void SocketTask::setKeepAliveTimeout (double timeout) {
if (keepAliveWatcher != 0 && timeout > 0.0) {
_scheduler->rearmTimer(keepAliveWatcher, timeout);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- protected virtual methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief fills the read buffer
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::fillReadBuffer () {
// reserve some memory for reading
if (_readBuffer->reserve(READ_BLOCK_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {
// out of memory
LOG_TRACE("out of memory");
return false;
}
int nr = TRI_READ_SOCKET(_commSocket, _readBuffer->end(), READ_BLOCK_SIZE, 0);
if (nr > 0) {
_readBuffer->increaseLength(nr);
return true;
}
else if (nr == 0) {
_clientClosed = true;
LOG_TRACE("read returned 0");
return false;
}
else {
if (errno == EINTR) {
return fillReadBuffer();
}
else if (errno != EWOULDBLOCK) {
LOG_TRACE("read failed with %d: %s", (int) errno, strerror(errno));
return false;
}
else {
LOG_TRACE("read would block with %d: %s", (int) errno, strerror(errno));
return true;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief handles a write
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::handleWrite () {
bool callCompletedWriteBuffer = false;
// size_t is unsigned, should never get < 0
size_t len = 0;
if (nullptr != _writeBuffer) {
TRI_ASSERT(_writeBuffer->length() >= writeLength);
len = _writeBuffer->length() - writeLength;
}
int nr = 0;
if (0 < len) {
nr = TRI_WRITE_SOCKET(_commSocket, _writeBuffer->begin() + writeLength, (int) len, 0);
if (nr < 0) {
if (errno == EINTR) {
return handleWrite();
}
else if (errno != EWOULDBLOCK) {
LOG_DEBUG("write failed with %d: %s", (int) errno, strerror(errno));
return false;
}
else {
nr = 0;
}
}
len -= nr;
}
if (len == 0) {
if (nullptr != _writeBuffer && ownBuffer) {
delete _writeBuffer;
}
callCompletedWriteBuffer = true;
}
else {
writeLength += nr;
}
if (callCompletedWriteBuffer) {
completedWriteBuffer();
// rearm timer for keep-alive timeout
// TODO: do we need some lock before we modify the scheduler?
setKeepAliveTimeout(_keepAliveTimeout);
}
if (_clientClosed) {
return false;
}
// we might have a new write buffer or none at all
if (_writeBuffer == nullptr) {
_scheduler->stopSocketEvents(writeWatcher);
}
else {
_scheduler->startSocketEvents(writeWatcher);
}
return true;
}
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief sets an active write buffer
////////////////////////////////////////////////////////////////////////////////
void SocketTask::setWriteBuffer (StringBuffer* buffer,
TRI_request_statistics_t* statistics,
bool ownBuffer) {
bool callCompletedWriteBuffer = false;
#ifdef TRI_ENABLE_FIGURES
_writeBufferStatistics = statistics;
if (_writeBufferStatistics != 0) {
_writeBufferStatistics->_writeStart = TRI_StatisticsTime();
_writeBufferStatistics->_sentBytes += buffer->length();
}
#endif
writeLength = 0;
if (buffer->empty()) {
if (ownBuffer) {
delete buffer;
}
callCompletedWriteBuffer = true;
}
else {
if (_writeBuffer != nullptr) {
if (this->ownBuffer) {
delete _writeBuffer;
}
}
_writeBuffer = buffer;
this->ownBuffer = ownBuffer;
}
if (callCompletedWriteBuffer) {
completedWriteBuffer();
}
if (_clientClosed) {
return;
}
// we might have a new write buffer or none at all
TRI_ASSERT(tid == Thread::currentThreadId());
if (_writeBuffer == 0) {
_scheduler->stopSocketEvents(writeWatcher);
}
else {
_scheduler->startSocketEvents(writeWatcher);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks for presence of an active write buffer
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::hasWriteBuffer () const {
return _writeBuffer != nullptr;
}
// -----------------------------------------------------------------------------
// --SECTION-- Task methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::setup (Scheduler* scheduler, EventLoop loop) {
#ifdef _WIN32
// ..........................................................................
// The problem we have here is that this opening of the fs handle may fail.
// There is no mechanism to the calling function to report failure.
// ..........................................................................
LOG_TRACE("attempting to convert socket handle to socket descriptor");
if (! TRI_isvalidsocket(_commSocket)) {
LOG_ERROR("In SocketTask::setup could not convert socket handle to socket descriptor -- invalid socket handle");
return false;
}
// For the official version of libev we would do this:
// int res = _open_osfhandle(_commSocket.fileHandle, 0);
// However, this opens a whole lot of problems and in general one should
// never use _open_osfhandle for sockets.
// Therefore, we do the following, although it has the potential to
// lose the higher bits of the socket handle:
int res = (int)_commSocket.fileHandle;
if (res == -1) {
LOG_ERROR("In SocketTask::setup could not convert socket handle to socket descriptor -- _open_osfhandle(...) failed");
res = TRI_CLOSE_SOCKET(_commSocket);
if (res != 0) {
res = WSAGetLastError();
LOG_ERROR("In SocketTask::setup closesocket(...) failed with error code: %d", (int) res);
}
TRI_invalidatesocket(&_commSocket);
return false;
}
_commSocket.fileDescriptor = res;
#endif
this->_scheduler = scheduler;
this->_loop = loop;
watcher = _scheduler->installAsyncEvent(loop, this);
readWatcher = _scheduler->installSocketEvent(loop, EVENT_SOCKET_READ, this, _commSocket);
writeWatcher = _scheduler->installSocketEvent(loop, EVENT_SOCKET_WRITE, this, _commSocket);
if (readWatcher == -1 || writeWatcher == -1) {
return false;
}
// install timer for keep-alive timeout with some high default value
keepAliveWatcher = _scheduler->installTimerEvent(loop, this, 60.0);
// and stop it immediately so it's not actively at the start
_scheduler->clearTimer(keepAliveWatcher);
tid = Thread::currentThreadId();
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
void SocketTask::cleanup () {
if (_scheduler == 0) {
LOG_WARNING("In SocketTask::cleanup the scheduler has disappeared -- invalid pointer");
watcher = 0;
keepAliveWatcher = 0;
readWatcher = 0;
writeWatcher = 0;
return;
}
_scheduler->uninstallEvent(watcher);
watcher = 0;
_scheduler->uninstallEvent(keepAliveWatcher);
keepAliveWatcher = 0;
_scheduler->uninstallEvent(readWatcher);
readWatcher = 0;
_scheduler->uninstallEvent(writeWatcher);
writeWatcher = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::handleEvent (EventToken token, EventType revents) {
bool result = true;
if (token == keepAliveWatcher && (revents & EVENT_TIMER)) {
// got a keep-alive timeout
LOG_TRACE("got keep-alive timeout signal, closing connection");
// TODO: do we need some lock before we modify the scheduler?
_scheduler->clearTimer(token);
// this will close the connection and destroy the task
handleTimeout();
return false;
}
if (token == readWatcher && (revents & EVENT_SOCKET_READ)) {
if (keepAliveWatcher != 0) {
// disable timer for keep-alive timeout
_scheduler->clearTimer(keepAliveWatcher);
}
result = handleRead();
}
if (result && ! _clientClosed && token == writeWatcher) {
if (revents & EVENT_SOCKET_WRITE) {
result = handleWrite();
}
}
if (result) {
if (_writeBuffer == nullptr) {
_scheduler->stopSocketEvents(writeWatcher);
}
else {
_scheduler->startSocketEvents(writeWatcher);
}
}
return result;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>fixed initialized order warning<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief base class for input-output tasks from sockets
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "SocketTask.h"
#include <errno.h>
#include "Basics/MutexLocker.h"
#include "Basics/StringBuffer.h"
#include "Basics/logging.h"
#include "Basics/socket-utils.h"
#include "Scheduler/Scheduler.h"
using namespace triagens::basics;
using namespace triagens::rest;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new task with a given socket
////////////////////////////////////////////////////////////////////////////////
SocketTask::SocketTask (TRI_socket_t socket, double keepAliveTimeout)
: Task("SocketTask"),
keepAliveWatcher(0),
readWatcher(0),
writeWatcher(0),
watcher(0),
_commSocket(socket),
_keepAliveTimeout(keepAliveTimeout),
_writeBuffer(nullptr),
#ifdef TRI_ENABLE_FIGURES
_writeBufferStatistics(0),
#endif
ownBuffer(true),
writeLength(0),
_readBuffer(nullptr),
_clientClosed(false),
tid(0) {
_readBuffer = new StringBuffer(TRI_UNKNOWN_MEM_ZONE);
ConnectionStatisticsAgent::acquire();
ConnectionStatisticsAgentSetStart(this);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief deletes a socket task
///
/// This method will close the underlying socket.
////////////////////////////////////////////////////////////////////////////////
SocketTask::~SocketTask () {
if (TRI_isvalidsocket(_commSocket)) {
TRI_CLOSE_SOCKET(_commSocket);
TRI_invalidatesocket(&_commSocket);
}
if (_writeBuffer != nullptr && ownBuffer) {
delete _writeBuffer;
}
#ifdef TRI_ENABLE_FIGURES
if (_writeBufferStatistics != nullptr) {
TRI_ReleaseRequestStatistics(_writeBufferStatistics);
}
#endif
delete _readBuffer;
ConnectionStatisticsAgentSetEnd(this);
ConnectionStatisticsAgent::release();
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
void SocketTask::setKeepAliveTimeout (double timeout) {
if (keepAliveWatcher != 0 && timeout > 0.0) {
_scheduler->rearmTimer(keepAliveWatcher, timeout);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- protected virtual methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief fills the read buffer
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::fillReadBuffer () {
// reserve some memory for reading
if (_readBuffer->reserve(READ_BLOCK_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {
// out of memory
LOG_TRACE("out of memory");
return false;
}
int nr = TRI_READ_SOCKET(_commSocket, _readBuffer->end(), READ_BLOCK_SIZE, 0);
if (nr > 0) {
_readBuffer->increaseLength(nr);
return true;
}
else if (nr == 0) {
_clientClosed = true;
LOG_TRACE("read returned 0");
return false;
}
else {
if (errno == EINTR) {
return fillReadBuffer();
}
else if (errno != EWOULDBLOCK) {
LOG_TRACE("read failed with %d: %s", (int) errno, strerror(errno));
return false;
}
else {
LOG_TRACE("read would block with %d: %s", (int) errno, strerror(errno));
return true;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief handles a write
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::handleWrite () {
bool callCompletedWriteBuffer = false;
// size_t is unsigned, should never get < 0
size_t len = 0;
if (nullptr != _writeBuffer) {
TRI_ASSERT(_writeBuffer->length() >= writeLength);
len = _writeBuffer->length() - writeLength;
}
int nr = 0;
if (0 < len) {
nr = TRI_WRITE_SOCKET(_commSocket, _writeBuffer->begin() + writeLength, (int) len, 0);
if (nr < 0) {
if (errno == EINTR) {
return handleWrite();
}
else if (errno != EWOULDBLOCK) {
LOG_DEBUG("write failed with %d: %s", (int) errno, strerror(errno));
return false;
}
else {
nr = 0;
}
}
len -= nr;
}
if (len == 0) {
if (nullptr != _writeBuffer && ownBuffer) {
delete _writeBuffer;
}
callCompletedWriteBuffer = true;
}
else {
writeLength += nr;
}
if (callCompletedWriteBuffer) {
completedWriteBuffer();
// rearm timer for keep-alive timeout
// TODO: do we need some lock before we modify the scheduler?
setKeepAliveTimeout(_keepAliveTimeout);
}
if (_clientClosed) {
return false;
}
// we might have a new write buffer or none at all
if (_writeBuffer == nullptr) {
_scheduler->stopSocketEvents(writeWatcher);
}
else {
_scheduler->startSocketEvents(writeWatcher);
}
return true;
}
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief sets an active write buffer
////////////////////////////////////////////////////////////////////////////////
void SocketTask::setWriteBuffer (StringBuffer* buffer,
TRI_request_statistics_t* statistics,
bool ownBuffer) {
bool callCompletedWriteBuffer = false;
#ifdef TRI_ENABLE_FIGURES
_writeBufferStatistics = statistics;
if (_writeBufferStatistics != nullptr) {
_writeBufferStatistics->_writeStart = TRI_StatisticsTime();
_writeBufferStatistics->_sentBytes += buffer->length();
}
#endif
writeLength = 0;
if (buffer->empty()) {
if (ownBuffer) {
delete buffer;
}
callCompletedWriteBuffer = true;
}
else {
if (_writeBuffer != nullptr) {
if (this->ownBuffer) {
delete _writeBuffer;
}
}
_writeBuffer = buffer;
this->ownBuffer = ownBuffer;
}
if (callCompletedWriteBuffer) {
completedWriteBuffer();
}
if (_clientClosed) {
return;
}
// we might have a new write buffer or none at all
TRI_ASSERT(tid == Thread::currentThreadId());
if (_writeBuffer == nullptr) {
_scheduler->stopSocketEvents(writeWatcher);
}
else {
_scheduler->startSocketEvents(writeWatcher);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks for presence of an active write buffer
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::hasWriteBuffer () const {
return _writeBuffer != nullptr;
}
// -----------------------------------------------------------------------------
// --SECTION-- Task methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::setup (Scheduler* scheduler, EventLoop loop) {
#ifdef _WIN32
// ..........................................................................
// The problem we have here is that this opening of the fs handle may fail.
// There is no mechanism to the calling function to report failure.
// ..........................................................................
LOG_TRACE("attempting to convert socket handle to socket descriptor");
if (! TRI_isvalidsocket(_commSocket)) {
LOG_ERROR("In SocketTask::setup could not convert socket handle to socket descriptor -- invalid socket handle");
return false;
}
// For the official version of libev we would do this:
// int res = _open_osfhandle(_commSocket.fileHandle, 0);
// However, this opens a whole lot of problems and in general one should
// never use _open_osfhandle for sockets.
// Therefore, we do the following, although it has the potential to
// lose the higher bits of the socket handle:
int res = (int)_commSocket.fileHandle;
if (res == -1) {
LOG_ERROR("In SocketTask::setup could not convert socket handle to socket descriptor -- _open_osfhandle(...) failed");
res = TRI_CLOSE_SOCKET(_commSocket);
if (res != 0) {
res = WSAGetLastError();
LOG_ERROR("In SocketTask::setup closesocket(...) failed with error code: %d", (int) res);
}
TRI_invalidatesocket(&_commSocket);
return false;
}
_commSocket.fileDescriptor = res;
#endif
this->_scheduler = scheduler;
this->_loop = loop;
watcher = _scheduler->installAsyncEvent(loop, this);
readWatcher = _scheduler->installSocketEvent(loop, EVENT_SOCKET_READ, this, _commSocket);
writeWatcher = _scheduler->installSocketEvent(loop, EVENT_SOCKET_WRITE, this, _commSocket);
if (readWatcher == -1 || writeWatcher == -1) {
return false;
}
// install timer for keep-alive timeout with some high default value
keepAliveWatcher = _scheduler->installTimerEvent(loop, this, 60.0);
// and stop it immediately so it's not actively at the start
_scheduler->clearTimer(keepAliveWatcher);
tid = Thread::currentThreadId();
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
void SocketTask::cleanup () {
if (_scheduler == nullptr) {
LOG_WARNING("In SocketTask::cleanup the scheduler has disappeared -- invalid pointer");
watcher = 0;
keepAliveWatcher = 0;
readWatcher = 0;
writeWatcher = 0;
return;
}
_scheduler->uninstallEvent(watcher);
watcher = 0;
_scheduler->uninstallEvent(keepAliveWatcher);
keepAliveWatcher = 0;
_scheduler->uninstallEvent(readWatcher);
readWatcher = 0;
_scheduler->uninstallEvent(writeWatcher);
writeWatcher = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool SocketTask::handleEvent (EventToken token, EventType revents) {
bool result = true;
if (token == keepAliveWatcher && (revents & EVENT_TIMER)) {
// got a keep-alive timeout
LOG_TRACE("got keep-alive timeout signal, closing connection");
// TODO: do we need some lock before we modify the scheduler?
_scheduler->clearTimer(token);
// this will close the connection and destroy the task
handleTimeout();
return false;
}
if (token == readWatcher && (revents & EVENT_SOCKET_READ)) {
if (keepAliveWatcher != 0) {
// disable timer for keep-alive timeout
_scheduler->clearTimer(keepAliveWatcher);
}
result = handleRead();
}
if (result && ! _clientClosed && token == writeWatcher) {
if (revents & EVENT_SOCKET_WRITE) {
result = handleWrite();
}
}
if (result) {
if (_writeBuffer == nullptr) {
_scheduler->stopSocketEvents(writeWatcher);
}
else {
_scheduler->startSocketEvents(writeWatcher);
}
}
return result;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
// 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 MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/system_error.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <new>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//
MemoryBuffer::~MemoryBuffer() { }
/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
bool RequiresNullTerminator) {
assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
"Buffer is not null terminated!");
BufferStart = BufStart;
BufferEnd = BufEnd;
}
//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//
/// CopyStringRef - Copies contents of a StringRef into a block of memory and
/// null-terminates it.
static void CopyStringRef(char *Memory, StringRef Data) {
memcpy(Memory, Data.data(), Data.size());
Memory[Data.size()] = 0; // Null terminate string.
}
/// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
template <typename T>
static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
bool RequiresNullTerminator) {
char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
CopyStringRef(Mem + sizeof(T), Name);
return new (Mem) T(Buffer, RequiresNullTerminator);
}
namespace {
/// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
class MemoryBufferMem : public MemoryBuffer {
public:
MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
init(InputData.begin(), InputData.end(), RequiresNullTerminator);
}
virtual const char *getBufferIdentifier() const {
// The name is stored after the class itself.
return reinterpret_cast<const char*>(this + 1);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_Malloc;
}
};
}
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that InputData must be a null terminated if RequiresNullTerminator is true!
MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
StringRef BufferName,
bool RequiresNullTerminator) {
return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
RequiresNullTerminator);
}
/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it. This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
StringRef BufferName) {
MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
if (!Buf) return 0;
memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
InputData.size());
return Buf;
}
/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is not initialized. Note that the caller should initialize the
/// memory allocated by this method. The memory is owned by the MemoryBuffer
/// object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
StringRef BufferName) {
// Allocate space for the MemoryBuffer, the data and the name. It is important
// that MemoryBuffer and data are aligned so PointerIntPair works with them.
size_t AlignedStringLen =
RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
sizeof(void*)); // TODO: Is sizeof(void*) enough?
size_t RealLen = AlignedStringLen + Size + 1;
char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
if (!Mem) return 0;
// The name is stored after the class itself.
CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
// The buffer begins after the name and must be aligned.
char *Buf = Mem + AlignedStringLen;
Buf[Size] = 0; // Null terminate buffer.
return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
}
/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
if (!SB) return 0;
memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
return SB;
}
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (Filename == "-")
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (strcmp(Filename, "-") == 0)
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//
namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method. When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBufferMem {
public:
MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
: MemoryBufferMem(Buffer, RequiresNullTerminator) { }
~MemoryBufferMMapFile() {
static int PageSize = sys::Process::GetPageSize();
uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
size_t Size = getBufferSize();
uintptr_t RealStart = Start & ~(PageSize - 1);
size_t RealSize = Size + (Start - RealStart);
sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
RealSize);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_MMap;
}
};
}
error_code MemoryBuffer::getFile(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
// Ensure the path is null terminated.
SmallString<256> PathBuf(Filename.begin(), Filename.end());
return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
RequiresNullTerminator);
}
error_code MemoryBuffer::getFile(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
int OpenFlags = O_RDONLY;
#ifdef O_BINARY
OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
#endif
int FD = ::open(Filename, OpenFlags);
if (FD == -1)
return error_code(errno, posix_category());
error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
0, RequiresNullTerminator);
close(FD);
return ret;
}
static bool shouldUseMmap(int FD,
size_t FileSize,
size_t MapSize,
off_t Offset,
bool RequiresNullTerminator,
int PageSize) {
// We don't use mmap for small files because this can severely fragment our
// address space.
if (MapSize < 4096*4)
return false;
if (!RequiresNullTerminator)
return true;
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
// FIXME: this chunk of code is duplicated, but it avoids a fstat when
// RequiresNullTerminator = false and MapSize != -1.
if (FileSize == size_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
// If we need a null terminator and the end of the map is inside the file,
// we cannot use mmap.
size_t End = Offset + MapSize;
assert(End <= FileSize);
if (End != FileSize)
return false;
// Don't try to map files that are exactly a multiple of the system page size
// if we need a null terminator.
if ((FileSize & (PageSize -1)) == 0)
return false;
return true;
}
error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
OwningPtr<MemoryBuffer> &result,
uint64_t FileSize, uint64_t MapSize,
int64_t Offset,
bool RequiresNullTerminator) {
static int PageSize = sys::Process::GetPageSize();
// Default is to map the full file.
if (MapSize == uint64_t(-1)) {
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
if (FileSize == uint64_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
MapSize = FileSize;
}
if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
PageSize)) {
off_t RealMapOffset = Offset & ~(PageSize - 1);
off_t Delta = Offset - RealMapOffset;
size_t RealMapSize = MapSize + Delta;
if (const char *Pages = sys::Path::MapInFilePages(FD,
RealMapSize,
RealMapOffset)) {
result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
return error_code::success();
}
}
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
if (!Buf) {
// Failed to create a buffer. The only way it can fail is if
// new(std::nothrow) returns 0.
return make_error_code(errc::not_enough_memory);
}
OwningPtr<MemoryBuffer> SB(Buf);
char *BufPtr = const_cast<char*>(SB->getBufferStart());
size_t BytesLeft = MapSize;
#ifndef HAVE_PREAD
if (lseek(FD, Offset, SEEK_SET) == -1)
return error_code(errno, posix_category());
#endif
while (BytesLeft) {
#ifdef HAVE_PREAD
ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
#else
ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
#endif
if (NumRead == -1) {
if (errno == EINTR)
continue;
// Error while reading.
return error_code(errno, posix_category());
}
assert(NumRead != 0 && "fstat reported an invalid file size.");
BytesLeft -= NumRead;
BufPtr += NumRead;
}
result.swap(SB);
return error_code::success();
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
// Read in all of the data from stdin, we cannot mmap stdin.
//
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::Program::ChangeStdinToBinary();
const ssize_t ChunkSize = 4096*4;
SmallString<ChunkSize> Buffer;
ssize_t ReadBytes;
// Read into Buffer until we hit EOF.
do {
Buffer.reserve(Buffer.size() + ChunkSize);
ReadBytes = read(0, Buffer.end(), ChunkSize);
if (ReadBytes == -1) {
if (errno == EINTR) continue;
return error_code(errno, posix_category());
}
Buffer.set_size(Buffer.size() + ReadBytes);
} while (ReadBytes != 0);
result.reset(getMemBufferCopy(Buffer, "<stdin>"));
return error_code::success();
}
<commit_msg>Add a sanity check in MemoryBuffer::getOpenFile() to make sure we don't hang if the passed in FileSize is inaccurate.<commit_after>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
// 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 MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/system_error.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <new>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//
MemoryBuffer::~MemoryBuffer() { }
/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
bool RequiresNullTerminator) {
assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
"Buffer is not null terminated!");
BufferStart = BufStart;
BufferEnd = BufEnd;
}
//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//
/// CopyStringRef - Copies contents of a StringRef into a block of memory and
/// null-terminates it.
static void CopyStringRef(char *Memory, StringRef Data) {
memcpy(Memory, Data.data(), Data.size());
Memory[Data.size()] = 0; // Null terminate string.
}
/// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
template <typename T>
static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
bool RequiresNullTerminator) {
char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
CopyStringRef(Mem + sizeof(T), Name);
return new (Mem) T(Buffer, RequiresNullTerminator);
}
namespace {
/// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
class MemoryBufferMem : public MemoryBuffer {
public:
MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
init(InputData.begin(), InputData.end(), RequiresNullTerminator);
}
virtual const char *getBufferIdentifier() const {
// The name is stored after the class itself.
return reinterpret_cast<const char*>(this + 1);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_Malloc;
}
};
}
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that InputData must be a null terminated if RequiresNullTerminator is true!
MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
StringRef BufferName,
bool RequiresNullTerminator) {
return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
RequiresNullTerminator);
}
/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it. This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
StringRef BufferName) {
MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
if (!Buf) return 0;
memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
InputData.size());
return Buf;
}
/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is not initialized. Note that the caller should initialize the
/// memory allocated by this method. The memory is owned by the MemoryBuffer
/// object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
StringRef BufferName) {
// Allocate space for the MemoryBuffer, the data and the name. It is important
// that MemoryBuffer and data are aligned so PointerIntPair works with them.
size_t AlignedStringLen =
RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
sizeof(void*)); // TODO: Is sizeof(void*) enough?
size_t RealLen = AlignedStringLen + Size + 1;
char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
if (!Mem) return 0;
// The name is stored after the class itself.
CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
// The buffer begins after the name and must be aligned.
char *Buf = Mem + AlignedStringLen;
Buf[Size] = 0; // Null terminate buffer.
return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
}
/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
if (!SB) return 0;
memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
return SB;
}
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (Filename == "-")
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize) {
if (strcmp(Filename, "-") == 0)
return getSTDIN(result);
return getFile(Filename, result, FileSize);
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//
namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method. When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBufferMem {
public:
MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
: MemoryBufferMem(Buffer, RequiresNullTerminator) { }
~MemoryBufferMMapFile() {
static int PageSize = sys::Process::GetPageSize();
uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
size_t Size = getBufferSize();
uintptr_t RealStart = Start & ~(PageSize - 1);
size_t RealSize = Size + (Start - RealStart);
sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
RealSize);
}
virtual BufferKind getBufferKind() const {
return MemoryBuffer_MMap;
}
};
}
error_code MemoryBuffer::getFile(StringRef Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
// Ensure the path is null terminated.
SmallString<256> PathBuf(Filename.begin(), Filename.end());
return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
RequiresNullTerminator);
}
error_code MemoryBuffer::getFile(const char *Filename,
OwningPtr<MemoryBuffer> &result,
int64_t FileSize,
bool RequiresNullTerminator) {
int OpenFlags = O_RDONLY;
#ifdef O_BINARY
OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
#endif
int FD = ::open(Filename, OpenFlags);
if (FD == -1)
return error_code(errno, posix_category());
error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
0, RequiresNullTerminator);
close(FD);
return ret;
}
static bool shouldUseMmap(int FD,
size_t FileSize,
size_t MapSize,
off_t Offset,
bool RequiresNullTerminator,
int PageSize) {
// We don't use mmap for small files because this can severely fragment our
// address space.
if (MapSize < 4096*4)
return false;
if (!RequiresNullTerminator)
return true;
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
// FIXME: this chunk of code is duplicated, but it avoids a fstat when
// RequiresNullTerminator = false and MapSize != -1.
if (FileSize == size_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
// If we need a null terminator and the end of the map is inside the file,
// we cannot use mmap.
size_t End = Offset + MapSize;
assert(End <= FileSize);
if (End != FileSize)
return false;
// Don't try to map files that are exactly a multiple of the system page size
// if we need a null terminator.
if ((FileSize & (PageSize -1)) == 0)
return false;
return true;
}
error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
OwningPtr<MemoryBuffer> &result,
uint64_t FileSize, uint64_t MapSize,
int64_t Offset,
bool RequiresNullTerminator) {
static int PageSize = sys::Process::GetPageSize();
// Default is to map the full file.
if (MapSize == uint64_t(-1)) {
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
if (FileSize == uint64_t(-1)) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
return error_code(errno, posix_category());
}
FileSize = FileInfo.st_size;
}
MapSize = FileSize;
}
if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
PageSize)) {
off_t RealMapOffset = Offset & ~(PageSize - 1);
off_t Delta = Offset - RealMapOffset;
size_t RealMapSize = MapSize + Delta;
if (const char *Pages = sys::Path::MapInFilePages(FD,
RealMapSize,
RealMapOffset)) {
result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
return error_code::success();
}
}
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
if (!Buf) {
// Failed to create a buffer. The only way it can fail is if
// new(std::nothrow) returns 0.
return make_error_code(errc::not_enough_memory);
}
OwningPtr<MemoryBuffer> SB(Buf);
char *BufPtr = const_cast<char*>(SB->getBufferStart());
size_t BytesLeft = MapSize;
#ifndef HAVE_PREAD
if (lseek(FD, Offset, SEEK_SET) == -1)
return error_code(errno, posix_category());
#endif
while (BytesLeft) {
#ifdef HAVE_PREAD
ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
#else
ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
#endif
if (NumRead == -1) {
if (errno == EINTR)
continue;
// Error while reading.
return error_code(errno, posix_category());
}
if (NumRead == 0) {
assert(0 && "We got inaccurate FileSize value or fstat reported an "
"invalid file size.");
break;
}
BytesLeft -= NumRead;
BufPtr += NumRead;
}
result.swap(SB);
return error_code::success();
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
// Read in all of the data from stdin, we cannot mmap stdin.
//
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::Program::ChangeStdinToBinary();
const ssize_t ChunkSize = 4096*4;
SmallString<ChunkSize> Buffer;
ssize_t ReadBytes;
// Read into Buffer until we hit EOF.
do {
Buffer.reserve(Buffer.size() + ChunkSize);
ReadBytes = read(0, Buffer.end(), ChunkSize);
if (ReadBytes == -1) {
if (errno == EINTR) continue;
return error_code(errno, posix_category());
}
Buffer.set_size(Buffer.size() + ReadBytes);
} while (ReadBytes != 0);
result.reset(getMemBufferCopy(Buffer, "<stdin>"));
return error_code::success();
}
<|endoftext|> |
<commit_before>//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the general parts of a Target machine.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
//---------------------------------------------------------------------------
// Command-line options that tend to be useful on more than one back-end.
//
namespace llvm {
bool LessPreciseFPMADOption;
bool PrintMachineCode;
bool NoFramePointerElim;
bool NoFramePointerElimNonLeaf;
bool NoExcessFPPrecision;
bool UnsafeFPMath;
bool FiniteOnlyFPMathOption;
bool HonorSignDependentRoundingFPMathOption;
bool UseSoftFloat;
FloatABI::ABIType FloatABIType;
bool NoImplicitFloat;
bool NoZerosInBSS;
bool JITExceptionHandling;
bool JITEmitDebugInfo;
bool JITEmitDebugInfoToDisk;
bool UnwindTablesMandatory;
Reloc::Model RelocationModel;
CodeModel::Model CMModel;
bool GuaranteedTailCallOpt;
unsigned StackAlignment;
bool RealignStack;
bool DisableJumpTables;
bool StrongPHIElim;
bool AsmVerbosityDefault(false);
}
static cl::opt<bool, true>
PrintCode("print-machineinstrs",
cl::desc("Print generated machine code"),
cl::location(PrintMachineCode), cl::init(false));
static cl::opt<bool, true>
DisableFPElim("disable-fp-elim",
cl::desc("Disable frame pointer elimination optimization"),
cl::location(NoFramePointerElim),
cl::init(false));
static cl::opt<bool, true>
DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
cl::location(NoFramePointerElimNonLeaf),
cl::init(false));
static cl::opt<bool, true>
DisableExcessPrecision("disable-excess-fp-precision",
cl::desc("Disable optimizations that may increase FP precision"),
cl::location(NoExcessFPPrecision),
cl::init(false));
static cl::opt<bool, true>
EnableFPMAD("enable-fp-mad",
cl::desc("Enable less precise MAD instructions to be generated"),
cl::location(LessPreciseFPMADOption),
cl::init(false));
static cl::opt<bool, true>
EnableUnsafeFPMath("enable-unsafe-fp-math",
cl::desc("Enable optimizations that may decrease FP precision"),
cl::location(UnsafeFPMath),
cl::init(false));
static cl::opt<bool, true>
EnableFiniteOnlyFPMath("enable-finite-only-fp-math",
cl::desc("Enable optimizations that assumes non- NaNs / +-Infs"),
cl::location(FiniteOnlyFPMathOption),
cl::init(false));
static cl::opt<bool, true>
EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
cl::Hidden,
cl::desc("Force codegen to assume rounding mode can change dynamically"),
cl::location(HonorSignDependentRoundingFPMathOption),
cl::init(false));
static cl::opt<bool, true>
GenerateSoftFloatCalls("soft-float",
cl::desc("Generate software floating point library calls"),
cl::location(UseSoftFloat),
cl::init(false));
static cl::opt<llvm::FloatABI::ABIType, true>
FloatABIForCalls("float-abi",
cl::desc("Choose float ABI type"),
cl::location(FloatABIType),
cl::init(FloatABI::Default),
cl::values(
clEnumValN(FloatABI::Default, "default",
"Target default float ABI type"),
clEnumValN(FloatABI::Soft, "soft",
"Soft float ABI (implied by -soft-float)"),
clEnumValN(FloatABI::Hard, "hard",
"Hard float ABI (uses FP registers)"),
clEnumValEnd));
static cl::opt<bool, true>
DontPlaceZerosInBSS("nozero-initialized-in-bss",
cl::desc("Don't place zero-initialized symbols into bss section"),
cl::location(NoZerosInBSS),
cl::init(false));
static cl::opt<bool, true>
EnableJITExceptionHandling("jit-enable-eh",
cl::desc("Emit exception handling information"),
cl::location(JITExceptionHandling),
cl::init(false));
// In debug builds, make this default to true.
#ifdef NDEBUG
#define EMIT_DEBUG false
#else
#define EMIT_DEBUG true
#endif
static cl::opt<bool, true>
EmitJitDebugInfo("jit-emit-debug",
cl::desc("Emit debug information to debugger"),
cl::location(JITEmitDebugInfo),
cl::init(EMIT_DEBUG));
#undef EMIT_DEBUG
static cl::opt<bool, true>
EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
cl::Hidden,
cl::desc("Emit debug info objfiles to disk"),
cl::location(JITEmitDebugInfoToDisk),
cl::init(false));
static cl::opt<bool, true>
EnableUnwindTables("unwind-tables",
cl::desc("Generate unwinding tables for all functions"),
cl::location(UnwindTablesMandatory),
cl::init(false));
static cl::opt<llvm::Reloc::Model, true>
DefRelocationModel("relocation-model",
cl::desc("Choose relocation model"),
cl::location(RelocationModel),
cl::init(Reloc::Default),
cl::values(
clEnumValN(Reloc::Default, "default",
"Target default relocation model"),
clEnumValN(Reloc::Static, "static",
"Non-relocatable code"),
clEnumValN(Reloc::PIC_, "pic",
"Fully relocatable, position independent code"),
clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
"Relocatable external references, non-relocatable code"),
clEnumValEnd));
static cl::opt<llvm::CodeModel::Model, true>
DefCodeModel("code-model",
cl::desc("Choose code model"),
cl::location(CMModel),
cl::init(CodeModel::Default),
cl::values(
clEnumValN(CodeModel::Default, "default",
"Target default code model"),
clEnumValN(CodeModel::Small, "small",
"Small code model"),
clEnumValN(CodeModel::Kernel, "kernel",
"Kernel code model"),
clEnumValN(CodeModel::Medium, "medium",
"Medium code model"),
clEnumValN(CodeModel::Large, "large",
"Large code model"),
clEnumValEnd));
static cl::opt<bool, true>
EnableGuaranteedTailCallOpt("tailcallopt",
cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
cl::location(GuaranteedTailCallOpt),
cl::init(false));
static cl::opt<unsigned, true>
OverrideStackAlignment("stack-alignment",
cl::desc("Override default stack alignment"),
cl::location(StackAlignment),
cl::init(0));
static cl::opt<bool, true>
EnableRealignStack("realign-stack",
cl::desc("Realign stack if needed"),
cl::location(RealignStack),
cl::init(true));
static cl::opt<bool, true>
DisableSwitchTables(cl::Hidden, "disable-jump-tables",
cl::desc("Do not generate jump tables."),
cl::location(DisableJumpTables),
cl::init(false));
static cl::opt<bool, true>
EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
cl::desc("Use strong PHI elimination."),
cl::location(StrongPHIElim),
cl::init(false));
static cl::opt<bool>
DataSections("fdata-sections",
cl::desc("Emit data into separate sections"),
cl::init(false));
static cl::opt<bool>
FunctionSections("ffunction-sections",
cl::desc("Emit functions into separate sections"),
cl::init(false));
//---------------------------------------------------------------------------
// TargetMachine Class
//
TargetMachine::TargetMachine(const Target &T)
: TheTarget(T), AsmInfo(0) {
// Typically it will be subtargets that will adjust FloatABIType from Default
// to Soft or Hard.
if (UseSoftFloat)
FloatABIType = FloatABI::Soft;
}
TargetMachine::~TargetMachine() {
delete AsmInfo;
}
/// getRelocationModel - Returns the code generation relocation model. The
/// choices are static, PIC, and dynamic-no-pic, and target default.
Reloc::Model TargetMachine::getRelocationModel() {
return RelocationModel;
}
/// setRelocationModel - Sets the code generation relocation model.
void TargetMachine::setRelocationModel(Reloc::Model Model) {
RelocationModel = Model;
}
/// getCodeModel - Returns the code model. The choices are small, kernel,
/// medium, large, and target default.
CodeModel::Model TargetMachine::getCodeModel() {
return CMModel;
}
/// setCodeModel - Sets the code model.
void TargetMachine::setCodeModel(CodeModel::Model Model) {
CMModel = Model;
}
bool TargetMachine::getAsmVerbosityDefault() {
return AsmVerbosityDefault;
}
void TargetMachine::setAsmVerbosityDefault(bool V) {
AsmVerbosityDefault = V;
}
bool TargetMachine::getFunctionSections() {
return FunctionSections;
}
bool TargetMachine::getDataSections() {
return DataSections;
}
void TargetMachine::setFunctionSections(bool V) {
FunctionSections = V;
}
void TargetMachine::setDataSections(bool V) {
DataSections = V;
}
namespace llvm {
/// DisableFramePointerElim - This returns true if frame pointer elimination
/// optimization should be disabled for the given machine function.
bool DisableFramePointerElim(const MachineFunction &MF) {
// Check to see if we should eliminate non-leaf frame pointers and then
// check to see if we should eliminate all frame pointers.
if (NoFramePointerElimNonLeaf) {
const MachineFrameInfo *MFI = MF.getFrameInfo();
return MFI->hasCalls();
}
return NoFramePointerElim;
}
/// LessPreciseFPMAD - This flag return true when -enable-fp-mad option
/// is specified on the command line. When this flag is off(default), the
/// code generator is not allowed to generate mad (multiply add) if the
/// result is "less precise" than doing those operations individually.
bool LessPreciseFPMAD() { return UnsafeFPMath || LessPreciseFPMADOption; }
/// FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math
/// option is specified on the command line. If this returns false (default),
/// the code generator is not allowed to assume that FP arithmetic arguments
/// and results are never NaNs or +-Infs.
bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; }
/// HonorSignDependentRoundingFPMath - Return true if the codegen must assume
/// that the rounding mode of the FPU can change from its default.
bool HonorSignDependentRoundingFPMath() {
return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
}
}
<commit_msg>Don't eliminate frame pointers from leaf functions if "--disable-fp-elim" is specified.<commit_after>//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the general parts of a Target machine.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
//---------------------------------------------------------------------------
// Command-line options that tend to be useful on more than one back-end.
//
namespace llvm {
bool LessPreciseFPMADOption;
bool PrintMachineCode;
bool NoFramePointerElim;
bool NoFramePointerElimNonLeaf;
bool NoExcessFPPrecision;
bool UnsafeFPMath;
bool FiniteOnlyFPMathOption;
bool HonorSignDependentRoundingFPMathOption;
bool UseSoftFloat;
FloatABI::ABIType FloatABIType;
bool NoImplicitFloat;
bool NoZerosInBSS;
bool JITExceptionHandling;
bool JITEmitDebugInfo;
bool JITEmitDebugInfoToDisk;
bool UnwindTablesMandatory;
Reloc::Model RelocationModel;
CodeModel::Model CMModel;
bool GuaranteedTailCallOpt;
unsigned StackAlignment;
bool RealignStack;
bool DisableJumpTables;
bool StrongPHIElim;
bool AsmVerbosityDefault(false);
}
static cl::opt<bool, true>
PrintCode("print-machineinstrs",
cl::desc("Print generated machine code"),
cl::location(PrintMachineCode), cl::init(false));
static cl::opt<bool, true>
DisableFPElim("disable-fp-elim",
cl::desc("Disable frame pointer elimination optimization"),
cl::location(NoFramePointerElim),
cl::init(false));
static cl::opt<bool, true>
DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
cl::location(NoFramePointerElimNonLeaf),
cl::init(false));
static cl::opt<bool, true>
DisableExcessPrecision("disable-excess-fp-precision",
cl::desc("Disable optimizations that may increase FP precision"),
cl::location(NoExcessFPPrecision),
cl::init(false));
static cl::opt<bool, true>
EnableFPMAD("enable-fp-mad",
cl::desc("Enable less precise MAD instructions to be generated"),
cl::location(LessPreciseFPMADOption),
cl::init(false));
static cl::opt<bool, true>
EnableUnsafeFPMath("enable-unsafe-fp-math",
cl::desc("Enable optimizations that may decrease FP precision"),
cl::location(UnsafeFPMath),
cl::init(false));
static cl::opt<bool, true>
EnableFiniteOnlyFPMath("enable-finite-only-fp-math",
cl::desc("Enable optimizations that assumes non- NaNs / +-Infs"),
cl::location(FiniteOnlyFPMathOption),
cl::init(false));
static cl::opt<bool, true>
EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
cl::Hidden,
cl::desc("Force codegen to assume rounding mode can change dynamically"),
cl::location(HonorSignDependentRoundingFPMathOption),
cl::init(false));
static cl::opt<bool, true>
GenerateSoftFloatCalls("soft-float",
cl::desc("Generate software floating point library calls"),
cl::location(UseSoftFloat),
cl::init(false));
static cl::opt<llvm::FloatABI::ABIType, true>
FloatABIForCalls("float-abi",
cl::desc("Choose float ABI type"),
cl::location(FloatABIType),
cl::init(FloatABI::Default),
cl::values(
clEnumValN(FloatABI::Default, "default",
"Target default float ABI type"),
clEnumValN(FloatABI::Soft, "soft",
"Soft float ABI (implied by -soft-float)"),
clEnumValN(FloatABI::Hard, "hard",
"Hard float ABI (uses FP registers)"),
clEnumValEnd));
static cl::opt<bool, true>
DontPlaceZerosInBSS("nozero-initialized-in-bss",
cl::desc("Don't place zero-initialized symbols into bss section"),
cl::location(NoZerosInBSS),
cl::init(false));
static cl::opt<bool, true>
EnableJITExceptionHandling("jit-enable-eh",
cl::desc("Emit exception handling information"),
cl::location(JITExceptionHandling),
cl::init(false));
// In debug builds, make this default to true.
#ifdef NDEBUG
#define EMIT_DEBUG false
#else
#define EMIT_DEBUG true
#endif
static cl::opt<bool, true>
EmitJitDebugInfo("jit-emit-debug",
cl::desc("Emit debug information to debugger"),
cl::location(JITEmitDebugInfo),
cl::init(EMIT_DEBUG));
#undef EMIT_DEBUG
static cl::opt<bool, true>
EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
cl::Hidden,
cl::desc("Emit debug info objfiles to disk"),
cl::location(JITEmitDebugInfoToDisk),
cl::init(false));
static cl::opt<bool, true>
EnableUnwindTables("unwind-tables",
cl::desc("Generate unwinding tables for all functions"),
cl::location(UnwindTablesMandatory),
cl::init(false));
static cl::opt<llvm::Reloc::Model, true>
DefRelocationModel("relocation-model",
cl::desc("Choose relocation model"),
cl::location(RelocationModel),
cl::init(Reloc::Default),
cl::values(
clEnumValN(Reloc::Default, "default",
"Target default relocation model"),
clEnumValN(Reloc::Static, "static",
"Non-relocatable code"),
clEnumValN(Reloc::PIC_, "pic",
"Fully relocatable, position independent code"),
clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
"Relocatable external references, non-relocatable code"),
clEnumValEnd));
static cl::opt<llvm::CodeModel::Model, true>
DefCodeModel("code-model",
cl::desc("Choose code model"),
cl::location(CMModel),
cl::init(CodeModel::Default),
cl::values(
clEnumValN(CodeModel::Default, "default",
"Target default code model"),
clEnumValN(CodeModel::Small, "small",
"Small code model"),
clEnumValN(CodeModel::Kernel, "kernel",
"Kernel code model"),
clEnumValN(CodeModel::Medium, "medium",
"Medium code model"),
clEnumValN(CodeModel::Large, "large",
"Large code model"),
clEnumValEnd));
static cl::opt<bool, true>
EnableGuaranteedTailCallOpt("tailcallopt",
cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
cl::location(GuaranteedTailCallOpt),
cl::init(false));
static cl::opt<unsigned, true>
OverrideStackAlignment("stack-alignment",
cl::desc("Override default stack alignment"),
cl::location(StackAlignment),
cl::init(0));
static cl::opt<bool, true>
EnableRealignStack("realign-stack",
cl::desc("Realign stack if needed"),
cl::location(RealignStack),
cl::init(true));
static cl::opt<bool, true>
DisableSwitchTables(cl::Hidden, "disable-jump-tables",
cl::desc("Do not generate jump tables."),
cl::location(DisableJumpTables),
cl::init(false));
static cl::opt<bool, true>
EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
cl::desc("Use strong PHI elimination."),
cl::location(StrongPHIElim),
cl::init(false));
static cl::opt<bool>
DataSections("fdata-sections",
cl::desc("Emit data into separate sections"),
cl::init(false));
static cl::opt<bool>
FunctionSections("ffunction-sections",
cl::desc("Emit functions into separate sections"),
cl::init(false));
//---------------------------------------------------------------------------
// TargetMachine Class
//
TargetMachine::TargetMachine(const Target &T)
: TheTarget(T), AsmInfo(0) {
// Typically it will be subtargets that will adjust FloatABIType from Default
// to Soft or Hard.
if (UseSoftFloat)
FloatABIType = FloatABI::Soft;
}
TargetMachine::~TargetMachine() {
delete AsmInfo;
}
/// getRelocationModel - Returns the code generation relocation model. The
/// choices are static, PIC, and dynamic-no-pic, and target default.
Reloc::Model TargetMachine::getRelocationModel() {
return RelocationModel;
}
/// setRelocationModel - Sets the code generation relocation model.
void TargetMachine::setRelocationModel(Reloc::Model Model) {
RelocationModel = Model;
}
/// getCodeModel - Returns the code model. The choices are small, kernel,
/// medium, large, and target default.
CodeModel::Model TargetMachine::getCodeModel() {
return CMModel;
}
/// setCodeModel - Sets the code model.
void TargetMachine::setCodeModel(CodeModel::Model Model) {
CMModel = Model;
}
bool TargetMachine::getAsmVerbosityDefault() {
return AsmVerbosityDefault;
}
void TargetMachine::setAsmVerbosityDefault(bool V) {
AsmVerbosityDefault = V;
}
bool TargetMachine::getFunctionSections() {
return FunctionSections;
}
bool TargetMachine::getDataSections() {
return DataSections;
}
void TargetMachine::setFunctionSections(bool V) {
FunctionSections = V;
}
void TargetMachine::setDataSections(bool V) {
DataSections = V;
}
namespace llvm {
/// DisableFramePointerElim - This returns true if frame pointer elimination
/// optimization should be disabled for the given machine function.
bool DisableFramePointerElim(const MachineFunction &MF) {
// Check to see if we should eliminate non-leaf frame pointers and then
// check to see if we should eliminate all frame pointers.
if (NoFramePointerElimNonLeaf && !NoFramePointerElim) {
const MachineFrameInfo *MFI = MF.getFrameInfo();
return MFI->hasCalls();
}
return NoFramePointerElim;
}
/// LessPreciseFPMAD - This flag return true when -enable-fp-mad option
/// is specified on the command line. When this flag is off(default), the
/// code generator is not allowed to generate mad (multiply add) if the
/// result is "less precise" than doing those operations individually.
bool LessPreciseFPMAD() { return UnsafeFPMath || LessPreciseFPMADOption; }
/// FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math
/// option is specified on the command line. If this returns false (default),
/// the code generator is not allowed to assume that FP arithmetic arguments
/// and results are never NaNs or +-Infs.
bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; }
/// HonorSignDependentRoundingFPMath - Return true if the codegen must assume
/// that the rounding mode of the FPU can change from its default.
bool HonorSignDependentRoundingFPMath() {
return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
}
}
<|endoftext|> |
<commit_before>#include "GraphicsRendererSystem.h"
#include <RenderInterface.h>
#include "GraphicsBackendSystem.h"
#include <GraphicsWrapper.h>
#include <RenderStateEnums.h>
#include "ShadowSystem.h"
#include <GPUTimer.h>
#include <AntTweakBarWrapper.h>
#include "ParticleRenderSystem.h"
#include "ClientStateSystem.h"
#include "MenuSystem.h"
#include "TimerSystem.h"
GraphicsRendererSystem::GraphicsRendererSystem(GraphicsBackendSystem* p_graphicsBackend,
ShadowSystem* p_shadowSystem,
RenderInterface* p_mesh,
RenderInterface* p_libRocket,
RenderInterface* p_particle,
RenderInterface* p_antTweakBar,
RenderInterface* p_light)
: EntitySystem(
SystemType::GraphicsRendererSystem){
m_backend = p_graphicsBackend;
m_shadowSystem = p_shadowSystem;
m_meshRenderer = p_mesh;
m_libRocketRenderSystem = p_libRocket;
m_particleRenderSystem = p_particle;
m_antTweakBarSystem = p_antTweakBar;
m_lightRenderSystem = p_light;
m_shouldRender = true;
m_enteredIngamePreviousFrame = false;
m_activeShadows = new int[MAXSHADOWS];
m_shadowViewProjections = new AglMatrix[MAXSHADOWS];
m_profiles.push_back(GPUTimerProfile("MESH"));
m_profiles.push_back(GPUTimerProfile("LIGH"));
m_profiles.push_back(GPUTimerProfile("SSAO"));
m_profiles.push_back(GPUTimerProfile("DOF"));
m_profiles.push_back(GPUTimerProfile("COMP"));
m_profiles.push_back(GPUTimerProfile("PART"));
m_profiles.push_back(GPUTimerProfile("GUI"));
m_profiles.push_back(GPUTimerProfile("TOTAL"));
clearShadowStuf();
}
GraphicsRendererSystem::~GraphicsRendererSystem(){
delete[] m_shadowViewProjections;
delete[] m_activeShadows;
}
void GraphicsRendererSystem::initialize(){
for (unsigned int i=0;i < NUMRENDERINGPASSES; i++)
{
string variableName = m_profiles[i].profile;
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(
AntTweakBarWrapper::MEASUREMENT,
variableName.c_str(),TwType::TW_TYPE_DOUBLE,
&m_profiles[i].renderingTime,"group=GPU");
variableName +=" Spike";
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(
AntTweakBarWrapper::MEASUREMENT,
variableName.c_str(),TwType::TW_TYPE_DOUBLE,
&m_profiles[i].renderingSpike,"group='GPU Extra'");
variableName = m_profiles[i].profile;
variableName += " Avg";
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(
AntTweakBarWrapper::MEASUREMENT,
variableName.c_str(),TwType::TW_TYPE_DOUBLE,
&m_profiles[i].renderingAverage,"group='GPU Extra'");
m_backend->getGfxWrapper()->getGPUTimer()->addProfile(m_profiles[i].profile);
}
}
void GraphicsRendererSystem::process(){
m_wrapper = m_backend->getGfxWrapper();
auto timerSystem = static_cast<TimerSystem*>(m_world->getSystem(SystemType::TimerSystem));
if(timerSystem->checkTimeInterval(TimerIntervals::EverySecond)){
for (unsigned int i= 0; i < NUMRENDERINGPASSES; i++)
{
m_profiles[i].calculateAvarage();
}
}
auto gameState = static_cast<ClientStateSystem*>(
m_world->getSystem(SystemType::ClientStateSystem));
if( m_shouldRender){
renderTheScene();
}
if(m_enteredIngamePreviousFrame){
auto menuSystem = static_cast<MenuSystem*>(m_world->getSystem(SystemType::MenuSystem));
menuSystem->endLoadingState();
m_shouldRender = true;
m_enteredIngamePreviousFrame = false;
}
if(!m_shouldRender && gameState->getStateDelta(GameStates::INGAME) == EnumGameDelta::NOTCHANGED){
m_enteredIngamePreviousFrame = true;
}
else if(gameState->getStateDelta(GameStates::LOADING) == EnumGameDelta::EXITTHISFRAME){
m_shouldRender = false;
}
}
void GraphicsRendererSystem::renderTheScene()
{
/*
//Shadows
//m_wrapper->getGPUTimer()->Start(m_profiles[SHADOW].profile);
clearShadowStuf();
//Fill the shadow view projections
for (unsigned int i = 0; i < m_shadowSystem->getNumberOfShadowCameras(); i++){
m_activeShadows[m_shadowSystem->getShadowIdx(i)] = 1;
m_shadowViewProjections[m_shadowSystem->getShadowIdx(i)] =
m_shadowSystem->getViewProjection(i);
}
*/
/*
initShadowPass();
for(unsigned int i = 0; i < MAXSHADOWS; i++){
if(m_activeShadows[i] != -1){
m_wrapper->setShadowMapAsRenderTarget(i);
//m_wrapper->setActiveShadow(i);
m_meshRenderer->render();
}
}
endShadowPass();
*/
//m_wrapper->getGPUTimer()->Stop(m_profiles[SHADOW].profile);
m_wrapper->clearRenderTargets();
// Meshes
m_wrapper->getGPUTimer()->Start(m_profiles[MESH].profile);
initMeshPass();
m_meshRenderer->render();
endMeshPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[MESH].profile);
// Lights
m_wrapper->getGPUTimer()->Start(m_profiles[LIGHT].profile);
initLightPass();
m_lightRenderSystem->render();
endLightPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[LIGHT].profile);
//SSAO
m_wrapper->getGPUTimer()->Start(m_profiles[SSAO].profile);
beginSsao();
m_wrapper->generateSsao();
endSsao();
m_wrapper->getGPUTimer()->Stop(m_profiles[SSAO].profile);
// DoF generation pass
m_wrapper->getGPUTimer()->Start(m_profiles[DOF].profile);
beginDofGenerationPass();
m_wrapper->generateDof();
endDofGenerationPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[DOF].profile);
//Compose
m_wrapper->getGPUTimer()->Start(m_profiles[COMPOSE].profile);
initComposePass();
m_wrapper->renderComposeStage();
endComposePass();
m_wrapper->getGPUTimer()->Stop(m_profiles[COMPOSE].profile);
//Particles
m_wrapper->getGPUTimer()->Start(m_profiles[PARTICLE].profile);
initParticlePass();
//renderParticles();
endParticlePass();
m_wrapper->getGPUTimer()->Stop(m_profiles[PARTICLE].profile);
//GUI
m_wrapper->getGPUTimer()->Start(m_profiles[GUI].profile);
initGUIPass();
m_libRocketRenderSystem->render();
m_antTweakBarSystem->render();
endGUIPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[GUI].profile);
flipBackbuffer();
updateTimers();
}
void GraphicsRendererSystem::initShadowPass(){
m_wrapper->setRasterizerStateSettings(RasterizerState::FILLED_CW_FRONTCULL);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
//m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
m_wrapper->setViewportToShadowMapSize();
m_wrapper->setRenderingShadows();
m_wrapper->setShadowViewProjections(m_shadowViewProjections);
}
void GraphicsRendererSystem::endShadowPass(){
m_wrapper->resetViewportToStdSize();
m_wrapper->stopedRenderingShadows();
//m_wrapper->unmapPerShadowBuffer();
}
void GraphicsRendererSystem::initMeshPass(){
m_wrapper->mapSceneInfo();
m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
//m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
m_wrapper->setBaseRenderTargets();
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
}
void GraphicsRendererSystem::endMeshPass(){
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
}
void GraphicsRendererSystem::initLightPass(){
m_wrapper->setRasterizerStateSettings(
//RasterizerState::WIREFRAME_NOCULL, false); // For debug /ML
RasterizerState::FILLED_CW_FRONTCULL, false);
m_wrapper->setBlendStateSettings(BlendState::LIGHT);
m_wrapper->setLightRenderTargets();
//m_wrapper->mapDeferredBaseToShader();
m_wrapper->mapDepthAndNormal();
//m_wrapper->mapShadows( m_activeShadows );
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
}
void GraphicsRendererSystem::endLightPass(){
m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
}
void GraphicsRendererSystem::beginSsao()
{
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP);
m_wrapper->setBlendStateSettings(BlendState::SSAO);
m_wrapper->setRasterizerStateSettings(
RasterizerState::FILLED_NOCULL_NOCLIP, false);
}
void GraphicsRendererSystem::endSsao()
{
m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
m_wrapper->unmapDepthAndNormal();
//m_wrapper->unmapShadows(m_activeShadows);
}
void GraphicsRendererSystem::beginDofGenerationPass()
{
m_wrapper->setViewportToLowRes();
m_wrapper->setPrimitiveTopology( PrimitiveTopology::TRIANGLESTRIP );
m_wrapper->setBlendStateSettings( BlendState::OVERWRITE );
m_wrapper->setDofRenderTargets();
//m_wrapper->setComposedRenderTargetWithNoDepthStencil();
m_wrapper->mapGbuffers();
}
void GraphicsRendererSystem::endDofGenerationPass()
{
m_wrapper->unmapGbuffers();
m_wrapper->resetViewportToStdSize();
}
void GraphicsRendererSystem::initComposePass()
{
m_wrapper->setRasterizerStateSettings(
RasterizerState::DEFAULT, false);
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP);
m_wrapper->setComposedRenderTargetWithNoDepthStencil();
m_wrapper->mapGbuffers();
m_wrapper->mapDofBuffers();
m_wrapper->mapDepth();
}
void GraphicsRendererSystem::endComposePass()
{
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
//m_wrapper->unmapVariousStagesAfterCompose();
m_wrapper->unmapDofBuffers();
m_wrapper->unmapGbuffers();
m_wrapper->unmapDepth();
}
void GraphicsRendererSystem::initParticlePass(){
m_wrapper->setParticleRenderState();
//m_wrapper->setBlendStateSettings(BlendState::PARTICLE);
m_wrapper->setBlendStateSettings(BlendState::ADDITIVE);
m_wrapper->setPrimitiveTopology(PrimitiveTopology::POINTLIST);
}
void GraphicsRendererSystem::renderParticles()
{
// A ugly way to be able to call the different rendering functions. Needs refactoring /ML.
ParticleRenderSystem* psRender = static_cast<ParticleRenderSystem*>( m_particleRenderSystem );
for( int i=0; i<AglParticleSystemHeader::AglBlendMode_CNT; i++ ) {
for( int j=0; j<AglParticleSystemHeader::AglRasterizerMode_CNT; j++ )
{
AglParticleSystemHeader::AglBlendMode blend = (AglParticleSystemHeader::AglBlendMode)i;
AglParticleSystemHeader::AglRasterizerMode rast = (AglParticleSystemHeader::AglRasterizerMode)j;
m_wrapper->setRasterizerStateSettings( psRender->rasterizerStateFromAglRasterizerMode(rast) );
m_wrapper->setBlendStateSettings( psRender->blendStateFromAglBlendMode(blend) );
psRender->render( blend, rast );
}
}
}
void GraphicsRendererSystem::endParticlePass(){
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
m_wrapper->setComposedRenderTargetWithNoDepthStencil();
}
void GraphicsRendererSystem::initGUIPass(){
m_wrapper->setBlendStateSettings(BlendState::ALPHA);
}
void GraphicsRendererSystem::endGUIPass(){
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
}
void GraphicsRendererSystem::flipBackbuffer(){
m_wrapper->flipBackBuffer();
}
void GraphicsRendererSystem::clearShadowStuf()
{
for(int i = 0; i < MAXSHADOWS; i++){
m_activeShadows[i] = -1;
m_shadowViewProjections[i] = AglMatrix::identityMatrix();
}
}
void GraphicsRendererSystem::updateTimers()
{
double total = 0;
GPUTimer* timer = m_wrapper->getGPUTimer();
for(unsigned int i = 0; i < NUMRENDERINGPASSES-1; i++){
m_profiles[i].pushNewTime(timer->getTheTimeAndReset(m_profiles[i].profile));
total += m_profiles[i].renderingTime;
}
m_profiles[TOTAL].pushNewTime(total);
m_wrapper->getGPUTimer()->tick();
}<commit_msg>Particle systems now visible again<commit_after>#include "GraphicsRendererSystem.h"
#include <RenderInterface.h>
#include "GraphicsBackendSystem.h"
#include <GraphicsWrapper.h>
#include <RenderStateEnums.h>
#include "ShadowSystem.h"
#include <GPUTimer.h>
#include <AntTweakBarWrapper.h>
#include "ParticleRenderSystem.h"
#include "ClientStateSystem.h"
#include "MenuSystem.h"
#include "TimerSystem.h"
GraphicsRendererSystem::GraphicsRendererSystem(GraphicsBackendSystem* p_graphicsBackend,
ShadowSystem* p_shadowSystem,
RenderInterface* p_mesh,
RenderInterface* p_libRocket,
RenderInterface* p_particle,
RenderInterface* p_antTweakBar,
RenderInterface* p_light)
: EntitySystem(
SystemType::GraphicsRendererSystem){
m_backend = p_graphicsBackend;
m_shadowSystem = p_shadowSystem;
m_meshRenderer = p_mesh;
m_libRocketRenderSystem = p_libRocket;
m_particleRenderSystem = p_particle;
m_antTweakBarSystem = p_antTweakBar;
m_lightRenderSystem = p_light;
m_shouldRender = true;
m_enteredIngamePreviousFrame = false;
m_activeShadows = new int[MAXSHADOWS];
m_shadowViewProjections = new AglMatrix[MAXSHADOWS];
m_profiles.push_back(GPUTimerProfile("MESH"));
m_profiles.push_back(GPUTimerProfile("LIGH"));
m_profiles.push_back(GPUTimerProfile("SSAO"));
m_profiles.push_back(GPUTimerProfile("DOF"));
m_profiles.push_back(GPUTimerProfile("COMP"));
m_profiles.push_back(GPUTimerProfile("PART"));
m_profiles.push_back(GPUTimerProfile("GUI"));
m_profiles.push_back(GPUTimerProfile("TOTAL"));
clearShadowStuf();
}
GraphicsRendererSystem::~GraphicsRendererSystem(){
delete[] m_shadowViewProjections;
delete[] m_activeShadows;
}
void GraphicsRendererSystem::initialize(){
for (unsigned int i=0;i < NUMRENDERINGPASSES; i++)
{
string variableName = m_profiles[i].profile;
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(
AntTweakBarWrapper::MEASUREMENT,
variableName.c_str(),TwType::TW_TYPE_DOUBLE,
&m_profiles[i].renderingTime,"group=GPU");
variableName +=" Spike";
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(
AntTweakBarWrapper::MEASUREMENT,
variableName.c_str(),TwType::TW_TYPE_DOUBLE,
&m_profiles[i].renderingSpike,"group='GPU Extra'");
variableName = m_profiles[i].profile;
variableName += " Avg";
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(
AntTweakBarWrapper::MEASUREMENT,
variableName.c_str(),TwType::TW_TYPE_DOUBLE,
&m_profiles[i].renderingAverage,"group='GPU Extra'");
m_backend->getGfxWrapper()->getGPUTimer()->addProfile(m_profiles[i].profile);
}
}
void GraphicsRendererSystem::process(){
m_wrapper = m_backend->getGfxWrapper();
auto timerSystem = static_cast<TimerSystem*>(m_world->getSystem(SystemType::TimerSystem));
if(timerSystem->checkTimeInterval(TimerIntervals::EverySecond)){
for (unsigned int i= 0; i < NUMRENDERINGPASSES; i++)
{
m_profiles[i].calculateAvarage();
}
}
auto gameState = static_cast<ClientStateSystem*>(
m_world->getSystem(SystemType::ClientStateSystem));
if( m_shouldRender){
renderTheScene();
}
if(m_enteredIngamePreviousFrame){
auto menuSystem = static_cast<MenuSystem*>(m_world->getSystem(SystemType::MenuSystem));
menuSystem->endLoadingState();
m_shouldRender = true;
m_enteredIngamePreviousFrame = false;
}
if(!m_shouldRender && gameState->getStateDelta(GameStates::INGAME) == EnumGameDelta::NOTCHANGED){
m_enteredIngamePreviousFrame = true;
}
else if(gameState->getStateDelta(GameStates::LOADING) == EnumGameDelta::EXITTHISFRAME){
m_shouldRender = false;
}
}
void GraphicsRendererSystem::renderTheScene()
{
/*
//Shadows
//m_wrapper->getGPUTimer()->Start(m_profiles[SHADOW].profile);
clearShadowStuf();
//Fill the shadow view projections
for (unsigned int i = 0; i < m_shadowSystem->getNumberOfShadowCameras(); i++){
m_activeShadows[m_shadowSystem->getShadowIdx(i)] = 1;
m_shadowViewProjections[m_shadowSystem->getShadowIdx(i)] =
m_shadowSystem->getViewProjection(i);
}
*/
/*
initShadowPass();
for(unsigned int i = 0; i < MAXSHADOWS; i++){
if(m_activeShadows[i] != -1){
m_wrapper->setShadowMapAsRenderTarget(i);
//m_wrapper->setActiveShadow(i);
m_meshRenderer->render();
}
}
endShadowPass();
*/
//m_wrapper->getGPUTimer()->Stop(m_profiles[SHADOW].profile);
m_wrapper->clearRenderTargets();
// Meshes
m_wrapper->getGPUTimer()->Start(m_profiles[MESH].profile);
initMeshPass();
m_meshRenderer->render();
endMeshPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[MESH].profile);
// Lights
m_wrapper->getGPUTimer()->Start(m_profiles[LIGHT].profile);
initLightPass();
m_lightRenderSystem->render();
endLightPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[LIGHT].profile);
//SSAO
m_wrapper->getGPUTimer()->Start(m_profiles[SSAO].profile);
beginSsao();
m_wrapper->generateSsao();
endSsao();
m_wrapper->getGPUTimer()->Stop(m_profiles[SSAO].profile);
// DoF generation pass
m_wrapper->getGPUTimer()->Start(m_profiles[DOF].profile);
beginDofGenerationPass();
m_wrapper->generateDof();
endDofGenerationPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[DOF].profile);
//Compose
m_wrapper->getGPUTimer()->Start(m_profiles[COMPOSE].profile);
initComposePass();
m_wrapper->renderComposeStage();
endComposePass();
m_wrapper->getGPUTimer()->Stop(m_profiles[COMPOSE].profile);
//Particles
m_wrapper->getGPUTimer()->Start(m_profiles[PARTICLE].profile);
initParticlePass();
renderParticles();
endParticlePass();
m_wrapper->getGPUTimer()->Stop(m_profiles[PARTICLE].profile);
//GUI
m_wrapper->getGPUTimer()->Start(m_profiles[GUI].profile);
initGUIPass();
m_libRocketRenderSystem->render();
m_antTweakBarSystem->render();
endGUIPass();
m_wrapper->getGPUTimer()->Stop(m_profiles[GUI].profile);
flipBackbuffer();
updateTimers();
}
void GraphicsRendererSystem::initShadowPass(){
m_wrapper->setRasterizerStateSettings(RasterizerState::FILLED_CW_FRONTCULL);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
//m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
m_wrapper->setViewportToShadowMapSize();
m_wrapper->setRenderingShadows();
m_wrapper->setShadowViewProjections(m_shadowViewProjections);
}
void GraphicsRendererSystem::endShadowPass(){
m_wrapper->resetViewportToStdSize();
m_wrapper->stopedRenderingShadows();
//m_wrapper->unmapPerShadowBuffer();
}
void GraphicsRendererSystem::initMeshPass(){
m_wrapper->mapSceneInfo();
m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
//m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
m_wrapper->setBaseRenderTargets();
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
}
void GraphicsRendererSystem::endMeshPass(){
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
}
void GraphicsRendererSystem::initLightPass(){
m_wrapper->setRasterizerStateSettings(
//RasterizerState::WIREFRAME_NOCULL, false); // For debug /ML
RasterizerState::FILLED_CW_FRONTCULL, false);
m_wrapper->setBlendStateSettings(BlendState::LIGHT);
m_wrapper->setLightRenderTargets();
//m_wrapper->mapDeferredBaseToShader();
m_wrapper->mapDepthAndNormal();
//m_wrapper->mapShadows( m_activeShadows );
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
}
void GraphicsRendererSystem::endLightPass(){
m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
}
void GraphicsRendererSystem::beginSsao()
{
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP);
m_wrapper->setBlendStateSettings(BlendState::SSAO);
m_wrapper->setRasterizerStateSettings(
RasterizerState::FILLED_NOCULL_NOCLIP, false);
}
void GraphicsRendererSystem::endSsao()
{
m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
m_wrapper->unmapDepthAndNormal();
//m_wrapper->unmapShadows(m_activeShadows);
}
void GraphicsRendererSystem::beginDofGenerationPass()
{
m_wrapper->setViewportToLowRes();
m_wrapper->setPrimitiveTopology( PrimitiveTopology::TRIANGLESTRIP );
m_wrapper->setBlendStateSettings( BlendState::OVERWRITE );
m_wrapper->setDofRenderTargets();
//m_wrapper->setComposedRenderTargetWithNoDepthStencil();
m_wrapper->mapGbuffers();
}
void GraphicsRendererSystem::endDofGenerationPass()
{
m_wrapper->unmapGbuffers();
m_wrapper->resetViewportToStdSize();
}
void GraphicsRendererSystem::initComposePass()
{
m_wrapper->setRasterizerStateSettings(
RasterizerState::DEFAULT, false);
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP);
m_wrapper->setComposedRenderTargetWithNoDepthStencil();
m_wrapper->mapGbuffers();
m_wrapper->mapDofBuffers();
m_wrapper->mapDepth();
}
void GraphicsRendererSystem::endComposePass()
{
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
//m_wrapper->unmapVariousStagesAfterCompose();
m_wrapper->unmapDofBuffers();
m_wrapper->unmapGbuffers();
m_wrapper->unmapDepth();
}
void GraphicsRendererSystem::initParticlePass(){
m_wrapper->setParticleRenderState();
//m_wrapper->setBlendStateSettings(BlendState::PARTICLE);
m_wrapper->setBlendStateSettings(BlendState::ADDITIVE);
m_wrapper->setPrimitiveTopology(PrimitiveTopology::POINTLIST);
}
void GraphicsRendererSystem::renderParticles()
{
// A ugly way to be able to call the different rendering functions. Needs refactoring /ML.
ParticleRenderSystem* psRender = static_cast<ParticleRenderSystem*>( m_particleRenderSystem );
for( int i=0; i<AglParticleSystemHeader::AglBlendMode_CNT; i++ ) {
for( int j=0; j<AglParticleSystemHeader::AglRasterizerMode_CNT; j++ )
{
AglParticleSystemHeader::AglBlendMode blend = (AglParticleSystemHeader::AglBlendMode)i;
AglParticleSystemHeader::AglRasterizerMode rast = (AglParticleSystemHeader::AglRasterizerMode)j;
m_wrapper->setRasterizerStateSettings( psRender->rasterizerStateFromAglRasterizerMode(rast) );
m_wrapper->setBlendStateSettings( psRender->blendStateFromAglBlendMode(blend) );
psRender->render( blend, rast );
}
}
}
void GraphicsRendererSystem::endParticlePass(){
m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST);
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
m_wrapper->setComposedRenderTargetWithNoDepthStencil();
}
void GraphicsRendererSystem::initGUIPass(){
m_wrapper->setBlendStateSettings(BlendState::ALPHA);
}
void GraphicsRendererSystem::endGUIPass(){
m_wrapper->setBlendStateSettings(BlendState::DEFAULT);
}
void GraphicsRendererSystem::flipBackbuffer(){
m_wrapper->flipBackBuffer();
}
void GraphicsRendererSystem::clearShadowStuf()
{
for(int i = 0; i < MAXSHADOWS; i++){
m_activeShadows[i] = -1;
m_shadowViewProjections[i] = AglMatrix::identityMatrix();
}
}
void GraphicsRendererSystem::updateTimers()
{
double total = 0;
GPUTimer* timer = m_wrapper->getGPUTimer();
for(unsigned int i = 0; i < NUMRENDERINGPASSES-1; i++){
m_profiles[i].pushNewTime(timer->getTheTimeAndReset(m_profiles[i].profile));
total += m_profiles[i].renderingTime;
}
m_profiles[TOTAL].pushNewTime(total);
m_wrapper->getGPUTimer()->tick();
}<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "scenepickinghandler.h"
// appleseed.studio headers.
#include "mainwindow/project/projectexplorer.h"
#include "utility/mousecoordinatestracker.h"
// appleseed.renderer headers.
#include "renderer/api/bsdf.h"
#include "renderer/api/camera.h"
#include "renderer/api/edf.h"
#include "renderer/api/entity.h"
#include "renderer/api/frame.h"
#include "renderer/api/log.h"
#include "renderer/api/material.h"
#include "renderer/api/object.h"
#include "renderer/api/project.h"
#include "renderer/api/rendering.h"
#include "renderer/api/scene.h"
#include "renderer/api/surfaceshader.h"
// appleseed.foundation headers.
#include "foundation/image/image.h"
#include "foundation/math/vector.h"
// Qt headers.
#include <QComboBox>
#include <QEvent>
#include <QLabel>
#include <QMouseEvent>
#include <QString>
#include <Qt>
#include <QWidget>
// Standard headers.
#include <cassert>
#include <sstream>
using namespace foundation;
using namespace renderer;
using namespace std;
namespace appleseed {
namespace studio {
ScenePickingHandler::ScenePickingHandler(
QWidget* widget,
QComboBox* picking_mode_combo,
QLabel* r_label,
QLabel* g_label,
QLabel* b_label,
QLabel* a_label,
const MouseCoordinatesTracker& mouse_tracker,
const ProjectExplorer& project_explorer,
const Project& project)
: m_widget(widget)
, m_picking_mode_combo(picking_mode_combo)
, m_r_label(r_label)
, m_g_label(g_label)
, m_b_label(b_label)
, m_a_label(a_label)
, m_mouse_tracker(mouse_tracker)
, m_project_explorer(project_explorer)
, m_project(project)
, m_enabled(true)
{
m_widget->installEventFilter(this);
m_picking_mode_combo->clear();
m_picking_mode_combo->addItem("Assembly", "assembly");
m_picking_mode_combo->addItem("Assembly Instance", "assembly_instance");
m_picking_mode_combo->addItem("Object", "object");
m_picking_mode_combo->addItem("Object Instance", "object_instance");
m_picking_mode_combo->addItem("Material", "material");
m_picking_mode_combo->addItem("Surface Shader", "surface_shader");
m_picking_mode_combo->addItem("BSDF", "bsdf");
m_picking_mode_combo->addItem("EDF", "edf");
m_picking_mode_combo->setCurrentIndex(3);
}
ScenePickingHandler::~ScenePickingHandler()
{
m_widget->removeEventFilter(this);
}
void ScenePickingHandler::set_enabled(const bool enabled)
{
m_enabled = enabled;
}
bool ScenePickingHandler::eventFilter(QObject* object, QEvent* event)
{
if (!m_enabled)
return QObject::eventFilter(object, event);
const QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event);
switch (event->type())
{
case QEvent::MouseButtonPress:
if (mouse_event->button() == Qt::LeftButton &&
!(mouse_event->modifiers() & (Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier)))
{
pick(mouse_event->pos());
return true;
}
break;
case QEvent::MouseMove:
set_rgb_label(mouse_event->pos());
break;
case QEvent::Leave:
m_r_label->clear();
m_g_label->clear();
m_b_label->clear();
m_a_label->clear();
break;
}
return QObject::eventFilter(object, event);
}
void ScenePickingHandler::set_rgb_label(const QPoint& point) const
{
Color4f linear_rgba;
m_project.get_frame()->image().get_pixel(static_cast<size_t>(point.x()), static_cast<size_t>( point.y()), linear_rgba);
QString red;
red.sprintf(" %4.3f", linear_rgba.r);
m_r_label->setText(red);
QString green;
green.sprintf(" %4.3f", linear_rgba.g);
m_g_label->setText(green);
QString blue;
blue.sprintf(" %4.3f", linear_rgba.b);
m_b_label->setText(blue);
QString alpha;
alpha.sprintf(" %4.3f", linear_rgba.a);
m_a_label->setText(alpha);
}
namespace
{
void print_entity(stringstream& sstr, const char* label, const Entity* entity)
{
sstr << label;
if (entity)
sstr << "\"" << entity->get_name() << "\" (#" << entity->get_uid() << ")";
else sstr << "n/a";
sstr << endl;
}
const Entity* get_picked_entity(
const ScenePicker::PickingResult& picking_result,
const QString& picking_mode)
{
if (picking_mode == "assembly")
return picking_result.m_assembly;
else if (picking_mode == "assembly_instance")
return picking_result.m_assembly_instance;
else if (picking_mode == "object")
return picking_result.m_object;
else if (picking_mode == "object_instance")
return picking_result.m_object_instance;
else if (picking_mode == "material")
return picking_result.m_material;
else if (picking_mode == "surface_shader")
return picking_result.m_surface_shader;
else if (picking_mode == "bsdf")
return picking_result.m_bsdf;
else if (picking_mode == "edf")
return picking_result.m_edf;
else
{
assert(!"Invalid picking mode.");
return 0;
}
}
}
void ScenePickingHandler::pick(const QPoint& point)
{
if (!m_project.has_trace_context())
{
RENDERER_LOG_INFO("the scene must be rendering or must have been rendered at least once for picking to be available.");
return;
}
const Vector2i pix = m_mouse_tracker.widget_to_pixel(point);
const Vector2d ndc = m_mouse_tracker.widget_to_ndc(point);
const ScenePicker scene_picker(m_project.get_trace_context());
const ScenePicker::PickingResult result = scene_picker.pick(ndc);
stringstream sstr;
sstr << "picking details:" << endl;
sstr << " pixel coords " << pix.x << ", " << pix.y << endl;
sstr << " ndc coords " << ndc.x << ", " << ndc.y << endl;
print_entity(sstr, " camera ", result.m_camera);
print_entity(sstr, " assembly inst. ", result.m_assembly_instance);
print_entity(sstr, " assembly ", result.m_assembly);
print_entity(sstr, " object inst. ", result.m_object_instance);
print_entity(sstr, " object ", result.m_object);
print_entity(sstr, " material ", result.m_material);
print_entity(sstr, " surface shader ", result.m_surface_shader);
print_entity(sstr, " bsdf ", result.m_bsdf);
print_entity(sstr, " edf ", result.m_edf);
RENDERER_LOG_INFO("%s", sstr.str().c_str());
const QString picking_mode =
m_picking_mode_combo->itemData(m_picking_mode_combo->currentIndex()).value<QString>();
const Entity* picked_entity = get_picked_entity(result, picking_mode);
if (picked_entity)
m_project_explorer.highlight_entity(picked_entity->get_uid());
else m_project_explorer.clear_highlighting();
}
} // namespace studio
} // namespace appleseed
<commit_msg>fixed formatting and eliminated dangerous construct.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "scenepickinghandler.h"
// appleseed.studio headers.
#include "mainwindow/project/projectexplorer.h"
#include "utility/mousecoordinatestracker.h"
// appleseed.renderer headers.
#include "renderer/api/bsdf.h"
#include "renderer/api/camera.h"
#include "renderer/api/edf.h"
#include "renderer/api/entity.h"
#include "renderer/api/frame.h"
#include "renderer/api/log.h"
#include "renderer/api/material.h"
#include "renderer/api/object.h"
#include "renderer/api/project.h"
#include "renderer/api/rendering.h"
#include "renderer/api/scene.h"
#include "renderer/api/surfaceshader.h"
// appleseed.foundation headers.
#include "foundation/image/image.h"
#include "foundation/math/vector.h"
// Qt headers.
#include <QComboBox>
#include <QEvent>
#include <QLabel>
#include <QMouseEvent>
#include <QString>
#include <Qt>
#include <QWidget>
// Standard headers.
#include <cassert>
#include <sstream>
using namespace foundation;
using namespace renderer;
using namespace std;
namespace appleseed {
namespace studio {
ScenePickingHandler::ScenePickingHandler(
QWidget* widget,
QComboBox* picking_mode_combo,
QLabel* r_label,
QLabel* g_label,
QLabel* b_label,
QLabel* a_label,
const MouseCoordinatesTracker& mouse_tracker,
const ProjectExplorer& project_explorer,
const Project& project)
: m_widget(widget)
, m_picking_mode_combo(picking_mode_combo)
, m_r_label(r_label)
, m_g_label(g_label)
, m_b_label(b_label)
, m_a_label(a_label)
, m_mouse_tracker(mouse_tracker)
, m_project_explorer(project_explorer)
, m_project(project)
, m_enabled(true)
{
m_widget->installEventFilter(this);
m_picking_mode_combo->clear();
m_picking_mode_combo->addItem("Assembly", "assembly");
m_picking_mode_combo->addItem("Assembly Instance", "assembly_instance");
m_picking_mode_combo->addItem("Object", "object");
m_picking_mode_combo->addItem("Object Instance", "object_instance");
m_picking_mode_combo->addItem("Material", "material");
m_picking_mode_combo->addItem("Surface Shader", "surface_shader");
m_picking_mode_combo->addItem("BSDF", "bsdf");
m_picking_mode_combo->addItem("EDF", "edf");
m_picking_mode_combo->setCurrentIndex(3);
}
ScenePickingHandler::~ScenePickingHandler()
{
m_widget->removeEventFilter(this);
}
void ScenePickingHandler::set_enabled(const bool enabled)
{
m_enabled = enabled;
}
bool ScenePickingHandler::eventFilter(QObject* object, QEvent* event)
{
if (!m_enabled)
return QObject::eventFilter(object, event);
switch (event->type())
{
case QEvent::MouseButtonPress:
{
const QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event);
if (mouse_event->button() == Qt::LeftButton &&
!(mouse_event->modifiers() & (Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier)))
{
pick(mouse_event->pos());
return true;
}
}
break;
case QEvent::MouseMove:
{
const QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event);
set_rgb_label(mouse_event->pos());
}
break;
case QEvent::Leave:
m_r_label->clear();
m_g_label->clear();
m_b_label->clear();
m_a_label->clear();
break;
}
return QObject::eventFilter(object, event);
}
void ScenePickingHandler::set_rgb_label(const QPoint& point) const
{
Color4f linear_rgba;
m_project.get_frame()->image().get_pixel(static_cast<size_t>(point.x()), static_cast<size_t>( point.y()), linear_rgba);
QString red;
red.sprintf(" %4.3f", linear_rgba.r);
m_r_label->setText(red);
QString green;
green.sprintf(" %4.3f", linear_rgba.g);
m_g_label->setText(green);
QString blue;
blue.sprintf(" %4.3f", linear_rgba.b);
m_b_label->setText(blue);
QString alpha;
alpha.sprintf(" %4.3f", linear_rgba.a);
m_a_label->setText(alpha);
}
namespace
{
void print_entity(stringstream& sstr, const char* label, const Entity* entity)
{
sstr << label;
if (entity)
sstr << "\"" << entity->get_name() << "\" (#" << entity->get_uid() << ")";
else sstr << "n/a";
sstr << endl;
}
const Entity* get_picked_entity(
const ScenePicker::PickingResult& picking_result,
const QString& picking_mode)
{
if (picking_mode == "assembly")
return picking_result.m_assembly;
else if (picking_mode == "assembly_instance")
return picking_result.m_assembly_instance;
else if (picking_mode == "object")
return picking_result.m_object;
else if (picking_mode == "object_instance")
return picking_result.m_object_instance;
else if (picking_mode == "material")
return picking_result.m_material;
else if (picking_mode == "surface_shader")
return picking_result.m_surface_shader;
else if (picking_mode == "bsdf")
return picking_result.m_bsdf;
else if (picking_mode == "edf")
return picking_result.m_edf;
else
{
assert(!"Invalid picking mode.");
return 0;
}
}
}
void ScenePickingHandler::pick(const QPoint& point)
{
if (!m_project.has_trace_context())
{
RENDERER_LOG_INFO("the scene must be rendering or must have been rendered at least once for picking to be available.");
return;
}
const Vector2i pix = m_mouse_tracker.widget_to_pixel(point);
const Vector2d ndc = m_mouse_tracker.widget_to_ndc(point);
const ScenePicker scene_picker(m_project.get_trace_context());
const ScenePicker::PickingResult result = scene_picker.pick(ndc);
stringstream sstr;
sstr << "picking details:" << endl;
sstr << " pixel coords " << pix.x << ", " << pix.y << endl;
sstr << " ndc coords " << ndc.x << ", " << ndc.y << endl;
print_entity(sstr, " camera ", result.m_camera);
print_entity(sstr, " assembly inst. ", result.m_assembly_instance);
print_entity(sstr, " assembly ", result.m_assembly);
print_entity(sstr, " object inst. ", result.m_object_instance);
print_entity(sstr, " object ", result.m_object);
print_entity(sstr, " material ", result.m_material);
print_entity(sstr, " surface shader ", result.m_surface_shader);
print_entity(sstr, " bsdf ", result.m_bsdf);
print_entity(sstr, " edf ", result.m_edf);
RENDERER_LOG_INFO("%s", sstr.str().c_str());
const QString picking_mode =
m_picking_mode_combo->itemData(m_picking_mode_combo->currentIndex()).value<QString>();
const Entity* picked_entity = get_picked_entity(result, picking_mode);
if (picked_entity)
m_project_explorer.highlight_entity(picked_entity->get_uid());
else m_project_explorer.clear_highlighting();
}
} // namespace studio
} // namespace appleseed
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE test_hdf5
#include <boost/test/unit_test.hpp>
#include <votca/xtp/checkpoint.h>
BOOST_AUTO_TEST_SUITE(test_hdf5)
BOOST_AUTO_TEST_CASE(constructor_test) {
votca::xtp::CheckpointFile cpf("xtp_testing.hdf5"); }
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add orbfile write code to checkpoint file writing<commit_after>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE test_hdf5
#include <boost/test/unit_test.hpp>
#include <votca/xtp/checkpoint.h>
BOOST_AUTO_TEST_SUITE(test_hdf5)
BOOST_AUTO_TEST_CASE(checkpoint_file_test) {
votca::xtp::CheckpointFile cpf("xtp_testing.hdf5");
// Write orbitals
votca::xtp::Orbitals orbWrite;
orbWrite.setBasisSetSize(17);
orbWrite.setNumberOfLevels(4,13);
Eigen::VectorXd moeTest = Eigen::VectorXd::Zero(17);
Eigen::MatrixXd mocTest = Eigen::MatrixXd::Zero(17,17);
orbWrite.MOEnergies()=moeTest;
orbWrite.MOCoefficients()=mocTest;
cpf.WriteOrbitals(orbWrite, "Test Orb");
// Read Orbitals
votca::xtp::Orbitals orbRead;
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/**
* @file Mu0Poly.cpp
* Definitions for a single-species standard state object derived
* from \link Cantera::SpeciesThermoInterpType SpeciesThermoInterpType\endlink based
* on a piecewise constant mu0 interpolation
* (see \ref spthermo and class \link Cantera::Mu0Poly Mu0Poly\endlink).
*/
#include "cantera/thermo/Mu0Poly.h"
#include "cantera/thermo/SpeciesThermo.h"
#include "cantera/base/ctml.h"
#include "cantera/base/stringUtils.h"
using namespace std;
using namespace ctml;
namespace Cantera
{
Mu0Poly::Mu0Poly() : m_numIntervals(0),
m_H298(0.0)
{
}
Mu0Poly::Mu0Poly(size_t n, doublereal tlow, doublereal thigh,
doublereal pref,
const doublereal* coeffs) :
SpeciesThermoInterpType(n, tlow, thigh, pref),
m_numIntervals(0),
m_H298(0.0)
{
processCoeffs(coeffs);
}
Mu0Poly::Mu0Poly(const Mu0Poly& b)
: SpeciesThermoInterpType(b),
m_numIntervals(b.m_numIntervals),
m_H298(b.m_H298),
m_t0_int(b.m_t0_int),
m_mu0_R_int(b.m_mu0_R_int),
m_h0_R_int(b.m_h0_R_int),
m_s0_R_int(b.m_s0_R_int),
m_cp0_R_int(b.m_cp0_R_int)
{
}
Mu0Poly& Mu0Poly::operator=(const Mu0Poly& b)
{
if (&b != this) {
SpeciesThermoInterpType::operator=(b);
m_numIntervals = b.m_numIntervals;
m_H298 = b.m_H298;
m_t0_int = b.m_t0_int;
m_mu0_R_int = b.m_mu0_R_int;
m_h0_R_int = b.m_h0_R_int;
m_s0_R_int = b.m_s0_R_int;
m_cp0_R_int = b.m_cp0_R_int;
}
return *this;
}
SpeciesThermoInterpType*
Mu0Poly::duplMyselfAsSpeciesThermoInterpType() const
{
return new Mu0Poly(*this);
}
void Mu0Poly::updateProperties(const doublereal* tt, doublereal* cp_R,
doublereal* h_RT, doublereal* s_R) const
{
size_t j = m_numIntervals;
double T = *tt;
for (size_t i = 0; i < m_numIntervals; i++) {
double T2 = m_t0_int[i+1];
if (T <=T2) {
j = i;
break;
}
}
double T1 = m_t0_int[j];
double cp_Rj = m_cp0_R_int[j];
doublereal rt = 1.0/T;
cp_R[m_index] = cp_Rj;
h_RT[m_index] = rt*(m_h0_R_int[j] + (T - T1) * cp_Rj);
s_R[m_index] = m_s0_R_int[j] + cp_Rj * (log(T/T1));
}
void Mu0Poly::updatePropertiesTemp(const doublereal T,
doublereal* cp_R,
doublereal* h_RT,
doublereal* s_R) const
{
updateProperties(&T, cp_R, h_RT, s_R);
}
void Mu0Poly::reportParameters(size_t& n, int& type,
doublereal& tlow, doublereal& thigh,
doublereal& pref,
doublereal* const coeffs) const
{
n = m_index;
type = MU0_INTERP;
tlow = m_lowT;
thigh = m_highT;
pref = m_Pref;
coeffs[0] = int(m_numIntervals)+1;
coeffs[1] = m_H298 * GasConstant;
int j = 2;
for (size_t i = 0; i < m_numIntervals+1; i++) {
coeffs[j] = m_t0_int[i];
coeffs[j+1] = m_mu0_R_int[i] * GasConstant;
j += 2;
}
}
void Mu0Poly::modifyParameters(doublereal* coeffs)
{
processCoeffs(coeffs);
}
Mu0Poly* newMu0ThermoFromXML(const std::string& speciesName,
const XML_Node& Mu0Node)
{
doublereal tmin, tmax;
bool dimensionlessMu0Values = false;
tmin = fpValue(Mu0Node["Tmin"]);
tmax = fpValue(Mu0Node["Tmax"]);
doublereal pref = fpValue(Mu0Node["Pref"]);
doublereal h298 = 0.0;
if (Mu0Node.hasChild("H298")) {
h298 = getFloat(Mu0Node, "H298", "actEnergy");
}
size_t numPoints = 1;
if (Mu0Node.hasChild("numPoints")) {
numPoints = getInteger(Mu0Node, "numPoints");
}
vector_fp cValues(numPoints);
const XML_Node* valNode_ptr =
getByTitle(const_cast<XML_Node&>(Mu0Node), "Mu0Values");
if (!valNode_ptr) {
throw CanteraError("installMu0ThermoFromXML",
"missing required while processing "
+ speciesName);
}
getFloatArray(*valNode_ptr, cValues, true, "actEnergy");
/*
* Check to see whether the Mu0's were input in a dimensionless
* form. If they were, then the assumed temperature needs to be
* adjusted from the assumed T = 273.15
*/
string uuu = valNode_ptr->attrib("units");
if (uuu == "Dimensionless") {
dimensionlessMu0Values = true;
}
size_t ns = cValues.size();
if (ns != numPoints) {
throw CanteraError("installMu0ThermoFromXML",
"numPoints inconsistent while processing "
+ speciesName);
}
vector_fp cTemperatures(numPoints);
const XML_Node* tempNode_ptr =
getByTitle(const_cast<XML_Node&>(Mu0Node), "Mu0Temperatures");
if (!tempNode_ptr) {
throw CanteraError("installMu0ThermoFromXML",
"missing required while processing + "
+ speciesName);
}
getFloatArray(*tempNode_ptr, cTemperatures, false);
ns = cTemperatures.size();
if (ns != numPoints) {
throw CanteraError("installMu0ThermoFromXML",
"numPoints inconsistent while processing "
+ speciesName);
}
/*
* Fix up dimensionless Mu0 values if input
*/
if (dimensionlessMu0Values) {
for (size_t i = 0; i < numPoints; i++) {
cValues[i] *= cTemperatures[i] / 273.15;
}
}
vector_fp c(2 + 2 * numPoints);
c[0] = static_cast<double>(numPoints);
c[1] = h298;
for (size_t i = 0; i < numPoints; i++) {
c[2+i*2] = cTemperatures[i];
c[2+i*2+1] = cValues[i];
}
return new Mu0Poly(0, tmin, tmax, pref, &c[0]);
}
void Mu0Poly::processCoeffs(const doublereal* coeffs)
{
size_t i, iindex;
double T1, T2;
size_t nPoints = (size_t) coeffs[0];
if (nPoints < 2) {
throw CanteraError("Mu0Poly",
"nPoints must be >= 2");
}
m_numIntervals = nPoints - 1;
m_H298 = coeffs[1] / GasConstant;
size_t iT298 = 0;
/*
* Resize according to the number of points
*/
m_t0_int.resize(nPoints);
m_h0_R_int.resize(nPoints);
m_s0_R_int.resize(nPoints);
m_cp0_R_int.resize(nPoints);
m_mu0_R_int.resize(nPoints);
/*
* Calculate the T298 interval and make sure that
* the temperatures are strictly monotonic.
* Also distribute the data into the internal arrays.
*/
bool ifound = false;
for (i = 0, iindex = 2; i < nPoints; i++) {
T1 = coeffs[iindex];
m_t0_int[i] = T1;
m_mu0_R_int[i] = coeffs[iindex+1] / GasConstant;
if (T1 == 298.15) {
iT298 = i;
ifound = true;
}
if (i < nPoints - 1) {
T2 = coeffs[iindex+2];
if (T2 <= T1) {
throw CanteraError("Mu0Poly",
"Temperatures are not monotonic increasing");
}
}
iindex += 2;
}
if (!ifound) {
throw CanteraError("Mu0Poly",
"One temperature has to be 298.15");
}
/*
* Starting from the interval with T298, we go up
*/
doublereal mu2, s1, s2, h1, h2, cpi, deltaMu, deltaT;
T1 = m_t0_int[iT298];
doublereal mu1 = m_mu0_R_int[iT298];
m_h0_R_int[iT298] = m_H298;
m_s0_R_int[iT298] = - (mu1 - m_h0_R_int[iT298]) / T1;
for (i = iT298; i < m_numIntervals; i++) {
T1 = m_t0_int[i];
s1 = m_s0_R_int[i];
h1 = m_h0_R_int[i];
mu1 = m_mu0_R_int[i];
T2 = m_t0_int[i+1];
mu2 = m_mu0_R_int[i+1];
deltaMu = mu2 - mu1;
deltaT = T2 - T1;
cpi = (deltaMu - T1 * s1 + T2 * s1) / (deltaT - T2 * log(T2/T1));
h2 = h1 + cpi * deltaT;
s2 = s1 + cpi * log(T2/T1);
m_cp0_R_int[i] = cpi;
m_h0_R_int[i+1] = h2;
m_s0_R_int[i+1] = s2;
m_cp0_R_int[i+1] = cpi;
}
/*
* Starting from the interval with T298, we go down
*/
if (iT298 != 0) {
T2 = m_t0_int[iT298];
mu2 = m_mu0_R_int[iT298];
m_h0_R_int[iT298] = m_H298;
m_s0_R_int[iT298] = - (mu2 - m_h0_R_int[iT298]) / T2;
for (i = iT298 - 1; i != npos; i--) {
T1 = m_t0_int[i];
mu1 = m_mu0_R_int[i];
T2 = m_t0_int[i+1];
mu2 = m_mu0_R_int[i+1];
s2 = m_s0_R_int[i+1];
h2 = m_h0_R_int[i+1];
deltaMu = mu2 - mu1;
deltaT = T2 - T1;
cpi = (deltaMu - T1 * s2 + T2 * s2) / (deltaT - T1 * log(T2/T1));
h1 = h2 - cpi * deltaT;
s1 = s2 - cpi * log(T2/T1);
m_cp0_R_int[i] = cpi;
m_h0_R_int[i] = h1;
m_s0_R_int[i] = s1;
if (i == (m_numIntervals-1)) {
m_cp0_R_int[i+1] = cpi;
}
}
}
#ifdef DEBUG_HKM_NOT
printf(" Temp mu0(J/kmol) cp0(J/kmol/K) "
" h0(J/kmol) s0(J/kmol/K) \n");
for (i = 0; i < nPoints; i++) {
printf("%12.3g %12.5g %12.5g %12.5g %12.5g\n",
m_t0_int[i], m_mu0_R_int[i] * GasConstant,
m_cp0_R_int[i]* GasConstant,
m_h0_R_int[i]* GasConstant,
m_s0_R_int[i]* GasConstant);
fflush(stdout);
}
#endif
}
}
<commit_msg>Remove unnecessary use of const_cast<commit_after>/**
* @file Mu0Poly.cpp
* Definitions for a single-species standard state object derived
* from \link Cantera::SpeciesThermoInterpType SpeciesThermoInterpType\endlink based
* on a piecewise constant mu0 interpolation
* (see \ref spthermo and class \link Cantera::Mu0Poly Mu0Poly\endlink).
*/
#include "cantera/thermo/Mu0Poly.h"
#include "cantera/thermo/SpeciesThermo.h"
#include "cantera/base/ctml.h"
#include "cantera/base/stringUtils.h"
using namespace std;
using namespace ctml;
namespace Cantera
{
Mu0Poly::Mu0Poly() : m_numIntervals(0),
m_H298(0.0)
{
}
Mu0Poly::Mu0Poly(size_t n, doublereal tlow, doublereal thigh,
doublereal pref,
const doublereal* coeffs) :
SpeciesThermoInterpType(n, tlow, thigh, pref),
m_numIntervals(0),
m_H298(0.0)
{
processCoeffs(coeffs);
}
Mu0Poly::Mu0Poly(const Mu0Poly& b)
: SpeciesThermoInterpType(b),
m_numIntervals(b.m_numIntervals),
m_H298(b.m_H298),
m_t0_int(b.m_t0_int),
m_mu0_R_int(b.m_mu0_R_int),
m_h0_R_int(b.m_h0_R_int),
m_s0_R_int(b.m_s0_R_int),
m_cp0_R_int(b.m_cp0_R_int)
{
}
Mu0Poly& Mu0Poly::operator=(const Mu0Poly& b)
{
if (&b != this) {
SpeciesThermoInterpType::operator=(b);
m_numIntervals = b.m_numIntervals;
m_H298 = b.m_H298;
m_t0_int = b.m_t0_int;
m_mu0_R_int = b.m_mu0_R_int;
m_h0_R_int = b.m_h0_R_int;
m_s0_R_int = b.m_s0_R_int;
m_cp0_R_int = b.m_cp0_R_int;
}
return *this;
}
SpeciesThermoInterpType*
Mu0Poly::duplMyselfAsSpeciesThermoInterpType() const
{
return new Mu0Poly(*this);
}
void Mu0Poly::updateProperties(const doublereal* tt, doublereal* cp_R,
doublereal* h_RT, doublereal* s_R) const
{
size_t j = m_numIntervals;
double T = *tt;
for (size_t i = 0; i < m_numIntervals; i++) {
double T2 = m_t0_int[i+1];
if (T <=T2) {
j = i;
break;
}
}
double T1 = m_t0_int[j];
double cp_Rj = m_cp0_R_int[j];
doublereal rt = 1.0/T;
cp_R[m_index] = cp_Rj;
h_RT[m_index] = rt*(m_h0_R_int[j] + (T - T1) * cp_Rj);
s_R[m_index] = m_s0_R_int[j] + cp_Rj * (log(T/T1));
}
void Mu0Poly::updatePropertiesTemp(const doublereal T,
doublereal* cp_R,
doublereal* h_RT,
doublereal* s_R) const
{
updateProperties(&T, cp_R, h_RT, s_R);
}
void Mu0Poly::reportParameters(size_t& n, int& type,
doublereal& tlow, doublereal& thigh,
doublereal& pref,
doublereal* const coeffs) const
{
n = m_index;
type = MU0_INTERP;
tlow = m_lowT;
thigh = m_highT;
pref = m_Pref;
coeffs[0] = int(m_numIntervals)+1;
coeffs[1] = m_H298 * GasConstant;
int j = 2;
for (size_t i = 0; i < m_numIntervals+1; i++) {
coeffs[j] = m_t0_int[i];
coeffs[j+1] = m_mu0_R_int[i] * GasConstant;
j += 2;
}
}
void Mu0Poly::modifyParameters(doublereal* coeffs)
{
processCoeffs(coeffs);
}
Mu0Poly* newMu0ThermoFromXML(const std::string& speciesName,
const XML_Node& Mu0Node)
{
doublereal tmin, tmax;
bool dimensionlessMu0Values = false;
tmin = fpValue(Mu0Node["Tmin"]);
tmax = fpValue(Mu0Node["Tmax"]);
doublereal pref = fpValue(Mu0Node["Pref"]);
doublereal h298 = 0.0;
if (Mu0Node.hasChild("H298")) {
h298 = getFloat(Mu0Node, "H298", "actEnergy");
}
size_t numPoints = 1;
if (Mu0Node.hasChild("numPoints")) {
numPoints = getInteger(Mu0Node, "numPoints");
}
vector_fp cValues(numPoints);
const XML_Node* valNode_ptr = getByTitle(Mu0Node, "Mu0Values");
if (!valNode_ptr) {
throw CanteraError("installMu0ThermoFromXML",
"missing required while processing "
+ speciesName);
}
getFloatArray(*valNode_ptr, cValues, true, "actEnergy");
/*
* Check to see whether the Mu0's were input in a dimensionless
* form. If they were, then the assumed temperature needs to be
* adjusted from the assumed T = 273.15
*/
string uuu = valNode_ptr->attrib("units");
if (uuu == "Dimensionless") {
dimensionlessMu0Values = true;
}
size_t ns = cValues.size();
if (ns != numPoints) {
throw CanteraError("installMu0ThermoFromXML",
"numPoints inconsistent while processing "
+ speciesName);
}
vector_fp cTemperatures(numPoints);
const XML_Node* tempNode_ptr = getByTitle(Mu0Node, "Mu0Temperatures");
if (!tempNode_ptr) {
throw CanteraError("installMu0ThermoFromXML",
"missing required while processing + "
+ speciesName);
}
getFloatArray(*tempNode_ptr, cTemperatures, false);
ns = cTemperatures.size();
if (ns != numPoints) {
throw CanteraError("installMu0ThermoFromXML",
"numPoints inconsistent while processing "
+ speciesName);
}
/*
* Fix up dimensionless Mu0 values if input
*/
if (dimensionlessMu0Values) {
for (size_t i = 0; i < numPoints; i++) {
cValues[i] *= cTemperatures[i] / 273.15;
}
}
vector_fp c(2 + 2 * numPoints);
c[0] = static_cast<double>(numPoints);
c[1] = h298;
for (size_t i = 0; i < numPoints; i++) {
c[2+i*2] = cTemperatures[i];
c[2+i*2+1] = cValues[i];
}
return new Mu0Poly(0, tmin, tmax, pref, &c[0]);
}
void Mu0Poly::processCoeffs(const doublereal* coeffs)
{
size_t i, iindex;
double T1, T2;
size_t nPoints = (size_t) coeffs[0];
if (nPoints < 2) {
throw CanteraError("Mu0Poly",
"nPoints must be >= 2");
}
m_numIntervals = nPoints - 1;
m_H298 = coeffs[1] / GasConstant;
size_t iT298 = 0;
/*
* Resize according to the number of points
*/
m_t0_int.resize(nPoints);
m_h0_R_int.resize(nPoints);
m_s0_R_int.resize(nPoints);
m_cp0_R_int.resize(nPoints);
m_mu0_R_int.resize(nPoints);
/*
* Calculate the T298 interval and make sure that
* the temperatures are strictly monotonic.
* Also distribute the data into the internal arrays.
*/
bool ifound = false;
for (i = 0, iindex = 2; i < nPoints; i++) {
T1 = coeffs[iindex];
m_t0_int[i] = T1;
m_mu0_R_int[i] = coeffs[iindex+1] / GasConstant;
if (T1 == 298.15) {
iT298 = i;
ifound = true;
}
if (i < nPoints - 1) {
T2 = coeffs[iindex+2];
if (T2 <= T1) {
throw CanteraError("Mu0Poly",
"Temperatures are not monotonic increasing");
}
}
iindex += 2;
}
if (!ifound) {
throw CanteraError("Mu0Poly",
"One temperature has to be 298.15");
}
/*
* Starting from the interval with T298, we go up
*/
doublereal mu2, s1, s2, h1, h2, cpi, deltaMu, deltaT;
T1 = m_t0_int[iT298];
doublereal mu1 = m_mu0_R_int[iT298];
m_h0_R_int[iT298] = m_H298;
m_s0_R_int[iT298] = - (mu1 - m_h0_R_int[iT298]) / T1;
for (i = iT298; i < m_numIntervals; i++) {
T1 = m_t0_int[i];
s1 = m_s0_R_int[i];
h1 = m_h0_R_int[i];
mu1 = m_mu0_R_int[i];
T2 = m_t0_int[i+1];
mu2 = m_mu0_R_int[i+1];
deltaMu = mu2 - mu1;
deltaT = T2 - T1;
cpi = (deltaMu - T1 * s1 + T2 * s1) / (deltaT - T2 * log(T2/T1));
h2 = h1 + cpi * deltaT;
s2 = s1 + cpi * log(T2/T1);
m_cp0_R_int[i] = cpi;
m_h0_R_int[i+1] = h2;
m_s0_R_int[i+1] = s2;
m_cp0_R_int[i+1] = cpi;
}
/*
* Starting from the interval with T298, we go down
*/
if (iT298 != 0) {
T2 = m_t0_int[iT298];
mu2 = m_mu0_R_int[iT298];
m_h0_R_int[iT298] = m_H298;
m_s0_R_int[iT298] = - (mu2 - m_h0_R_int[iT298]) / T2;
for (i = iT298 - 1; i != npos; i--) {
T1 = m_t0_int[i];
mu1 = m_mu0_R_int[i];
T2 = m_t0_int[i+1];
mu2 = m_mu0_R_int[i+1];
s2 = m_s0_R_int[i+1];
h2 = m_h0_R_int[i+1];
deltaMu = mu2 - mu1;
deltaT = T2 - T1;
cpi = (deltaMu - T1 * s2 + T2 * s2) / (deltaT - T1 * log(T2/T1));
h1 = h2 - cpi * deltaT;
s1 = s2 - cpi * log(T2/T1);
m_cp0_R_int[i] = cpi;
m_h0_R_int[i] = h1;
m_s0_R_int[i] = s1;
if (i == (m_numIntervals-1)) {
m_cp0_R_int[i+1] = cpi;
}
}
}
#ifdef DEBUG_HKM_NOT
printf(" Temp mu0(J/kmol) cp0(J/kmol/K) "
" h0(J/kmol) s0(J/kmol/K) \n");
for (i = 0; i < nPoints; i++) {
printf("%12.3g %12.5g %12.5g %12.5g %12.5g\n",
m_t0_int[i], m_mu0_R_int[i] * GasConstant,
m_cp0_R_int[i]* GasConstant,
m_h0_R_int[i]* GasConstant,
m_s0_R_int[i]* GasConstant);
fflush(stdout);
}
#endif
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planning.h"
#include <algorithm>
#include "google/protobuf/repeated_field.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/planner/em/em_planner.h"
#include "modules/planning/planner/rtk/rtk_replay_planner.h"
#include "modules/planning/trajectory_stitcher/trajectory_stitcher.h"
namespace apollo {
namespace planning {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::adapter::AdapterManager;
using apollo::common::time::Clock;
std::string Planning::Name() const { return "planning"; }
void Planning::RegisterPlanners() {
planner_factory_.Register(
PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });
planner_factory_.Register(PlanningConfig::EM,
[]() -> Planner* { return new EMPlanner(); });
}
const Frame* Planning::GetFrame() const { return frame_.get(); }
const hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); }
bool Planning::InitFrame(const uint32_t sequence_num) {
frame_.reset(new Frame(sequence_num));
if (AdapterManager::GetRoutingResult()->Empty()) {
AERROR << "Routing is empty";
return false;
}
common::TrajectoryPoint point;
frame_->SetVehicleInitPose(VehicleState::instance()->pose());
frame_->SetRoutingResult(
AdapterManager::GetRoutingResult()->GetLatestObserved());
if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) {
const auto& prediction =
AdapterManager::GetPrediction()->GetLatestObserved();
frame_->SetPrediction(prediction);
ADEBUG << "Get prediction";
}
if (!frame_->Init()) {
AERROR << "failed to init frame";
return false;
}
return true;
}
Status Planning::Init() {
pnc_map_.reset(new hdmap::PncMap(FLAGS_map_filename));
Frame::SetMap(pnc_map_.get());
if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,
&config_)) {
AERROR << "failed to load planning config file "
<< FLAGS_planning_config_file;
return Status(
ErrorCode::PLANNING_ERROR,
"failed to load planning config file: " + FLAGS_planning_config_file);
}
AdapterManager::Init(FLAGS_adapter_config_path);
if (AdapterManager::GetLocalization() == nullptr) {
std::string error_msg("Localization is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
if (AdapterManager::GetChassis() == nullptr) {
std::string error_msg("Chassis is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
if (AdapterManager::GetRoutingResult() == nullptr) {
std::string error_msg("RoutingResult is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
// TODO(all) temporarily use the offline routing data.
if (!AdapterManager::GetRoutingResult()->HasReceived()) {
if (!AdapterManager::GetRoutingResult()->FeedFile(
FLAGS_offline_routing_file)) {
auto error_msg = common::util::StrCat(
"Failed to load offline routing file ", FLAGS_offline_routing_file);
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
} else {
AWARN << "Using offline routing file " << FLAGS_offline_routing_file;
}
}
if (AdapterManager::GetPrediction() == nullptr) {
std::string error_msg("Prediction is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
RegisterPlanners();
planner_ = planner_factory_.CreateObject(config_.planner_type());
if (!planner_) {
return Status(
ErrorCode::PLANNING_ERROR,
"planning is not initialized with config : " + config_.DebugString());
}
return planner_->Init(config_);
}
Status Planning::Start() {
static ros::Rate loop_rate(FLAGS_planning_loop_rate);
while (ros::ok()) {
RunOnce();
ros::spinOnce();
loop_rate.sleep();
}
return Status::OK();
}
void Planning::RecordInput(ADCTrajectory* trajectory_pb) {
if (!FLAGS_enable_record_debug) {
ADEBUG << "Skip record input into debug";
return;
}
auto planning_data = trajectory_pb->mutable_debug()->mutable_planning_data();
auto adc_position = planning_data->mutable_adc_position();
const auto& localization =
AdapterManager::GetLocalization()->GetLatestObserved();
adc_position->CopyFrom(localization);
const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();
auto debug_chassis = planning_data->mutable_chassis();
debug_chassis->CopyFrom(chassis);
const auto& routing_result =
AdapterManager::GetRoutingResult()->GetLatestObserved();
auto debug_routing = planning_data->mutable_routing();
debug_routing->CopyFrom(routing_result);
}
void Planning::RunOnce() {
AdapterManager::Observe();
if (AdapterManager::GetLocalization()->Empty()) {
AERROR << "Localization is not available; skip the planning cycle";
return;
}
if (AdapterManager::GetChassis()->Empty()) {
AERROR << "Chassis is not available; skip the planning cycle";
return;
}
if (AdapterManager::GetRoutingResult()->Empty()) {
AERROR << "RoutingResult is not available; skip the planning cycle";
return;
}
// FIXME(all): enable prediction check when perception and prediction is
// ready.
// if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) {
// AERROR << "Prediction is not available; skip the planning cycle";
// return;
// }
AINFO << "Start planning ...";
const double start_timestamp = apollo::common::time::ToSecond(Clock::Now());
// localization
const auto& localization =
AdapterManager::GetLocalization()->GetLatestObserved();
ADEBUG << "Get localization:" << localization.DebugString();
// chassis
const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();
ADEBUG << "Get chassis:" << chassis.DebugString();
common::VehicleState::instance()->Update(localization, chassis);
const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate;
ADCTrajectory trajectory_pb;
RecordInput(&trajectory_pb);
const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1;
if (!InitFrame(frame_num)) {
AERROR << "Init frame failed";
return;
}
bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE;
bool res_planning = Plan(is_auto_mode, start_timestamp, planning_cycle_time,
&trajectory_pb);
const double end_timestamp = apollo::common::time::ToSecond(Clock::Now());
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
ADEBUG << "Planning latency: " << trajectory_pb.latency_stats().DebugString();
if (res_planning) {
AdapterManager::FillPlanningHeader("planning", &trajectory_pb);
trajectory_pb.mutable_header()->set_timestamp_sec(start_timestamp);
AdapterManager::PublishPlanning(trajectory_pb);
ADEBUG << "Planning succeeded:" << trajectory_pb.header().DebugString();
} else {
AERROR << "Planning failed";
}
}
void Planning::Stop() {}
bool Planning::Plan(const bool is_on_auto_mode,
const double current_time_stamp,
const double planning_cycle_time,
ADCTrajectory* trajectory_pb) {
const auto& stitching_trajectory =
TrajectoryStitcher::compute_stitching_trajectory(
is_on_auto_mode, current_time_stamp, planning_cycle_time,
last_publishable_trajectory_);
frame_->SetPlanningStartPoint(stitching_trajectory.back());
PublishableTrajectory publishable_trajectory;
auto status = planner_->Plan(stitching_trajectory.back(),
frame_.get(), &publishable_trajectory, trajectory_pb->mutable_debug(),
trajectory_pb->mutable_latency_stats());
if (status != Status::OK()) {
AERROR << "planner failed to make a driving plan";
last_publishable_trajectory_.Clear();
return false;
}
publishable_trajectory.prepend_trajectory_points(
stitching_trajectory.begin(), stitching_trajectory.end() - 1);
publishable_trajectory.set_header_time(current_time_stamp);
publishable_trajectory.populate_trajectory_protobuf(trajectory_pb);
// update last publishable trajectory;
last_publishable_trajectory_ = std::move(publishable_trajectory);
return true;
}
} // namespace planning
} // namespace apollo
<commit_msg>planning passes GEAR_DRIVE.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planning.h"
#include <algorithm>
#include "google/protobuf/repeated_field.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/planner/em/em_planner.h"
#include "modules/planning/planner/rtk/rtk_replay_planner.h"
#include "modules/planning/trajectory_stitcher/trajectory_stitcher.h"
namespace apollo {
namespace planning {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleState;
using apollo::common::adapter::AdapterManager;
using apollo::common::time::Clock;
std::string Planning::Name() const { return "planning"; }
void Planning::RegisterPlanners() {
planner_factory_.Register(
PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });
planner_factory_.Register(PlanningConfig::EM,
[]() -> Planner* { return new EMPlanner(); });
}
const Frame* Planning::GetFrame() const { return frame_.get(); }
const hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); }
bool Planning::InitFrame(const uint32_t sequence_num) {
frame_.reset(new Frame(sequence_num));
if (AdapterManager::GetRoutingResult()->Empty()) {
AERROR << "Routing is empty";
return false;
}
common::TrajectoryPoint point;
frame_->SetVehicleInitPose(VehicleState::instance()->pose());
frame_->SetRoutingResult(
AdapterManager::GetRoutingResult()->GetLatestObserved());
if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) {
const auto& prediction =
AdapterManager::GetPrediction()->GetLatestObserved();
frame_->SetPrediction(prediction);
ADEBUG << "Get prediction";
}
if (!frame_->Init()) {
AERROR << "failed to init frame";
return false;
}
return true;
}
Status Planning::Init() {
pnc_map_.reset(new hdmap::PncMap(FLAGS_map_filename));
Frame::SetMap(pnc_map_.get());
if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,
&config_)) {
AERROR << "failed to load planning config file "
<< FLAGS_planning_config_file;
return Status(
ErrorCode::PLANNING_ERROR,
"failed to load planning config file: " + FLAGS_planning_config_file);
}
AdapterManager::Init(FLAGS_adapter_config_path);
if (AdapterManager::GetLocalization() == nullptr) {
std::string error_msg("Localization is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
if (AdapterManager::GetChassis() == nullptr) {
std::string error_msg("Chassis is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
if (AdapterManager::GetRoutingResult() == nullptr) {
std::string error_msg("RoutingResult is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
// TODO(all) temporarily use the offline routing data.
if (!AdapterManager::GetRoutingResult()->HasReceived()) {
if (!AdapterManager::GetRoutingResult()->FeedFile(
FLAGS_offline_routing_file)) {
auto error_msg = common::util::StrCat(
"Failed to load offline routing file ", FLAGS_offline_routing_file);
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
} else {
AWARN << "Using offline routing file " << FLAGS_offline_routing_file;
}
}
if (AdapterManager::GetPrediction() == nullptr) {
std::string error_msg("Prediction is not registered");
AERROR << error_msg;
return Status(ErrorCode::PLANNING_ERROR, error_msg);
}
RegisterPlanners();
planner_ = planner_factory_.CreateObject(config_.planner_type());
if (!planner_) {
return Status(
ErrorCode::PLANNING_ERROR,
"planning is not initialized with config : " + config_.DebugString());
}
return planner_->Init(config_);
}
Status Planning::Start() {
static ros::Rate loop_rate(FLAGS_planning_loop_rate);
while (ros::ok()) {
RunOnce();
ros::spinOnce();
loop_rate.sleep();
}
return Status::OK();
}
void Planning::RecordInput(ADCTrajectory* trajectory_pb) {
if (!FLAGS_enable_record_debug) {
ADEBUG << "Skip record input into debug";
return;
}
auto planning_data = trajectory_pb->mutable_debug()->mutable_planning_data();
auto adc_position = planning_data->mutable_adc_position();
const auto& localization =
AdapterManager::GetLocalization()->GetLatestObserved();
adc_position->CopyFrom(localization);
const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();
auto debug_chassis = planning_data->mutable_chassis();
debug_chassis->CopyFrom(chassis);
const auto& routing_result =
AdapterManager::GetRoutingResult()->GetLatestObserved();
auto debug_routing = planning_data->mutable_routing();
debug_routing->CopyFrom(routing_result);
}
void Planning::RunOnce() {
AdapterManager::Observe();
if (AdapterManager::GetLocalization()->Empty()) {
AERROR << "Localization is not available; skip the planning cycle";
return;
}
if (AdapterManager::GetChassis()->Empty()) {
AERROR << "Chassis is not available; skip the planning cycle";
return;
}
if (AdapterManager::GetRoutingResult()->Empty()) {
AERROR << "RoutingResult is not available; skip the planning cycle";
return;
}
// FIXME(all): enable prediction check when perception and prediction is
// ready.
// if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) {
// AERROR << "Prediction is not available; skip the planning cycle";
// return;
// }
AINFO << "Start planning ...";
const double start_timestamp = apollo::common::time::ToSecond(Clock::Now());
// localization
const auto& localization =
AdapterManager::GetLocalization()->GetLatestObserved();
ADEBUG << "Get localization:" << localization.DebugString();
// chassis
const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();
ADEBUG << "Get chassis:" << chassis.DebugString();
common::VehicleState::instance()->Update(localization, chassis);
const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate;
ADCTrajectory trajectory_pb;
RecordInput(&trajectory_pb);
const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1;
if (!InitFrame(frame_num)) {
AERROR << "Init frame failed";
return;
}
bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE;
bool res_planning = Plan(is_auto_mode, start_timestamp, planning_cycle_time,
&trajectory_pb);
const double end_timestamp = apollo::common::time::ToSecond(Clock::Now());
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
ADEBUG << "Planning latency: " << trajectory_pb.latency_stats().DebugString();
if (res_planning) {
AdapterManager::FillPlanningHeader("planning", &trajectory_pb);
trajectory_pb.mutable_header()->set_timestamp_sec(start_timestamp);
// TODO(all): integrate reverse gear
trajectory_pb.set_gear(canbus::Chassis::GEAR_DRIVE);
AdapterManager::PublishPlanning(trajectory_pb);
ADEBUG << "Planning succeeded:" << trajectory_pb.header().DebugString();
} else {
AERROR << "Planning failed";
}
}
void Planning::Stop() {}
bool Planning::Plan(const bool is_on_auto_mode,
const double current_time_stamp,
const double planning_cycle_time,
ADCTrajectory* trajectory_pb) {
const auto& stitching_trajectory =
TrajectoryStitcher::compute_stitching_trajectory(
is_on_auto_mode, current_time_stamp, planning_cycle_time,
last_publishable_trajectory_);
frame_->SetPlanningStartPoint(stitching_trajectory.back());
PublishableTrajectory publishable_trajectory;
auto status = planner_->Plan(stitching_trajectory.back(),
frame_.get(), &publishable_trajectory, trajectory_pb->mutable_debug(),
trajectory_pb->mutable_latency_stats());
if (status != Status::OK()) {
AERROR << "planner failed to make a driving plan";
last_publishable_trajectory_.Clear();
return false;
}
publishable_trajectory.prepend_trajectory_points(
stitching_trajectory.begin(), stitching_trajectory.end() - 1);
publishable_trajectory.set_header_time(current_time_stamp);
publishable_trajectory.populate_trajectory_protobuf(trajectory_pb);
// update last publishable trajectory;
last_publishable_trajectory_ = std::move(publishable_trajectory);
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/*
* SessionConnectionsIndexer.cpp
*
* Copyright (C) 2009-16 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/Macros.hpp>
#include <core/Algorithm.hpp>
#include <core/Debug.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/text/DcfParser.hpp>
#include <boost/regex.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/system/error_code.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionPackageProvidedExtension.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace connections {
namespace {
class SessionConnectionsIndexEntry
{
public:
SessionConnectionsIndexEntry() {}
SessionConnectionsIndexEntry(const std::string& name,
const std::string& package)
: name_(name), package_(package)
{
}
const std::string& getName() const { return name_; }
const std::string& getPackage() const { return package_; }
json::Object toJson() const
{
json::Object object;
object["name"] = name_;
object["package"] = package_;
return object;
}
private:
std::string name_;
std::string package_;
};
}
} // namespace connections
} // namespace modules
} // namesapce session
} // namespace rstudio
<commit_msg>implement a connections registry based of addinregistry<commit_after>/*
* SessionConnectionsIndexer.cpp
*
* Copyright (C) 2009-16 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/Macros.hpp>
#include <core/Algorithm.hpp>
#include <core/Debug.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/text/DcfParser.hpp>
#include <boost/regex.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/system/error_code.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionPackageProvidedExtension.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace connections {
namespace {
class SessionConnectionsIndexEntry
{
public:
SessionConnectionsIndexEntry() {}
SessionConnectionsIndexEntry(const std::string& name,
const std::string& package)
: name_(name), package_(package)
{
}
const std::string& getName() const { return name_; }
const std::string& getPackage() const { return package_; }
json::Object toJson() const
{
json::Object object;
object["name"] = name_;
object["package"] = package_;
return object;
}
private:
std::string name_;
std::string package_;
};
class SessionConnectionsIndexRegistry : boost::noncopyable
{
public:
void add(const std::string& package, const SessionConnectionsIndexEntry& spec)
{
connections_[constructKey(package, spec.getName())] = spec;
}
void add(const std::string& pkgName,
std::map<std::string, std::string>& fields)
{
add(pkgName, SessionConnectionsIndexEntry(
fields["Name"],
pkgName));
}
void add(const std::string& pkgName, const FilePath& connectionExtensionPath)
{
static const boost::regex reSeparator("\\n{2,}");
std::string contents;
Error error = core::readStringFromFile(connectionExtensionPath, &contents, string_utils::LineEndingPosix);
if (error)
{
LOG_ERROR(error);
return;
}
boost::sregex_token_iterator it(contents.begin(), contents.end(), reSeparator, -1);
boost::sregex_token_iterator end;
for (; it != end; ++it)
{
std::map<std::string, std::string> fields = parseConnectionsDcf(*it);
add(pkgName, fields);
}
}
bool contains(const std::string& package, const std::string& name)
{
return connections_.count(constructKey(package, name));
}
const SessionConnectionsIndexEntry& get(const std::string& package, const std::string& name)
{
return connections_[constructKey(package, name)];
}
json::Object toJson() const
{
json::Object object;
BOOST_FOREACH(const std::string& key, connections_ | boost::adaptors::map_keys)
{
object[key] = connections_.at(key).toJson();
}
return object;
}
std::size_t size() const { return connections_.size(); }
private:
static std::map<std::string, std::string> parseConnectionsDcf(
const std::string& contents)
{
// read and parse the DCF file
std::map<std::string, std::string> fields;
std::string errMsg;
Error error = text::parseDcfFile(contents, true, &fields, &errMsg);
if (error)
LOG_ERROR(error);
return fields;
}
static std::string constructKey(const std::string& package, const std::string& name)
{
return package + "::" + name;
}
std::map<std::string, SessionConnectionsIndexEntry> connections_;
};
}
} // namespace connections
} // namespace modules
} // namesapce session
} // namespace rstudio
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/odyssey/common/include/ody_scom_mp.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2021,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#pragma once
#include "ody_scom_mp_rdf.H"
<commit_msg>Add Synopsys includes and test.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/odyssey/common/include/ody_scom_mp.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2021,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#pragma once
#include "ody_scom_mp_rdf.H"
#include "ody_scom_mp_acsm0_b0.H"
#include "ody_scom_mp_acsm0_b1.H"
#include "ody_scom_mp_acsm0_b2.H"
#include "ody_scom_mp_acsm0_b3.H"
#include "ody_scom_mp_anib0_b0.H"
#include "ody_scom_mp_anib0_b1.H"
#include "ody_scom_mp_anib0_b2.H"
#include "ody_scom_mp_anib0_b3.H"
#include "ody_scom_mp_anib10_b0.H"
#include "ody_scom_mp_anib10_b1.H"
#include "ody_scom_mp_anib10_b2.H"
#include "ody_scom_mp_anib10_b3.H"
#include "ody_scom_mp_anib11_b0.H"
#include "ody_scom_mp_anib11_b1.H"
#include "ody_scom_mp_anib11_b2.H"
#include "ody_scom_mp_anib11_b3.H"
#include "ody_scom_mp_anib12_b0.H"
#include "ody_scom_mp_anib12_b1.H"
#include "ody_scom_mp_anib12_b2.H"
#include "ody_scom_mp_anib12_b3.H"
#include "ody_scom_mp_anib13_b0.H"
#include "ody_scom_mp_anib13_b1.H"
#include "ody_scom_mp_anib13_b2.H"
#include "ody_scom_mp_anib13_b3.H"
#include "ody_scom_mp_anib1_b0.H"
#include "ody_scom_mp_anib1_b1.H"
#include "ody_scom_mp_anib1_b2.H"
#include "ody_scom_mp_anib1_b3.H"
#include "ody_scom_mp_anib2_b0.H"
#include "ody_scom_mp_anib2_b1.H"
#include "ody_scom_mp_anib2_b2.H"
#include "ody_scom_mp_anib2_b3.H"
#include "ody_scom_mp_anib3_b0.H"
#include "ody_scom_mp_anib3_b1.H"
#include "ody_scom_mp_anib3_b2.H"
#include "ody_scom_mp_anib3_b3.H"
#include "ody_scom_mp_anib4_b0.H"
#include "ody_scom_mp_anib4_b1.H"
#include "ody_scom_mp_anib4_b2.H"
#include "ody_scom_mp_anib4_b3.H"
#include "ody_scom_mp_anib5_b0.H"
#include "ody_scom_mp_anib5_b1.H"
#include "ody_scom_mp_anib5_b2.H"
#include "ody_scom_mp_anib5_b3.H"
#include "ody_scom_mp_anib6_b0.H"
#include "ody_scom_mp_anib6_b1.H"
#include "ody_scom_mp_anib6_b2.H"
#include "ody_scom_mp_anib6_b3.H"
#include "ody_scom_mp_anib7_b0.H"
#include "ody_scom_mp_anib7_b1.H"
#include "ody_scom_mp_anib7_b2.H"
#include "ody_scom_mp_anib7_b3.H"
#include "ody_scom_mp_anib8_b0.H"
#include "ody_scom_mp_anib8_b1.H"
#include "ody_scom_mp_anib8_b2.H"
#include "ody_scom_mp_anib8_b3.H"
#include "ody_scom_mp_anib9_b0.H"
#include "ody_scom_mp_anib9_b1.H"
#include "ody_scom_mp_anib9_b2.H"
#include "ody_scom_mp_anib9_b3.H"
#include "ody_scom_mp_apbonly0.H"
#include "ody_scom_mp_dbyte0_b0.H"
#include "ody_scom_mp_dbyte0_b1.H"
#include "ody_scom_mp_dbyte0_b2.H"
#include "ody_scom_mp_dbyte0_b3.H"
#include "ody_scom_mp_dbyte1_b0.H"
#include "ody_scom_mp_dbyte1_b1.H"
#include "ody_scom_mp_dbyte1_b2.H"
#include "ody_scom_mp_dbyte1_b3.H"
#include "ody_scom_mp_dbyte2_b0.H"
#include "ody_scom_mp_dbyte2_b1.H"
#include "ody_scom_mp_dbyte2_b2.H"
#include "ody_scom_mp_dbyte2_b3.H"
#include "ody_scom_mp_dbyte3_b0.H"
#include "ody_scom_mp_dbyte3_b1.H"
#include "ody_scom_mp_dbyte3_b2.H"
#include "ody_scom_mp_dbyte3_b3.H"
#include "ody_scom_mp_dbyte4_b0.H"
#include "ody_scom_mp_dbyte4_b1.H"
#include "ody_scom_mp_dbyte4_b2.H"
#include "ody_scom_mp_dbyte4_b3.H"
#include "ody_scom_mp_dbyte5_b0.H"
#include "ody_scom_mp_dbyte5_b1.H"
#include "ody_scom_mp_dbyte5_b2.H"
#include "ody_scom_mp_dbyte5_b3.H"
#include "ody_scom_mp_dbyte6_b0.H"
#include "ody_scom_mp_dbyte6_b1.H"
#include "ody_scom_mp_dbyte6_b2.H"
#include "ody_scom_mp_dbyte6_b3.H"
#include "ody_scom_mp_dbyte7_b0.H"
#include "ody_scom_mp_dbyte7_b1.H"
#include "ody_scom_mp_dbyte7_b2.H"
#include "ody_scom_mp_dbyte7_b3.H"
#include "ody_scom_mp_dbyte8_b0.H"
#include "ody_scom_mp_dbyte8_b1.H"
#include "ody_scom_mp_dbyte8_b2.H"
#include "ody_scom_mp_dbyte8_b3.H"
#include "ody_scom_mp_dbyte9_b0.H"
#include "ody_scom_mp_dbyte9_b1.H"
#include "ody_scom_mp_dbyte9_b2.H"
#include "ody_scom_mp_dbyte9_b3.H"
#include "ody_scom_mp_drtub0.H"
#include "ody_scom_mp_intgo_b0.H"
#include "ody_scom_mp_intgo_b1.H"
#include "ody_scom_mp_intgo_b2.H"
#include "ody_scom_mp_intgo_b3.H"
#include "ody_scom_mp_mastr_b0.H"
#include "ody_scom_mp_mastr_b1.H"
#include "ody_scom_mp_mastr_b2.H"
#include "ody_scom_mp_mastr_b3.H"
#include "ody_scom_mp_ppgc0.H"
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h"
#include "platform/graphics/DiscardablePixelRef.h"
#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
namespace {
// URI label for a discardable SkPixelRef.
const char labelDiscardable[] = "discardable";
} // namespace
bool DiscardablePixelRefAllocator::allocPixelRef(SkBitmap* dst, SkColorTable* ctable)
{
// It should not be possible to have a non-null color table in Blink.
ASSERT(!ctable);
Sk64 size = dst->getSize64();
if (size.isNeg() || !size.is32())
return false;
SkImageInfo info;
if (!dst->asImageInfo(&info))
return false;
SkAutoTUnref<DiscardablePixelRef> pixelRef(new DiscardablePixelRef(info, adoptPtr(new SkMutex())));
if (pixelRef->allocAndLockDiscardableMemory(size.get32())) {
pixelRef->setURI(labelDiscardable);
dst->setPixelRef(pixelRef.get());
// This method is only called when a DiscardablePixelRef is created to back a SkBitmap.
// It is necessary to lock this SkBitmap to have a valid pointer to pixels. Otherwise,
// this SkBitmap could be assigned to another SkBitmap and locking/unlocking the other
// SkBitmap will make this one losing its pixels.
dst->lockPixels();
return true;
}
// Fallback to heap allocator if discardable memory is not available.
return dst->allocPixels();
}
DiscardablePixelRef::DiscardablePixelRef(const SkImageInfo& info, PassOwnPtr<SkMutex> mutex)
: SkPixelRef(info, mutex.get())
, m_lockedMemory(0)
, m_mutex(mutex)
{
}
DiscardablePixelRef::~DiscardablePixelRef()
{
}
bool DiscardablePixelRef::allocAndLockDiscardableMemory(size_t bytes)
{
m_discardable = adoptPtr(blink::Platform::current()->allocateAndLockDiscardableMemory(bytes));
if (m_discardable) {
m_lockedMemory = m_discardable->data();
return true;
}
return false;
}
void* DiscardablePixelRef::onLockPixels(SkColorTable** ctable)
{
if (!m_lockedMemory && m_discardable->lock())
m_lockedMemory = m_discardable->data();
*ctable = 0;
return m_lockedMemory;
}
void DiscardablePixelRef::onUnlockPixels()
{
if (m_lockedMemory)
m_discardable->unlock();
m_lockedMemory = 0;
}
bool DiscardablePixelRef::isDiscardable(SkPixelRef* pixelRef)
{
// FIXME: DEFINE_STATIC_LOCAL is not thread safe.
// ImageDecodingStore provides the synchronization for this.
DEFINE_STATIC_LOCAL(const SkString, discardable, (labelDiscardable));
return pixelRef && pixelRef->getURI() && discardable.equals(pixelRef->getURI());
}
} // namespace WebCore
<commit_msg>use native int64_t api on SkBitmap<commit_after>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h"
#include "platform/graphics/DiscardablePixelRef.h"
#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
namespace {
// URI label for a discardable SkPixelRef.
const char labelDiscardable[] = "discardable";
} // namespace
bool DiscardablePixelRefAllocator::allocPixelRef(SkBitmap* dst, SkColorTable* ctable)
{
// It should not be possible to have a non-null color table in Blink.
ASSERT(!ctable);
int64_t size = dst->computeSize64();
if (size < 0 || !sk_64_isS32(size))
return false;
SkImageInfo info;
if (!dst->asImageInfo(&info))
return false;
SkAutoTUnref<DiscardablePixelRef> pixelRef(new DiscardablePixelRef(info, adoptPtr(new SkMutex())));
if (pixelRef->allocAndLockDiscardableMemory(sk_64_asS32(size))) {
pixelRef->setURI(labelDiscardable);
dst->setPixelRef(pixelRef.get());
// This method is only called when a DiscardablePixelRef is created to back a SkBitmap.
// It is necessary to lock this SkBitmap to have a valid pointer to pixels. Otherwise,
// this SkBitmap could be assigned to another SkBitmap and locking/unlocking the other
// SkBitmap will make this one losing its pixels.
dst->lockPixels();
return true;
}
// Fallback to heap allocator if discardable memory is not available.
return dst->allocPixels();
}
DiscardablePixelRef::DiscardablePixelRef(const SkImageInfo& info, PassOwnPtr<SkMutex> mutex)
: SkPixelRef(info, mutex.get())
, m_lockedMemory(0)
, m_mutex(mutex)
{
}
DiscardablePixelRef::~DiscardablePixelRef()
{
}
bool DiscardablePixelRef::allocAndLockDiscardableMemory(size_t bytes)
{
m_discardable = adoptPtr(blink::Platform::current()->allocateAndLockDiscardableMemory(bytes));
if (m_discardable) {
m_lockedMemory = m_discardable->data();
return true;
}
return false;
}
void* DiscardablePixelRef::onLockPixels(SkColorTable** ctable)
{
if (!m_lockedMemory && m_discardable->lock())
m_lockedMemory = m_discardable->data();
*ctable = 0;
return m_lockedMemory;
}
void DiscardablePixelRef::onUnlockPixels()
{
if (m_lockedMemory)
m_discardable->unlock();
m_lockedMemory = 0;
}
bool DiscardablePixelRef::isDiscardable(SkPixelRef* pixelRef)
{
// FIXME: DEFINE_STATIC_LOCAL is not thread safe.
// ImageDecodingStore provides the synchronization for this.
DEFINE_STATIC_LOCAL(const SkString, discardable, (labelDiscardable));
return pixelRef && pixelRef->getURI() && discardable.equals(pixelRef->getURI());
}
} // namespace WebCore
<|endoftext|> |
<commit_before>#include "openmc/tallies/filter_mesh.h"
#include <fmt/core.h>
#include <gsl/gsl>
#include "openmc/capi.h"
#include "openmc/constants.h"
#include "openmc/error.h"
#include "openmc/mesh.h"
#include "openmc/xml_interface.h"
namespace openmc {
void
MeshFilter::from_xml(pugi::xml_node node)
{
auto bins_ = get_node_array<int32_t>(node, "bins");
if (bins_.size() != 1) {
fatal_error("Only one mesh can be specified per " + type()
+ " mesh filter.");
}
auto id = bins_[0];
auto search = model::mesh_map.find(id);
if (search != model::mesh_map.end()) {
set_mesh(search->second);
} else{
fatal_error(fmt::format(
"Could not find mesh {} specified on tally filter.", id));
}
}
void
MeshFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)
const
{
Position last_r = p.r_last_;
Position r = p.r();
Position u = p.u();
// apply translation if present
if (translated_) {
last_r -= translation_;
r -= translation_;
}
if (estimator != TallyEstimator::TRACKLENGTH) {
auto bin = model::meshes[mesh_]->get_bin(r);
if (bin >= 0) {
match.bins_.push_back(bin);
match.weights_.push_back(1.0);
}
} else {
model::meshes[mesh_]->bins_crossed(last_r, r, u, match.bins_, match.weights_);
}
}
void
MeshFilter::to_statepoint(hid_t filter_group) const
{
Filter::to_statepoint(filter_group);
write_dataset(filter_group, "bins", model::meshes[mesh_]->id_);
}
std::string
MeshFilter::text_label(int bin) const
{
auto& mesh = *model::meshes.at(mesh_);
return mesh.bin_label(bin);
}
void
MeshFilter::set_mesh(int32_t mesh)
{
mesh_ = mesh;
n_bins_ = model::meshes[mesh_]->n_bins();
}
void MeshFilter::set_translation(const Position& translation)
{
translated_ = true;
translation_ = translation;
}
void MeshFilter::set_translation(const double translation[3])
{
translated_ = true;
translation_ = translation;
}
//==============================================================================
// C-API functions
//==============================================================================
extern "C" int
openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh)
{
if (!index_mesh) {
set_errmsg("Mesh index argument is a null pointer.");
return OPENMC_E_INVALID_ARGUMENT;
}
// Make sure this is a valid index to an allocated filter.
if (int err = verify_filter(index)) return err;
// Get a pointer to the filter and downcast.
const auto& filt_base = model::tally_filters[index].get();
auto* filt = dynamic_cast<MeshFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to get mesh on a non-mesh filter.");
return OPENMC_E_INVALID_TYPE;
}
// Output the mesh.
*index_mesh = filt->mesh();
return 0;
}
extern "C" int
openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh)
{
// Make sure this is a valid index to an allocated filter.
if (int err = verify_filter(index)) return err;
// Get a pointer to the filter and downcast.
const auto& filt_base = model::tally_filters[index].get();
auto* filt = dynamic_cast<MeshFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to set mesh on a non-mesh filter.");
return OPENMC_E_INVALID_TYPE;
}
// Check the mesh index.
if (index_mesh < 0 || index_mesh >= model::meshes.size()) {
set_errmsg("Index in 'meshes' array is out of bounds.");
return OPENMC_E_OUT_OF_BOUNDS;
}
// Update the filter.
filt->set_mesh(index_mesh);
return 0;
}
extern "C" int
openmc_mesh_filter_set_translation(int32_t index, double translation[3])
{
// Make sure this is a valid index to an allocated filter
if (int err = verify_filter(index)) return err;
// Get a pointer to the filter and downcast.
const auto& filt_base = model::tally_filters[index].get();
auto* filt = dynamic_cast<MeshFilter*>(filt_base);
// Check the filter type
if (!filt) {
set_errmsg("Tried to set mesh on a non-mesh filter.");
return OPENMC_E_INVALID_TYPE;
}
// Set the translation
filt->set_translation(translation);
return 0;
}
} // namespace openmc
<commit_msg>Updating label, creation, and statepoint methods for the mesh filter.<commit_after>#include "openmc/tallies/filter_mesh.h"
#include <fmt/core.h>
#include <gsl/gsl>
#include "openmc/capi.h"
#include "openmc/constants.h"
#include "openmc/error.h"
#include "openmc/mesh.h"
#include "openmc/xml_interface.h"
namespace openmc {
void
MeshFilter::from_xml(pugi::xml_node node)
{
auto bins_ = get_node_array<int32_t>(node, "bins");
if (bins_.size() != 1) {
fatal_error("Only one mesh can be specified per " + type()
+ " mesh filter.");
}
auto id = bins_[0];
auto search = model::mesh_map.find(id);
if (search != model::mesh_map.end()) {
set_mesh(search->second);
} else{
fatal_error(fmt::format(
"Could not find mesh {} specified on tally filter.", id));
}
if (check_for_node(node, "translation")) {
set_translation(get_node_array<double>(node, "translation"));
}
}
void
MeshFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)
const
{
Position last_r = p.r_last_;
Position r = p.r();
Position u = p.u();
// apply translation if present
if (translated_) {
last_r -= translation_;
r -= translation_;
}
if (estimator != TallyEstimator::TRACKLENGTH) {
auto bin = model::meshes[mesh_]->get_bin(r);
if (bin >= 0) {
match.bins_.push_back(bin);
match.weights_.push_back(1.0);
}
} else {
model::meshes[mesh_]->bins_crossed(last_r, r, u, match.bins_, match.weights_);
}
}
void
MeshFilter::to_statepoint(hid_t filter_group) const
{
Filter::to_statepoint(filter_group);
write_dataset(filter_group, "bins", model::meshes[mesh_]->id_);
if (translated_) {
write_dataset(filter_group, "translation", translation_);
}
}
std::string
MeshFilter::text_label(int bin) const
{
auto& mesh = *model::meshes.at(mesh_);
std::string label = mesh.bin_label(bin);
if (translated_) {
label += fmt::format("\nTranslation: {}, {}, {}\n",
translation_.x, translation_.y, translation_.z);
}
return label;
}
void
MeshFilter::set_mesh(int32_t mesh)
{
mesh_ = mesh;
n_bins_ = model::meshes[mesh_]->n_bins();
}
void MeshFilter::set_translation(const Position& translation)
{
translated_ = true;
translation_ = translation;
}
void MeshFilter::set_translation(const double translation[3])
{
translated_ = true;
translation_ = translation;
}
//==============================================================================
// C-API functions
//==============================================================================
extern "C" int
openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh)
{
if (!index_mesh) {
set_errmsg("Mesh index argument is a null pointer.");
return OPENMC_E_INVALID_ARGUMENT;
}
// Make sure this is a valid index to an allocated filter.
if (int err = verify_filter(index)) return err;
// Get a pointer to the filter and downcast.
const auto& filt_base = model::tally_filters[index].get();
auto* filt = dynamic_cast<MeshFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to get mesh on a non-mesh filter.");
return OPENMC_E_INVALID_TYPE;
}
// Output the mesh.
*index_mesh = filt->mesh();
return 0;
}
extern "C" int
openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh)
{
// Make sure this is a valid index to an allocated filter.
if (int err = verify_filter(index)) return err;
// Get a pointer to the filter and downcast.
const auto& filt_base = model::tally_filters[index].get();
auto* filt = dynamic_cast<MeshFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to set mesh on a non-mesh filter.");
return OPENMC_E_INVALID_TYPE;
}
// Check the mesh index.
if (index_mesh < 0 || index_mesh >= model::meshes.size()) {
set_errmsg("Index in 'meshes' array is out of bounds.");
return OPENMC_E_OUT_OF_BOUNDS;
}
// Update the filter.
filt->set_mesh(index_mesh);
return 0;
}
extern "C" int
openmc_mesh_filter_set_translation(int32_t index, double translation[3])
{
// Make sure this is a valid index to an allocated filter
if (int err = verify_filter(index)) return err;
// Get a pointer to the filter and downcast.
const auto& filt_base = model::tally_filters[index].get();
auto* filt = dynamic_cast<MeshFilter*>(filt_base);
// Check the filter type
if (!filt) {
set_errmsg("Tried to set mesh on a non-mesh filter.");
return OPENMC_E_INVALID_TYPE;
}
// Set the translation
filt->set_translation(translation);
return 0;
}
} // namespace openmc
<|endoftext|> |
<commit_before>#include "amatrix.h"
#include "checks.h"
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestSubMatrixAcess() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
a_matrix(i, j) = 2.33 * i - 4.52 * j;
std::size_t sub_size1 = (TSize1 > 1) ? TSize1 - 1 : 1;
std::size_t sub_size2 = (TSize2 > 1) ? TSize2 - 1 : 1;
std::size_t sub_index1 = (TSize1 > 1) ? 1 : 0;
std::size_t sub_index2 = (TSize2 > 1) ? 1 : 0;
AMatrix::SubMatrix<AMatrix::Matrix<double, TSize1, TSize2>> sub_matrix(
a_matrix, sub_index1, sub_index2, sub_size1, sub_size2);
AMATRIX_CHECK_EQUAL(sub_matrix.size1(), sub_size1);
AMATRIX_CHECK_EQUAL(sub_matrix.size2(), sub_size2);
for (std::size_t i = 0; i < sub_matrix.size1(); i++)
for (std::size_t j = 0; j < sub_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(
sub_matrix(i, j), a_matrix(i + sub_index1, j + sub_index2));
}
return 0; // not failed
}
int main() {
std::size_t number_of_failed_tests = 0;
number_of_failed_tests += TestSubMatrixAcess<1, 1>();
number_of_failed_tests += TestSubMatrixAcess<1, 2>();
number_of_failed_tests += TestSubMatrixAcess<2, 1>();
number_of_failed_tests += TestSubMatrixAcess<2, 2>();
number_of_failed_tests += TestSubMatrixAcess<3, 1>();
number_of_failed_tests += TestSubMatrixAcess<3, 2>();
number_of_failed_tests += TestSubMatrixAcess<3, 3>();
number_of_failed_tests += TestSubMatrixAcess<1, 3>();
number_of_failed_tests += TestSubMatrixAcess<2, 3>();
number_of_failed_tests += TestSubMatrixAcess<3, 3>();
std::cout << number_of_failed_tests << "tests failed" << std::endl;
return number_of_failed_tests;
}
<commit_msg>Adding sub matrix assign test<commit_after>#include "amatrix.h"
#include "checks.h"
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestSubMatrixAcess() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
a_matrix(i, j) = 2.33 * i - 4.52 * j;
std::size_t sub_size1 = (TSize1 > 1) ? TSize1 - 1 : 1;
std::size_t sub_size2 = (TSize2 > 1) ? TSize2 - 1 : 1;
std::size_t sub_index1 = (TSize1 > 1) ? 1 : 0;
std::size_t sub_index2 = (TSize2 > 1) ? 1 : 0;
AMatrix::SubMatrix<AMatrix::Matrix<double, TSize1, TSize2>> sub_matrix(
a_matrix, sub_index1, sub_index2, sub_size1, sub_size2);
AMATRIX_CHECK_EQUAL(sub_matrix.size1(), sub_size1);
AMATRIX_CHECK_EQUAL(sub_matrix.size2(), sub_size2);
for (std::size_t i = 0; i < sub_matrix.size1(); i++)
for (std::size_t j = 0; j < sub_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(
sub_matrix(i, j), a_matrix(i + sub_index1, j + sub_index2));
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestSubMatrixAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix(
AMatrix::ZeroMatrix<double>(TSize1, TSize2));
std::size_t sub_size1 = (TSize1 > 1) ? TSize1 - 1 : 1;
std::size_t sub_size2 = (TSize2 > 1) ? TSize2 - 1 : 1;
std::size_t sub_index1 = (TSize1 > 1) ? 1 : 0;
std::size_t sub_index2 = (TSize2 > 1) ? 1 : 0;
AMatrix::SubMatrix<AMatrix::Matrix<double, TSize1, TSize2>> sub_matrix(
a_matrix, sub_index1, sub_index2, sub_size1, sub_size2);
AMATRIX_CHECK_EQUAL(sub_matrix.size1(), sub_size1);
AMATRIX_CHECK_EQUAL(sub_matrix.size2(), sub_size2);
for (std::size_t i = 0; i < sub_matrix.size1(); i++)
for (std::size_t j = 0; j < sub_matrix.size2(); j++) {
sub_matrix(i, j) = 2.33 * i - 4.52 * j;
}
for (std::size_t i = sub_index1; i < a_matrix.size1(); i++)
for (std::size_t j = sub_index2; j < a_matrix.size2(); j++) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j),
2.33 * (i - sub_index1) - 4.52 * (j - sub_index2));
}
return 0; // not failed
}
int main() {
std::size_t number_of_failed_tests = 0;
number_of_failed_tests += TestSubMatrixAcess<1, 1>();
number_of_failed_tests += TestSubMatrixAcess<1, 2>();
number_of_failed_tests += TestSubMatrixAcess<2, 1>();
number_of_failed_tests += TestSubMatrixAcess<2, 2>();
number_of_failed_tests += TestSubMatrixAcess<3, 1>();
number_of_failed_tests += TestSubMatrixAcess<3, 2>();
number_of_failed_tests += TestSubMatrixAcess<3, 3>();
number_of_failed_tests += TestSubMatrixAcess<1, 3>();
number_of_failed_tests += TestSubMatrixAcess<2, 3>();
number_of_failed_tests += TestSubMatrixAcess<3, 3>();
number_of_failed_tests += TestSubMatrixAssign<1, 1>();
number_of_failed_tests += TestSubMatrixAssign<1, 2>();
number_of_failed_tests += TestSubMatrixAssign<2, 1>();
number_of_failed_tests += TestSubMatrixAssign<2, 2>();
number_of_failed_tests += TestSubMatrixAssign<3, 1>();
number_of_failed_tests += TestSubMatrixAssign<3, 2>();
number_of_failed_tests += TestSubMatrixAssign<3, 3>();
number_of_failed_tests += TestSubMatrixAssign<1, 3>();
number_of_failed_tests += TestSubMatrixAssign<2, 3>();
number_of_failed_tests += TestSubMatrixAssign<3, 3>();
std::cout << number_of_failed_tests << "tests failed" << std::endl;
return number_of_failed_tests;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 deepstreamHub GmbH
*
* 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 <ostream>
#include <client.hpp>
#include <message.hpp>
#include <use.hpp>
#include <cassert>
namespace deepstream {
namespace client
{
std::ostream& operator<<(std::ostream& os, State state)
{
os << static_cast<int>(state);
return os;
}
State transition(State state, const Message& message, Sender sender)
{
assert( state != State::ERROR );
assert( state != State::DISCONNECTED );
const Topic topic = message.topic();
const Action action = message.action();
const bool is_ack = message.is_ack();
const auto expected_num_args = Message::num_arguments( message.header() );
const std::size_t& num_args = message.num_arguments();
use(expected_num_args);
assert( num_args >= expected_num_args.first );
assert( num_args <= expected_num_args.second );
// ping/pong
if( topic == Topic::CONNECTION &&
action == Action::PING &&
sender == Sender::SERVER )
{
assert( !is_ack );
return state;
}
if( topic == Topic::CONNECTION &&
action == Action::PONG &&
sender == Sender::CLIENT )
{
assert( !is_ack );
return state;
}
// actual state transitions
if( state == State::AWAIT_CONNECTION &&
topic == Topic::CONNECTION &&
action == Action::CHALLENGE &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::CHALLENGING;
}
if( state == State::CHALLENGING &&
topic == Topic::CONNECTION &&
action == Action::CHALLENGE_RESPONSE &&
sender == Sender::CLIENT )
{
assert( !is_ack );
return State::CHALLENGING_WAIT;
}
if( state == State::CHALLENGING_WAIT &&
topic == Topic::CONNECTION &&
action == Action::CHALLENGE_RESPONSE &&
sender == Sender::SERVER )
{
assert( is_ack );
return State::AWAIT_AUTHENTICATION;
}
if( state == State::CHALLENGING_WAIT &&
topic == Topic::CONNECTION &&
action == Action::REDIRECT &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::AWAIT_CONNECTION;
}
if( state == State::CHALLENGING_WAIT &&
topic == Topic::CONNECTION &&
action == Action::REJECT &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::DISCONNECTED;
}
if( state == State::AWAIT_AUTHENTICATION &&
topic == Topic::AUTH &&
action == Action::REQUEST &&
sender == Sender::CLIENT )
{
assert( !is_ack );
return State::AUTHENTICATING;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::REQUEST &&
sender == Sender::SERVER )
{
assert( is_ack );
return State::CONNECTED;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::DISCONNECTED;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::ERROR_INVALID_AUTH_DATA &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::AWAIT_AUTHENTICATION;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::ERROR_INVALID_AUTH_MSG &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::DISCONNECTED;
}
if( state == State::CONNECTED &&
topic == Topic::EVENT )
{
if( action == Action::LISTEN ||
action == Action::SUBSCRIBE ||
action == Action::UNLISTEN ||
action == Action::UNSUBSCRIBE )
{
if( (sender == Sender::CLIENT && !is_ack) ||
(sender == Sender::SERVER && is_ack) )
return state;
}
else if( action == Action::EVENT )
return state;
}
return State::ERROR;
}
}
}
<commit_msg>Src: fix client state transition checks<commit_after>/*
* Copyright 2017 deepstreamHub GmbH
*
* 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 <ostream>
#include <client.hpp>
#include <message.hpp>
#include <use.hpp>
#include <cassert>
namespace deepstream {
namespace client
{
std::ostream& operator<<(std::ostream& os, State state)
{
os << static_cast<int>(state);
return os;
}
State transition(State state, const Message& message, Sender sender)
{
assert( state != State::ERROR );
assert( state != State::DISCONNECTED );
const Topic topic = message.topic();
const Action action = message.action();
const bool is_ack = message.is_ack();
const auto expected_num_args = Message::num_arguments( message.header() );
const std::size_t& num_args = message.num_arguments();
use(expected_num_args);
assert( num_args >= expected_num_args.first );
assert( num_args <= expected_num_args.second );
// ping/pong
if( topic == Topic::CONNECTION &&
action == Action::PING &&
sender == Sender::SERVER )
{
assert( !is_ack );
return state;
}
if( topic == Topic::CONNECTION &&
action == Action::PONG &&
sender == Sender::CLIENT )
{
assert( !is_ack );
return state;
}
// actual state transitions
if( state == State::AWAIT_CONNECTION &&
topic == Topic::CONNECTION &&
action == Action::CHALLENGE &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::CHALLENGING;
}
if( state == State::CHALLENGING &&
topic == Topic::CONNECTION &&
action == Action::CHALLENGE_RESPONSE &&
!is_ack &&
sender == Sender::CLIENT )
{
return State::CHALLENGING_WAIT;
}
if( state == State::CHALLENGING_WAIT &&
topic == Topic::CONNECTION &&
action == Action::CHALLENGE_RESPONSE &&
is_ack &&
sender == Sender::SERVER )
{
return State::AWAIT_AUTHENTICATION;
}
if( state == State::CHALLENGING_WAIT &&
topic == Topic::CONNECTION &&
action == Action::REDIRECT &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::AWAIT_CONNECTION;
}
if( state == State::CHALLENGING_WAIT &&
topic == Topic::CONNECTION &&
action == Action::REJECT &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::DISCONNECTED;
}
if( state == State::AWAIT_AUTHENTICATION &&
topic == Topic::AUTH &&
action == Action::REQUEST &&
!is_ack &&
sender == Sender::CLIENT )
{
return State::AUTHENTICATING;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::REQUEST &&
is_ack &&
sender == Sender::SERVER )
{
return State::CONNECTED;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::DISCONNECTED;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::ERROR_INVALID_AUTH_DATA &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::AWAIT_AUTHENTICATION;
}
if( state == State::AUTHENTICATING &&
topic == Topic::AUTH &&
action == Action::ERROR_INVALID_AUTH_MSG &&
sender == Sender::SERVER )
{
assert( !is_ack );
return State::DISCONNECTED;
}
if( state == State::CONNECTED &&
topic == Topic::EVENT )
{
if( action == Action::LISTEN ||
action == Action::SUBSCRIBE ||
action == Action::UNLISTEN ||
action == Action::UNSUBSCRIBE )
{
if( (sender == Sender::CLIENT && !is_ack) ||
(sender == Sender::SERVER && is_ack) )
return state;
}
else if( action == Action::EVENT )
return state;
}
return State::ERROR;
}
}
}
<|endoftext|> |
<commit_before>// The Modified BSD License
//
// Copyright (c) 2015, Mikhail Balakhno
// 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 fontio 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 <fstream>
#include <gtest/gtest.h>
#include <fontio/logic/cff/CffReader.hpp>
#include <fontio/logic/type2/Type2GlyphMetricsCalculator.hpp>
namespace fontio { namespace logic { namespace type2
{
using namespace fontio::logic::cff;
using namespace fontio::model;
using namespace fontio::model::cff;
using namespace fontio::model::type2;
class Type2GlyphMetricsCalculatorTests : public testing::Test
{
protected:
CffReader reader;
Type2GlyphMetricsCalculator calculator;
protected:
std::unique_ptr<Cff> ReadCffFile(const std::string& filename)
{
std::ifstream stream(filename, std::ios_base::binary);
return this->reader.ReadCff(stream);
}
};
TEST_F(Type2GlyphMetricsCalculatorTests, CanCalculateMetrics)
{
auto cff = this->ReadCffFile("test_data/cff/bare.cff");
const auto& charstrings = static_cast<const CffType2Charstrings&>(cff->GetTopDicts()[0].GetCharstrings()).GetCharstrings();
auto metrics = this->calculator.CalculateMetrics(
charstrings[10],
Type2SubroutineAccessor(),
Type2SubroutineAccessor(),
472,
220);
ASSERT_EQ(328, metrics.GetAdvanceWidth());
ASSERT_EQ(12, metrics.GetBoundBox().GetX0());
ASSERT_EQ(-120, metrics.GetBoundBox().GetY0());
ASSERT_EQ(273, metrics.GetBoundBox().GetX1());
ASSERT_EQ(739, metrics.GetBoundBox().GetY1());
ASSERT_EQ(12, metrics.GetLeftSideBearings());
}
} } }
<commit_msg>Added test for width calculation, which yet fails.<commit_after>// The Modified BSD License
//
// Copyright (c) 2015, Mikhail Balakhno
// 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 fontio 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 <fstream>
#include <gtest/gtest.h>
#include <fontio/logic/cff/CffReader.hpp>
#include <fontio/logic/type2/Type2GlyphMetricsCalculator.hpp>
namespace fontio { namespace logic { namespace type2
{
using namespace fontio::logic::cff;
using namespace fontio::model;
using namespace fontio::model::cff;
using namespace fontio::model::type2;
class Type2GlyphMetricsCalculatorTests : public testing::Test
{
protected:
CffReader reader;
Type2GlyphMetricsCalculator calculator;
protected:
std::unique_ptr<Cff> ReadCffFile(const std::string& filename)
{
std::ifstream stream(filename, std::ios_base::binary);
return this->reader.ReadCff(stream);
}
};
TEST_F(Type2GlyphMetricsCalculatorTests, CanCalculateMetrics)
{
auto cff = this->ReadCffFile("test_data/cff/bare.cff");
const auto& charstrings = static_cast<const CffType2Charstrings&>(cff->GetTopDicts()[0].GetCharstrings()).GetCharstrings();
auto metrics = this->calculator.CalculateMetrics(
charstrings[10],
Type2SubroutineAccessor(),
Type2SubroutineAccessor(),
472,
220);
ASSERT_EQ(328, metrics.GetAdvanceWidth());
ASSERT_EQ(12, metrics.GetBoundBox().GetX0());
ASSERT_EQ(-120, metrics.GetBoundBox().GetY0());
ASSERT_EQ(273, metrics.GetBoundBox().GetX1());
ASSERT_EQ(739, metrics.GetBoundBox().GetY1());
ASSERT_EQ(12, metrics.GetLeftSideBearings());
}
TEST_F(Type2GlyphMetricsCalculatorTests, CanCalculateSpaceWidth)
{
auto cff = this->ReadCffFile("test_data/cff/test_font_width.cff");
const auto& topDict = cff->GetTopDicts()[0];
const auto& charstrings = static_cast<const CffType2Charstrings&>(topDict.GetCharstrings()).GetCharstrings();
auto metrics = this->calculator.CalculateMetrics(
charstrings[0],
Type2SubroutineAccessor(),
Type2SubroutineAccessor(),
topDict.GetNominalWidthX(),
topDict.GetDefaultWidthX());
ASSERT_EQ(227, metrics.GetAdvanceWidth());
}
} } }
<|endoftext|> |
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fstream>
#include <iostream>
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
return 0;
}
<commit_msg>:construction: chore(tadpole): updated the main entry<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fstream>
#include <iostream>
#include "Common/Common.hh"
int main(int argc, char* argv[]) {
TADPOLE_UNUSED(argc), TADPOLE_UNUSED(argv);
return 0;
}
<|endoftext|> |
<commit_before>// Filename: hdf2vertex.C
// Created on 31 May 2007 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// 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 New York University 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.
/////////////////////////////// INCLUDES /////////////////////////////////////
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <H5LT.h>
/////////////////////////////// NAMESPACE ////////////////////////////////////
using namespace std;
/////////////////////////////// STATIC ///////////////////////////////////////
inline string
discard_comments(
const string& input_string)
{
// Create a copy of the input string, but without any text following a '!',
// '#', or '%' character.
string output_string = input_string;
istringstream string_stream;
// Discard any text following a '!' character.
string_stream.str(output_string);
getline(string_stream, output_string, '!');
string_stream.clear();
// Discard any text following a '#' character.
string_stream.str(output_string);
getline(string_stream, output_string, '#');
string_stream.clear();
// Discard any text following a '%' character.
string_stream.str(output_string);
getline(string_stream, output_string, '%');
string_stream.clear();
return output_string;
}// discard_comments
int
main(
int argc,
char* argv[])
{
if (argc != 3)
{
cout << argv[0] << ": a tool to convert IBAMR vertex files from HDF5 to ASCII" << "\n"
<< "USAGE: " << argv[0] << " <input filename> <output filename>" << endl;
return -1;
}
const string input_filename = argv[1];
const string output_filename = argv[2];
cout << "input file name: " << input_filename << "\n"
<< "output file name: " << output_filename << "\n";
// Ensure that the input file exists, and that the output file does not.
ifstream input_fstream, output_fstream;
input_fstream.open(input_filename.c_str(), ios::in);
output_fstream.open(output_filename.c_str(), ios::in);
if (!input_fstream.is_open())
{
cout << "error: Unable to open input file " << input_filename << endl;
return -1;
}
if (output_fstream.is_open())
{
cout << "error: Output file " << output_filename << " already exists" << endl;
return -1;
}
input_fstream.close();
output_fstream.close();
// Process the HDF5 file.
hid_t file_id;
int rank;
hsize_t dims[2];
H5T_class_t class_id;
size_t type_size;
herr_t status;
file_id = H5Fopen(input_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
if (file_id < 0)
{
cout << "error: Unable to open input file " << input_filename << endl;
return -1;
}
if (!H5LTfind_dataset(file_id, "vertex"))
{
cout << "error: Cannot find vertex dataset in input file " << input_filename << endl;
return -1;
}
status = H5LTget_dataset_ndims(file_id, "vertex", &rank);
if (rank != 2)
{
cout << "error: Invalid dataset rank in input file " << input_filename << endl;
return -1;
}
status = H5LTget_dataset_info(file_id, "vertex", &dims[0], &class_id, &type_size);
if (dims[0] != NDIM || dims[1] <= 0)
{
cout << "error: Invalid dataset dimension in input file " << input_filename << endl;
return -1;
}
static const int num_vertex = dims[1];
vector<double> vertex_posn(NDIM*num_vertex);
status = H5LTread_dataset_static_cast<double>(file_id, "vertex", &vertex_posn[0]);
status = H5Fclose(file_id);
// Output the vertex file.
ofstream file_stream;
file_stream.open(output_filename.c_str(), ios::out);
if (!file_stream.is_open())
{
cout << "error: Unable to open output file " << output_filename << endl;
return -1;
}
// The first entry in the file is the number of vertices.
ostringstream stream;
stream << num_vertex;
string first_line(stream.str());
first_line.resize((NDIM == 2 ? 46 : 69),' ');
file_stream << first_line << "# number of vertices\n";
// Each successive line provides the initial position of each vertex in the
// input file.
for (int k = 0; k < num_vertex; ++k)
{
for (unsigned int d = 0; d < NDIM; ++d)
{
file_stream.setf(ios_base::scientific);
file_stream.precision(16);
file_stream << vertex_posn[k*NDIM+d];
if (d < NDIM-1) file_stream << " ";
}
#if (NDIM == 2)
if (k == 0) file_stream << " # x-coord, y-coord";
#endif
#if (NDIM == 3)
if (k == 0) file_stream << " # x-coord, y-coord, z-coord";
#endif
file_stream << "\n";
}
// Close the output file.
file_stream.close();
return 0;
}// main
/////////////////////////////// PUBLIC ///////////////////////////////////////
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
<commit_msg>fixing HDF5 headers in branches/ibamr-dev<commit_after>// Filename: hdf2vertex.C
// Created on 31 May 2007 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// 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 New York University 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.
/////////////////////////////// INCLUDES /////////////////////////////////////
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <hdf5.h>
#include <hdf5_lt.h>
/////////////////////////////// NAMESPACE ////////////////////////////////////
using namespace std;
/////////////////////////////// STATIC ///////////////////////////////////////
inline string
discard_comments(
const string& input_string)
{
// Create a copy of the input string, but without any text following a '!',
// '#', or '%' character.
string output_string = input_string;
istringstream string_stream;
// Discard any text following a '!' character.
string_stream.str(output_string);
getline(string_stream, output_string, '!');
string_stream.clear();
// Discard any text following a '#' character.
string_stream.str(output_string);
getline(string_stream, output_string, '#');
string_stream.clear();
// Discard any text following a '%' character.
string_stream.str(output_string);
getline(string_stream, output_string, '%');
string_stream.clear();
return output_string;
}// discard_comments
int
main(
int argc,
char* argv[])
{
if (argc != 3)
{
cout << argv[0] << ": a tool to convert IBAMR vertex files from HDF5 to ASCII" << "\n"
<< "USAGE: " << argv[0] << " <input filename> <output filename>" << endl;
return -1;
}
const string input_filename = argv[1];
const string output_filename = argv[2];
cout << "input file name: " << input_filename << "\n"
<< "output file name: " << output_filename << "\n";
// Ensure that the input file exists, and that the output file does not.
ifstream input_fstream, output_fstream;
input_fstream.open(input_filename.c_str(), ios::in);
output_fstream.open(output_filename.c_str(), ios::in);
if (!input_fstream.is_open())
{
cout << "error: Unable to open input file " << input_filename << endl;
return -1;
}
if (output_fstream.is_open())
{
cout << "error: Output file " << output_filename << " already exists" << endl;
return -1;
}
input_fstream.close();
output_fstream.close();
// Process the HDF5 file.
hid_t file_id;
int rank;
hsize_t dims[2];
H5T_class_t class_id;
size_t type_size;
herr_t status;
file_id = H5Fopen(input_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
if (file_id < 0)
{
cout << "error: Unable to open input file " << input_filename << endl;
return -1;
}
if (!H5LTfind_dataset(file_id, "vertex"))
{
cout << "error: Cannot find vertex dataset in input file " << input_filename << endl;
return -1;
}
status = H5LTget_dataset_ndims(file_id, "vertex", &rank);
if (rank != 2)
{
cout << "error: Invalid dataset rank in input file " << input_filename << endl;
return -1;
}
status = H5LTget_dataset_info(file_id, "vertex", &dims[0], &class_id, &type_size);
if (dims[0] != NDIM || dims[1] <= 0)
{
cout << "error: Invalid dataset dimension in input file " << input_filename << endl;
return -1;
}
static const int num_vertex = dims[1];
vector<double> vertex_posn(NDIM*num_vertex);
status = H5LTread_dataset_static_cast<double>(file_id, "vertex", &vertex_posn[0]);
status = H5Fclose(file_id);
// Output the vertex file.
ofstream file_stream;
file_stream.open(output_filename.c_str(), ios::out);
if (!file_stream.is_open())
{
cout << "error: Unable to open output file " << output_filename << endl;
return -1;
}
// The first entry in the file is the number of vertices.
ostringstream stream;
stream << num_vertex;
string first_line(stream.str());
first_line.resize((NDIM == 2 ? 46 : 69),' ');
file_stream << first_line << "# number of vertices\n";
// Each successive line provides the initial position of each vertex in the
// input file.
for (int k = 0; k < num_vertex; ++k)
{
for (unsigned int d = 0; d < NDIM; ++d)
{
file_stream.setf(ios_base::scientific);
file_stream.precision(16);
file_stream << vertex_posn[k*NDIM+d];
if (d < NDIM-1) file_stream << " ";
}
#if (NDIM == 2)
if (k == 0) file_stream << " # x-coord, y-coord";
#endif
#if (NDIM == 3)
if (k == 0) file_stream << " # x-coord, y-coord, z-coord";
#endif
file_stream << "\n";
}
// Close the output file.
file_stream.close();
return 0;
}// main
/////////////////////////////// PUBLIC ///////////////////////////////////////
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "acmacs-base/argv.hh"
#include "acmacs-base/string.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"
#include "seqdb-3/seqdb.hh"
#include "hidb-5/hidb.hh"
#include "hidb-5/report.hh"
// ----------------------------------------------------------------------
struct AntigenData
{
size_t no;
const hidb::HiDb* hidb = nullptr;
std::shared_ptr<acmacs::chart::Antigen> antigen_chart;
std::shared_ptr<hidb::Antigen> antigen_hidb;
acmacs::seqdb::ref antigen_seqdb;
};
template <> struct fmt::formatter<AntigenData> : fmt::formatter<acmacs::fmt_default_formatter> {
template <typename FormatCtx> auto format(const AntigenData& ag, FormatCtx& ctx)
{
format_to(ctx.out(), "{} {}", ag.no, *ag.antigen_chart);
if (ag.antigen_hidb)
hidb::report_tables(std::cout, *ag.hidb, ag.antigen_hidb->tables(), hidb::report_tables::recent, "\n ");
if (ag.antigen_seqdb) {
if (const auto& clades = ag.antigen_seqdb.seq().clades; !clades.empty())
format_to(ctx.out(), "\n clades: {}", clades);
}
return ctx.out();
}
};
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
// option<str> db_dir{*this, "db-dir"};
option<str> seqdb{*this, "seqdb"};
option<bool> sort_by_tables{*this, "sort-by-tables"};
option<str> clade{*this, "clade"};
option<str> aa{*this, "aa", desc{"report AA at given positions (comma separated)"}};
option<bool> verbose{*this, 'v', "verbose"};
argument<str> chart_file{*this, arg_name{"chart"}, mandatory};
};
int main(int argc, char* const argv[])
{
int exit_code = 0;
try {
Options opt(argc, argv);
acmacs::seqdb::setup(opt.seqdb);
const std::vector<size_t> report_aa_at_pos = opt.aa ? acmacs::string::split_into_size_t(*opt.aa, ",") : std::vector<size_t>{};
auto chart = acmacs::chart::import_from_file(opt.chart_file);
const auto virus_type = chart->info()->virus_type(acmacs::chart::Info::Compute::Yes);
const auto& seqdb = acmacs::seqdb::get();
const auto& hidb = hidb::get(virus_type); // , do_report_time(verbose));
auto antigens_chart = chart->antigens();
const auto hidb_antigens = hidb.antigens()->find(*antigens_chart);
const auto seqdb_antigens = seqdb.match(*antigens_chart, virus_type);
std::vector<AntigenData> antigens(antigens_chart->size());
std::transform(acmacs::index_iterator(0UL), acmacs::index_iterator(antigens_chart->size()), antigens.begin(), [&](size_t index) -> AntigenData {
return {index, &hidb, antigens_chart->at(index), hidb_antigens[index], seqdb_antigens[index]};
});
if (opt.clade)
antigens.erase(std::remove_if(antigens.begin(), antigens.end(), [clade = *opt.clade](const auto& ag) -> bool { return !ag.antigen_seqdb || !ag.antigen_seqdb.seq().has_clade(clade); }),
antigens.end());
std::cerr << "INFO: " << antigens.size() << " antigens upon filtering\n";
if (opt.sort_by_tables) {
auto hidb_tables = hidb.tables();
std::sort(antigens.begin(), antigens.end(), [&](const auto& e1, const auto& e2) -> bool {
if (!e1.antigen_hidb)
return false;
if (!e2.antigen_hidb)
return true;
if (const auto nt1 = e1.antigen_hidb->number_of_tables(), nt2 = e2.antigen_hidb->number_of_tables(); nt1 == nt2) {
auto mrt1 = hidb_tables->most_recent(e1.antigen_hidb->tables()), mrt2 = hidb_tables->most_recent(e2.antigen_hidb->tables());
return mrt1->date() > mrt2->date();
}
else
return nt1 > nt2;
});
}
for (const auto& ad : antigens) {
fmt::print("{}\n", ad);
if (!report_aa_at_pos.empty()) {
const auto aa = ad.antigen_seqdb.seq().amino_acids.aligned();
fmt::print(" ");
for (auto pos : report_aa_at_pos) {
fmt::print(" {}", pos);
if (aa.size() >= pos)
fmt::print("{}", aa[pos - 1]);
else
fmt::print("?");
}
fmt::print("\n");
}
}
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>handing seqdb ref with a reference<commit_after>#include "acmacs-base/argv.hh"
#include "acmacs-base/string.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"
#include "seqdb-3/seqdb.hh"
#include "hidb-5/hidb.hh"
#include "hidb-5/report.hh"
// ----------------------------------------------------------------------
struct AntigenData
{
size_t no;
const hidb::HiDb* hidb = nullptr;
std::shared_ptr<acmacs::chart::Antigen> antigen_chart;
std::shared_ptr<hidb::Antigen> antigen_hidb;
acmacs::seqdb::ref antigen_seqdb;
};
template <> struct fmt::formatter<AntigenData> : fmt::formatter<acmacs::fmt_default_formatter> {
template <typename FormatCtx> auto format(const AntigenData& ag, FormatCtx& ctx)
{
format_to(ctx.out(), "{} {}", ag.no, *ag.antigen_chart);
if (ag.antigen_hidb)
hidb::report_tables(std::cout, *ag.hidb, ag.antigen_hidb->tables(), hidb::report_tables::recent, "\n ");
if (ag.antigen_seqdb) {
if (const auto& clades = ag.antigen_seqdb.seq().clades; !clades.empty())
format_to(ctx.out(), "\n clades: {}", clades);
}
return ctx.out();
}
};
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
// option<str> db_dir{*this, "db-dir"};
option<str> seqdb{*this, "seqdb"};
option<bool> sort_by_tables{*this, "sort-by-tables"};
option<str> clade{*this, "clade"};
option<str> aa{*this, "aa", desc{"report AA at given positions (comma separated)"}};
option<bool> verbose{*this, 'v', "verbose"};
argument<str> chart_file{*this, arg_name{"chart"}, mandatory};
};
int main(int argc, char* const argv[])
{
int exit_code = 0;
try {
Options opt(argc, argv);
acmacs::seqdb::setup(opt.seqdb);
const std::vector<size_t> report_aa_at_pos = opt.aa ? acmacs::string::split_into_size_t(*opt.aa, ",") : std::vector<size_t>{};
auto chart = acmacs::chart::import_from_file(opt.chart_file);
const auto virus_type = chart->info()->virus_type(acmacs::chart::Info::Compute::Yes);
const auto& seqdb = acmacs::seqdb::get();
const auto& hidb = hidb::get(virus_type); // , do_report_time(verbose));
auto antigens_chart = chart->antigens();
const auto hidb_antigens = hidb.antigens()->find(*antigens_chart);
const auto seqdb_antigens = seqdb.match(*antigens_chart, virus_type);
std::vector<AntigenData> antigens(antigens_chart->size());
std::transform(acmacs::index_iterator(0UL), acmacs::index_iterator(antigens_chart->size()), antigens.begin(), [&](size_t index) -> AntigenData {
return {index, &hidb, antigens_chart->at(index), hidb_antigens[index], seqdb_antigens[index]};
});
if (opt.clade)
antigens.erase(std::remove_if(antigens.begin(), antigens.end(), [&seqdb, clade = *opt.clade](const auto& ag) -> bool { return !ag.antigen_seqdb || !ag.antigen_seqdb.has_clade(seqdb, clade); }),
antigens.end());
std::cerr << "INFO: " << antigens.size() << " antigens upon filtering\n";
if (opt.sort_by_tables) {
auto hidb_tables = hidb.tables();
std::sort(antigens.begin(), antigens.end(), [&](const auto& e1, const auto& e2) -> bool {
if (!e1.antigen_hidb)
return false;
if (!e2.antigen_hidb)
return true;
if (const auto nt1 = e1.antigen_hidb->number_of_tables(), nt2 = e2.antigen_hidb->number_of_tables(); nt1 == nt2) {
auto mrt1 = hidb_tables->most_recent(e1.antigen_hidb->tables()), mrt2 = hidb_tables->most_recent(e2.antigen_hidb->tables());
return mrt1->date() > mrt2->date();
}
else
return nt1 > nt2;
});
}
for (const auto& ad : antigens) {
fmt::print("{}\n", ad);
if (!report_aa_at_pos.empty()) {
const auto aa = ad.antigen_seqdb.seq().amino_acids.aligned();
fmt::print(" ");
for (auto pos : report_aa_at_pos) {
fmt::print(" {}", pos);
if (aa.size() >= pos)
fmt::print("{}", aa[pos - 1]);
else
fmt::print("?");
}
fmt::print("\n");
}
}
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "external_task.h"
#include "../sandbox/isolate_sandbox.h"
#include "../helpers/string_utils.h"
#include <fstream>
#include <algorithm>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
external_task::external_task(const create_params &data)
: task_base(data.id, data.task_meta), worker_config_(data.worker_conf), sandbox_(nullptr),
sandbox_config_(data.task_meta->sandbox), limits_(data.limits), logger_(data.logger), temp_dir_(data.temp_dir),
source_dir_(data.source_path), working_dir_(data.working_path)
{
if (worker_config_ == nullptr) {
throw task_exception("No worker configuration provided.");
}
if (limits_ == nullptr) {
throw task_exception("No limits provided.");
}
if (sandbox_config_ == nullptr) {
throw task_exception("No sandbox configuration provided.");
}
sandbox_check();
}
external_task::~external_task()
{
}
void external_task::sandbox_check()
{
bool found = false;
#ifndef _WIN32
if (task_meta_->sandbox->name == "isolate") {
found = true;
}
#endif
if (found == false) {
throw task_exception("Unknown sandbox type: " + task_meta_->sandbox->name);
}
}
void external_task::sandbox_init()
{
#ifndef _WIN32
if (task_meta_->sandbox->name == "isolate") {
sandbox_ = std::make_shared<isolate_sandbox>(
sandbox_config_, *limits_, worker_config_->get_worker_id(), temp_dir_, logger_);
}
#endif
}
void external_task::sandbox_fini()
{
sandbox_ = nullptr;
}
std::shared_ptr<task_results> external_task::run()
{
sandbox_init();
// TODO: only temporary solution, should be removed
if (sandbox_ == nullptr) {
return nullptr;
}
// initialize output from stdout and stderr
results_output_init();
// check if binary is executable and set it otherwise
make_binary_executable(task_meta_->binary);
std::shared_ptr<task_results> res(new task_results());
res->sandbox_status =
std::unique_ptr<sandbox_results>(new sandbox_results(sandbox_->run(task_meta_->binary, task_meta_->cmd_args)));
// get output from stdout and stderr
res->sandbox_status->output = get_results_output();
sandbox_fini();
// Check if sandbox ran successfully, else report error
if (res->sandbox_status->status != isolate_status::OK) {
res->status = task_status::FAILED;
res->error_message = "Sandboxed program failed: " + res->sandbox_status->message;
}
return res;
}
std::shared_ptr<sandbox_limits> external_task::get_limits()
{
return limits_;
}
void external_task::results_output_init()
{
if (sandbox_config_->output) {
std::string random = helpers::random_alphanum_string(10);
if (sandbox_config_->std_output == "") {
remove_stdout_ = true;
std::string stdout_file = task_meta_->task_id + "." + random + ".output.stdout";
sandbox_config_->std_output = (working_dir_ / fs::path(stdout_file)).string();
}
if (sandbox_config_->std_error == "") {
remove_stderr_ = true;
std::string stderr_file = task_meta_->task_id + "." + random + ".output.stderr";
sandbox_config_->std_error = (working_dir_ / fs::path(stderr_file)).string();
}
}
}
fs::path external_task::find_path_outside_sandbox(std::string file)
{
fs::path file_path = fs::path(file);
fs::path sandbox_dir = file_path.parent_path();
for (auto &dir : limits_->bound_dirs) {
fs::path sandbox_dir_bound = fs::path(std::get<1>(dir));
if (sandbox_dir_bound == sandbox_dir) {
return fs::path(std::get<0>(dir)) / file_path.filename();
}
}
return fs::path();
}
std::string external_task::get_results_output()
{
std::string result;
if (sandbox_config_->output) {
size_t count = worker_config_->get_max_output_length();
std::string result_stdout(count, 0);
std::string result_stderr(count, 0);
// files were outputted inside sandbox, so we have to find path outside sandbox
fs::path stdout_file_path = find_path_outside_sandbox(sandbox_config_->std_output);
fs::path stderr_file_path = find_path_outside_sandbox(sandbox_config_->std_error);
// open and read files
std::ifstream std_out(stdout_file_path.string());
std::ifstream std_err(stderr_file_path.string());
std_out.read(&result_stdout[0], count);
std_err.read(&result_stderr[0], count);
// if there was something in one of the files, write it to the result
if (std_out.gcount() != 0 || std_err.gcount() != 0) {
result = result_stdout.substr(0, std_out.gcount()) + result_stderr.substr(0, std_err.gcount());
}
// delete produced files
try {
if (remove_stdout_) {
fs::remove(stdout_file_path);
}
if (remove_stderr_) {
fs::remove(stderr_file_path);
}
} catch (fs::filesystem_error &e) {
logger_->warn("Temporary sandbox output files not cleaned properly: {}", e.what());
}
}
return result;
}
void external_task::make_binary_executable(std::string binary)
{
try {
fs::permissions(
fs::path(binary), fs::perms::add_perms | fs::perms::owner_exe | fs::perms::group_exe | fs::others_exe);
} catch (fs::filesystem_error &e) {
auto message = std::string("Failed to set executable bits for executed binary. Error: ") + e.what();
logger_->warn(message);
throw sandbox_exception(message);
}
}
<commit_msg>Path to binary is inside sandbox, reflect this in permission setting<commit_after>#include "external_task.h"
#include "../sandbox/isolate_sandbox.h"
#include "../helpers/string_utils.h"
#include <fstream>
#include <algorithm>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
external_task::external_task(const create_params &data)
: task_base(data.id, data.task_meta), worker_config_(data.worker_conf), sandbox_(nullptr),
sandbox_config_(data.task_meta->sandbox), limits_(data.limits), logger_(data.logger), temp_dir_(data.temp_dir),
source_dir_(data.source_path), working_dir_(data.working_path)
{
if (worker_config_ == nullptr) {
throw task_exception("No worker configuration provided.");
}
if (limits_ == nullptr) {
throw task_exception("No limits provided.");
}
if (sandbox_config_ == nullptr) {
throw task_exception("No sandbox configuration provided.");
}
sandbox_check();
}
external_task::~external_task()
{
}
void external_task::sandbox_check()
{
bool found = false;
#ifndef _WIN32
if (task_meta_->sandbox->name == "isolate") {
found = true;
}
#endif
if (found == false) {
throw task_exception("Unknown sandbox type: " + task_meta_->sandbox->name);
}
}
void external_task::sandbox_init()
{
#ifndef _WIN32
if (task_meta_->sandbox->name == "isolate") {
sandbox_ = std::make_shared<isolate_sandbox>(
sandbox_config_, *limits_, worker_config_->get_worker_id(), temp_dir_, logger_);
}
#endif
}
void external_task::sandbox_fini()
{
sandbox_ = nullptr;
}
std::shared_ptr<task_results> external_task::run()
{
sandbox_init();
// TODO: only temporary solution, should be removed
if (sandbox_ == nullptr) {
return nullptr;
}
// initialize output from stdout and stderr
results_output_init();
// check if binary is executable and set it otherwise
make_binary_executable(task_meta_->binary);
std::shared_ptr<task_results> res(new task_results());
res->sandbox_status =
std::unique_ptr<sandbox_results>(new sandbox_results(sandbox_->run(task_meta_->binary, task_meta_->cmd_args)));
// get output from stdout and stderr
res->sandbox_status->output = get_results_output();
sandbox_fini();
// Check if sandbox ran successfully, else report error
if (res->sandbox_status->status != isolate_status::OK) {
res->status = task_status::FAILED;
res->error_message = "Sandboxed program failed: " + res->sandbox_status->message;
}
return res;
}
std::shared_ptr<sandbox_limits> external_task::get_limits()
{
return limits_;
}
void external_task::results_output_init()
{
if (sandbox_config_->output) {
std::string random = helpers::random_alphanum_string(10);
if (sandbox_config_->std_output == "") {
remove_stdout_ = true;
std::string stdout_file = task_meta_->task_id + "." + random + ".output.stdout";
sandbox_config_->std_output = (working_dir_ / fs::path(stdout_file)).string();
}
if (sandbox_config_->std_error == "") {
remove_stderr_ = true;
std::string stderr_file = task_meta_->task_id + "." + random + ".output.stderr";
sandbox_config_->std_error = (working_dir_ / fs::path(stderr_file)).string();
}
}
}
fs::path external_task::find_path_outside_sandbox(std::string file)
{
fs::path file_path = fs::path(file);
if (!file_path.has_root_directory()) {
// relative path to chdir
return fs::path(sandbox_config_->chdir) / file_path;
}
// absolute path in sandbox provided
fs::path sandbox_dir = file_path.parent_path();
for (auto &dir : limits_->bound_dirs) {
fs::path sandbox_dir_bound = fs::path(std::get<1>(dir));
if (sandbox_dir_bound == sandbox_dir) {
return fs::path(std::get<0>(dir)) / file_path.filename();
}
}
return fs::path();
}
std::string external_task::get_results_output()
{
std::string result;
if (sandbox_config_->output) {
size_t count = worker_config_->get_max_output_length();
std::string result_stdout(count, 0);
std::string result_stderr(count, 0);
// files were outputted inside sandbox, so we have to find path outside sandbox
fs::path stdout_file_path = find_path_outside_sandbox(sandbox_config_->std_output);
fs::path stderr_file_path = find_path_outside_sandbox(sandbox_config_->std_error);
// open and read files
std::ifstream std_out(stdout_file_path.string());
std::ifstream std_err(stderr_file_path.string());
std_out.read(&result_stdout[0], count);
std_err.read(&result_stderr[0], count);
// if there was something in one of the files, write it to the result
if (std_out.gcount() != 0 || std_err.gcount() != 0) {
result = result_stdout.substr(0, std_out.gcount()) + result_stderr.substr(0, std_err.gcount());
}
// delete produced files
try {
if (remove_stdout_) {
fs::remove(stdout_file_path);
}
if (remove_stderr_) {
fs::remove(stderr_file_path);
}
} catch (fs::filesystem_error &e) {
logger_->warn("Temporary sandbox output files not cleaned properly: {}", e.what());
}
}
return result;
}
void external_task::make_binary_executable(std::string binary)
{
try {
fs::path binary_path = find_path_outside_sandbox(binary);
fs::permissions(
binary_path, fs::perms::add_perms | fs::perms::owner_exe | fs::perms::group_exe | fs::others_exe);
} catch (fs::filesystem_error &e) {
auto message = std::string("Failed to set executable bits for executed binary. Error: ") + e.what();
logger_->warn(message);
throw sandbox_exception(message);
}
}
<|endoftext|> |
<commit_before>#include "cnn/expr.h"
#include <initializer_list>
#include "cnn/nodes.h"
#include "cnn/conv.h"
namespace cnn { namespace expr {
Expression input(ComputationGraph& g, real s) { return Expression(&g, g.add_input(s)); }
Expression input(ComputationGraph& g, const real *ps) { return Expression(&g, g.add_input(ps)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>& pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>* pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression reference(ComputationGraph& g, const Dim& d, const cnn::real* pdata) { return Expression(&g, g.add_reference(d, pdata)); }
Expression const_parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_const_parameters(p)); }
Expression parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_parameters(p)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_lookup(p, index)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_lookup(p, pindex)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_lookup(p, indices)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_lookup(p, pindices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_const_lookup(p, index)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_const_lookup(p, pindex)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_const_lookup(p, indices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_const_lookup(p, pindices)); }
Expression zeroes(ComputationGraph& g, const Dim& d) { return Expression(&g, g.add_function<Zeroes>(d)); }
Expression operator-(const Expression& x) { return Expression(x.pg, x.pg->add_function<Negate>({x.i})); }
Expression operator+(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Sum>({x.i, y.i})); }
Expression operator+(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantPlusX>({y.i}, x)); }
Expression operator+(const Expression& x, real y) { return y+x; }
Expression operator-(const Expression& x, const Expression& y) { return x+(-y); }
Expression operator-(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantMinusX>({y.i}, x)); }
Expression operator-(const Expression& x, real y) { return -(y-x); }
Expression operator*(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<MatrixMultiply>({x.i, y.i})); }
Expression operator*(const Expression& x, cnn::real y) { return Expression(x.pg, x.pg->add_function<ConstScalarMultiply>({x.i}, y)); }
Expression cdiv(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<CwiseQuotient>({x.i, y.i})); }
Expression colwise_add(const Expression& x, const Expression& bias) { return Expression(x.pg, x.pg->add_function<AddVectorToAllColumns>({x.i, bias.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i, b.i})); }
Expression sqrt(const Expression& x) { return Expression(x.pg, x.pg->add_function<Sqrt>({x.i})); }
//Expression erf(const Expression& x) { return Expression(x.pg, x.pg->add_function<Erf>({x.i})); }
Expression tanh(const Expression& x) { return Expression(x.pg, x.pg->add_function<Tanh>({x.i})); }
//Expression lgamma(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogGamma>({x.i})); }
Expression log(const Expression& x) { return Expression(x.pg, x.pg->add_function<Log>({x.i})); }
Expression exp(const Expression& x) { return Expression(x.pg, x.pg->add_function<Exp>({x.i})); }
Expression square(const Expression& x) { return Expression(x.pg, x.pg->add_function<Square>({x.i})); }
Expression cube(const Expression& x) { return Expression(x.pg, x.pg->add_function<Cube>({x.i})); }
Expression logistic(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogisticSigmoid>({x.i})); }
Expression rectify(const Expression& x) { return Expression(x.pg, x.pg->add_function<Rectify>({x.i})); }
Expression hinge(const Expression& x, unsigned index, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({x.i}, index, m)); }
Expression hinge(const Expression& x, const unsigned* pindex, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({x.i}, pindex, m)); }
Expression log_softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogSoftmax>({x.i})); }
Expression log_softmax(const Expression& x, const std::vector<unsigned>& d) { return Expression(x.pg, x.pg->add_function<RestrictedLogSoftmax>({x.i}, d)); }
Expression softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<Softmax>({x.i})); }
Expression softsign(const Expression& x) { return Expression(x.pg, x.pg->add_function<SoftSign>({x.i})); }
Expression pow(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Pow>({x.i, y.i})); }
Expression min(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Min>({x.i, y.i})); }
Expression max(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Max>({x.i, y.i})); }
Expression noise(const Expression& x, real stddev) { return Expression(x.pg, x.pg->add_function<GaussianNoise>({x.i}, stddev)); }
Expression dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<Dropout>({x.i}, p)); }
Expression block_dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<BlockDropout>({x.i}, p)); }
Expression reshape(const Expression& x, const Dim& d) { return Expression(x.pg, x.pg->add_function<Reshape>({x.i}, d)); }
Expression transpose(const Expression& x) { return Expression(x.pg, x.pg->add_function<Transpose>({x.i})); }
Expression trace_of_product(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<TraceOfProduct>({x.i, y.i}));}
Expression cwise_multiply(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<CwiseMultiply>({x.i, y.i}));}
Expression dot_product(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<DotProduct>({x.i, y.i})); }
Expression squared_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<SquaredEuclideanDistance>({x.i, y.i})); }
Expression huber_distance(const Expression& x, const Expression& y, real c) { return Expression(x.pg, x.pg->add_function<HuberDistance>({x.i, y.i}, c)); }
Expression l1_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<L1Distance>({x.i, y.i})); }
Expression binary_log_loss(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<BinaryLogLoss>({x.i,y.i})); }
Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m) { return Expression(x.pg, x.pg->add_function<PairwiseRankLoss>({x.i, y.i}, m)); }
Expression poisson_loss(const Expression& x, unsigned y) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, y)); }
Expression poisson_loss(const Expression& x, const unsigned* py) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, py)); }
Expression conv1d_narrow(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DNarrow>({x.i, f.i})); }
Expression conv1d_wide(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DWide>({x.i, f.i})); }
Expression kmax_pooling(const Expression& x, unsigned k) { return Expression(x.pg, x.pg->add_function<KMaxPooling>({x.i}, k)); }
Expression fold_rows(const Expression& x, unsigned nrows) { return Expression(x.pg, x.pg->add_function<FoldRows>({x.i}, nrows)); }
Expression pick(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, v)); }
Expression pick(const Expression& x, unsigned* pv) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, pv)); }
Expression pickrange(const Expression& x, unsigned v, unsigned u) { return Expression(x.pg, x.pg->add_function<PickRange>({ x.i }, v, u)); }
Expression columnslices(const Expression& x, unsigned row, unsigned start_column, unsigned exclusive_end_column) { return Expression(x.pg, x.pg->add_function<ColumnSlices>({ x.i }, row, start_column, exclusive_end_column)); }
//Expression pickneglogsoftmax(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }
//Expression pickneglogsoftmax(const Expression& x, const std::vector<unsigned> & v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }
Expression sum_cols(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumColumns>({x.i})); }
Expression sum_batches(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumBatches>({x.i})); }
Expression kmh_ngram(const Expression& x, unsigned n) { return Expression(x.pg, x.pg->add_function<KMHNGram>({x.i}, n)); }
} }
<commit_msg>implemented exponential linear units<commit_after>#include "cnn/expr.h"
#include <initializer_list>
#include "cnn/nodes.h"
#include "cnn/conv.h"
namespace cnn { namespace expr {
Expression input(ComputationGraph& g, real s) { return Expression(&g, g.add_input(s)); }
Expression input(ComputationGraph& g, const real *ps) { return Expression(&g, g.add_input(ps)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>& pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>* pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression reference(ComputationGraph& g, const Dim& d, const cnn::real* pdata) { return Expression(&g, g.add_reference(d, pdata)); }
Expression const_parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_const_parameters(p)); }
Expression parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_parameters(p)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_lookup(p, index)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_lookup(p, pindex)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_lookup(p, indices)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_lookup(p, pindices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_const_lookup(p, index)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_const_lookup(p, pindex)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_const_lookup(p, indices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_const_lookup(p, pindices)); }
Expression zeroes(ComputationGraph& g, const Dim& d) { return Expression(&g, g.add_function<Zeroes>(d)); }
Expression operator-(const Expression& x) { return Expression(x.pg, x.pg->add_function<Negate>({x.i})); }
Expression operator+(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Sum>({x.i, y.i})); }
Expression operator+(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantPlusX>({y.i}, x)); }
Expression operator+(const Expression& x, real y) { return y+x; }
Expression operator-(const Expression& x, const Expression& y) { return x+(-y); }
Expression operator-(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantMinusX>({y.i}, x)); }
Expression operator-(const Expression& x, real y) { return -(y-x); }
Expression operator*(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<MatrixMultiply>({x.i, y.i})); }
Expression operator*(const Expression& x, cnn::real y) { return Expression(x.pg, x.pg->add_function<ConstScalarMultiply>({x.i}, y)); }
Expression cdiv(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<CwiseQuotient>({x.i, y.i})); }
Expression colwise_add(const Expression& x, const Expression& bias) { return Expression(x.pg, x.pg->add_function<AddVectorToAllColumns>({x.i, bias.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i, b.i})); }
Expression sqrt(const Expression& x) { return Expression(x.pg, x.pg->add_function<Sqrt>({x.i})); }
//Expression erf(const Expression& x) { return Expression(x.pg, x.pg->add_function<Erf>({x.i})); }
Expression tanh(const Expression& x) { return Expression(x.pg, x.pg->add_function<Tanh>({x.i})); }
//Expression lgamma(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogGamma>({x.i})); }
Expression log(const Expression& x) { return Expression(x.pg, x.pg->add_function<Log>({x.i})); }
Expression exp(const Expression& x) { return Expression(x.pg, x.pg->add_function<Exp>({x.i})); }
Expression square(const Expression& x) { return Expression(x.pg, x.pg->add_function<Square>({x.i})); }
Expression cube(const Expression& x) { return Expression(x.pg, x.pg->add_function<Cube>({x.i})); }
Expression logistic(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogisticSigmoid>({x.i})); }
Expression rectify(const Expression& x) { return Expression(x.pg, x.pg->add_function<Rectify>({ x.i })); }
Expression exponential_linear_units(const Expression& x, cnn::real scale) { return Expression(x.pg, x.pg->add_function<ExponentialLinearUnits>({ x.i }, scale)); }
Expression hinge(const Expression& x, unsigned index, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({ x.i }, index, m)); }
Expression hinge(const Expression& x, const unsigned* pindex, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({x.i}, pindex, m)); }
Expression log_softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogSoftmax>({x.i})); }
Expression log_softmax(const Expression& x, const std::vector<unsigned>& d) { return Expression(x.pg, x.pg->add_function<RestrictedLogSoftmax>({x.i}, d)); }
Expression softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<Softmax>({x.i})); }
Expression softsign(const Expression& x) { return Expression(x.pg, x.pg->add_function<SoftSign>({x.i})); }
Expression pow(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Pow>({x.i, y.i})); }
Expression min(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Min>({x.i, y.i})); }
Expression max(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Max>({x.i, y.i})); }
Expression noise(const Expression& x, real stddev) { return Expression(x.pg, x.pg->add_function<GaussianNoise>({x.i}, stddev)); }
Expression dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<Dropout>({x.i}, p)); }
Expression block_dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<BlockDropout>({x.i}, p)); }
Expression reshape(const Expression& x, const Dim& d) { return Expression(x.pg, x.pg->add_function<Reshape>({x.i}, d)); }
Expression transpose(const Expression& x) { return Expression(x.pg, x.pg->add_function<Transpose>({x.i})); }
Expression trace_of_product(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<TraceOfProduct>({x.i, y.i}));}
Expression cwise_multiply(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<CwiseMultiply>({x.i, y.i}));}
Expression dot_product(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<DotProduct>({x.i, y.i})); }
Expression squared_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<SquaredEuclideanDistance>({x.i, y.i})); }
Expression huber_distance(const Expression& x, const Expression& y, real c) { return Expression(x.pg, x.pg->add_function<HuberDistance>({x.i, y.i}, c)); }
Expression l1_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<L1Distance>({x.i, y.i})); }
Expression binary_log_loss(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<BinaryLogLoss>({x.i,y.i})); }
Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m) { return Expression(x.pg, x.pg->add_function<PairwiseRankLoss>({x.i, y.i}, m)); }
Expression poisson_loss(const Expression& x, unsigned y) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, y)); }
Expression poisson_loss(const Expression& x, const unsigned* py) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, py)); }
Expression conv1d_narrow(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DNarrow>({x.i, f.i})); }
Expression conv1d_wide(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DWide>({x.i, f.i})); }
Expression kmax_pooling(const Expression& x, unsigned k) { return Expression(x.pg, x.pg->add_function<KMaxPooling>({x.i}, k)); }
Expression fold_rows(const Expression& x, unsigned nrows) { return Expression(x.pg, x.pg->add_function<FoldRows>({x.i}, nrows)); }
Expression pick(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, v)); }
Expression pick(const Expression& x, unsigned* pv) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, pv)); }
Expression pickrange(const Expression& x, unsigned v, unsigned u) { return Expression(x.pg, x.pg->add_function<PickRange>({ x.i }, v, u)); }
Expression columnslices(const Expression& x, unsigned row, unsigned start_column, unsigned exclusive_end_column) { return Expression(x.pg, x.pg->add_function<ColumnSlices>({ x.i }, row, start_column, exclusive_end_column)); }
//Expression pickneglogsoftmax(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }
//Expression pickneglogsoftmax(const Expression& x, const std::vector<unsigned> & v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }
Expression sum_cols(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumColumns>({x.i})); }
Expression sum_batches(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumBatches>({x.i})); }
Expression kmh_ngram(const Expression& x, unsigned n) { return Expression(x.pg, x.pg->add_function<KMHNGram>({x.i}, n)); }
} }
<|endoftext|> |
<commit_before>/*
* Copyright © 2017 Mozilla Foundation
*
* This program is made available under an ISC-style license. See the
* accompanying file LICENSE for details.
*/
#include "gtest/gtest.h"
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <atomic>
#include "cubeb/cubeb.h"
#include "common.h"
#define SAMPLE_FREQUENCY 48000
#if (defined(_WIN32) || defined(__WIN32__))
#define STREAM_FORMAT CUBEB_SAMPLE_FLOAT32LE
#else
#define STREAM_FORMAT CUBEB_SAMPLE_S16LE
#endif
std::atomic<bool> load_callback{ false };
long data_cb(cubeb_stream * stream, void * user, const void * inputbuffer, void * outputbuffer, long nframes)
{
if (load_callback) {
printf("Sleeping...\n");
delay(100000);
printf("Sleeping done\n");
}
return nframes;
}
void state_cb(cubeb_stream * stream, void * /*user*/, cubeb_state state)
{
ASSERT_TRUE(!!stream);
switch (state) {
case CUBEB_STATE_STARTED:
printf("stream started\n"); break;
case CUBEB_STATE_STOPPED:
printf("stream stopped\n"); break;
case CUBEB_STATE_DRAINED:
FAIL() << "this test is not supposed to drain"; break;
case CUBEB_STATE_ERROR:
printf("stream error\n"); break;
default:
FAIL() << "this test is not supposed to have a weird state"; break;
}
}
TEST(cubeb, overload_callback)
{
cubeb * ctx;
cubeb_stream * stream;
cubeb_stream_params output_params;
int r;
uint32_t latency_frames = 0;
r = cubeb_init(&ctx, "Cubeb callback overload", NULL);
ASSERT_EQ(r, CUBEB_OK);
output_params.format = STREAM_FORMAT;
output_params.rate = 48000;
output_params.channels = 2;
output_params.layout = CUBEB_LAYOUT_STEREO;
r = cubeb_get_min_latency(ctx, output_params, &latency_frames);
ASSERT_EQ(r, CUBEB_OK);
r = cubeb_stream_init(ctx, &stream, "Cubeb",
NULL, NULL, NULL, &output_params,
latency_frames, data_cb, state_cb, NULL);
ASSERT_EQ(r, CUBEB_OK);
cubeb_stream_start(stream);
delay(500);
// This causes the callback to sleep for a large number of seconds.
load_callback = true;
delay(500);
cubeb_stream_stop(stream);
cubeb_stream_destroy(stream);
cubeb_destroy(ctx);
}
<commit_msg>Replace printf by fprintf with stderr<commit_after>/*
* Copyright © 2017 Mozilla Foundation
*
* This program is made available under an ISC-style license. See the
* accompanying file LICENSE for details.
*/
#include "gtest/gtest.h"
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <atomic>
#include "cubeb/cubeb.h"
#include "common.h"
#define SAMPLE_FREQUENCY 48000
#if (defined(_WIN32) || defined(__WIN32__))
#define STREAM_FORMAT CUBEB_SAMPLE_FLOAT32LE
#else
#define STREAM_FORMAT CUBEB_SAMPLE_S16LE
#endif
std::atomic<bool> load_callback{ false };
long data_cb(cubeb_stream * stream, void * user, const void * inputbuffer, void * outputbuffer, long nframes)
{
if (load_callback) {
fprintf(stderr, "Sleeping...\n");
delay(100000);
fprintf(stderr, "Sleeping done\n");
}
return nframes;
}
void state_cb(cubeb_stream * stream, void * /*user*/, cubeb_state state)
{
ASSERT_TRUE(!!stream);
switch (state) {
case CUBEB_STATE_STARTED:
fprintf(stderr, "stream started\n"); break;
case CUBEB_STATE_STOPPED:
fprintf(stderr, "stream stopped\n"); break;
case CUBEB_STATE_DRAINED:
FAIL() << "this test is not supposed to drain"; break;
case CUBEB_STATE_ERROR:
fprintf(stderr, "stream error\n"); break;
default:
FAIL() << "this test is not supposed to have a weird state"; break;
}
}
TEST(cubeb, overload_callback)
{
cubeb * ctx;
cubeb_stream * stream;
cubeb_stream_params output_params;
int r;
uint32_t latency_frames = 0;
r = cubeb_init(&ctx, "Cubeb callback overload", NULL);
ASSERT_EQ(r, CUBEB_OK);
output_params.format = STREAM_FORMAT;
output_params.rate = 48000;
output_params.channels = 2;
output_params.layout = CUBEB_LAYOUT_STEREO;
r = cubeb_get_min_latency(ctx, output_params, &latency_frames);
ASSERT_EQ(r, CUBEB_OK);
r = cubeb_stream_init(ctx, &stream, "Cubeb",
NULL, NULL, NULL, &output_params,
latency_frames, data_cb, state_cb, NULL);
ASSERT_EQ(r, CUBEB_OK);
cubeb_stream_start(stream);
delay(500);
// This causes the callback to sleep for a large number of seconds.
load_callback = true;
delay(500);
cubeb_stream_stop(stream);
cubeb_stream_destroy(stream);
cubeb_destroy(ctx);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used 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. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecategory_p.h"
#include "qdeclarativeplaceicon_p.h"
#include "qdeclarativegeoserviceprovider_p.h"
#include <QtDeclarative/QDeclarativeInfo>
#include <QtLocation/QGeoServiceProvider>
#include <QtLocation/QPlaceManager>
QT_USE_NAMESPACE
/*!
\qmlclass Category QDeclarativeCategory
\inqmlmodule QtLocation 5
\ingroup qml-QtLocation5-places
\since QtLocation 5.0
\brief The Category element represents a category that a \l Place can be associated with.
Categories are used to search for places based on the categories they are associated with. The
list of available categories can be obtained from the \l CategoryModel. The
\l PlaceSearchModel has a \l {PlaceSearchModel::categories}{categories} property that is used
to limit the search results to places with the specified categories.
If the \l Plugin supports it, categories can be created or removed. To create a new category
construct a new Category object and set its properties, then invoke the \l save() method.
\snippet snippets/declarative/places.qml QtLocation import
\codeline
\snippet snippets/declarative/places.qml Category
\dots 0
\snippet snippets/declarative/places.qml Category save
To remove a category ensure that the \l plugin and categoryId properties are set and call the
\l remove() method.
\sa CategoryModel
*/
QDeclarativeCategory::QDeclarativeCategory(QObject* parent)
: QObject(parent), m_icon(0), m_reply(0)
{
}
QDeclarativeCategory::QDeclarativeCategory(const QPlaceCategory &category,
QDeclarativeGeoServiceProvider *plugin,
QObject *parent)
: QObject(parent),
m_category(category),
m_icon(0), m_plugin(plugin), m_reply(0)
{
Q_ASSERT(plugin);
setCategory(category);
}
QDeclarativeCategory::~QDeclarativeCategory() {}
// From QDeclarativeParserStatus
void QDeclarativeCategory::componentComplete()
{
m_complete = true;
}
/*!
\qmlproperty Plugin Category::plugin
This property holds the plugin to which the category belongs.
*/
void QDeclarativeCategory::setPlugin(QDeclarativeGeoServiceProvider *plugin)
{
if (m_plugin == plugin)
return;
m_plugin = plugin;
if (m_complete)
emit pluginChanged();
QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
QPlaceManager *placeManager = serviceProvider->placeManager();
if (!placeManager || serviceProvider->error() != QGeoServiceProvider::NoError) {
qmlInfo(this) << tr("Warning: Plugin does not support places.");
return;
}
}
QDeclarativeGeoServiceProvider* QDeclarativeCategory::plugin() const
{
return m_plugin;
}
/*!
\qmlproperty QPlaceCategory Category::category
This property is used to provide an interface between C++ and QML code. First a pointer to a
Category object must be obtained from C++, then use the \l {QObject::property()}{property()} and
\l {QObject::setProperty()}{setProperty()} functions to get and set the \c category property.
The following gets the QPlaceCategory representing this object from C++:
\snippet snippets/cpp/cppqml.cpp Category get
The following sets the properties of this object based on a QPlaceCategory object from C++:
\snippet snippets/cpp/cppqml.cpp Category set
*/
void QDeclarativeCategory::setCategory(const QPlaceCategory &category)
{
QPlaceCategory previous = m_category;
m_category = category;
if (category.name() != previous.name())
emit nameChanged();
if (category.categoryId() != previous.categoryId())
emit categoryIdChanged();
if (m_icon && m_icon->parent() == this) {
m_icon->setPlugin(m_plugin);
m_icon->setBaseUrl(m_category.icon().baseUrl());
m_icon->setFullUrl(m_category.icon().fullUrl());
} else if (!m_icon || m_icon->parent() != this){
m_icon = new QDeclarativePlaceIcon(m_category.icon(), m_plugin, this);
emit iconChanged();
}
}
QPlaceCategory QDeclarativeCategory::category()
{
m_category.setIcon(m_icon ? m_icon->icon() : QPlaceIcon());
return m_category;
}
/*!
\qmlproperty string Category::categoryId
This property holds the id of the category. The categoryId is a string which uniquely
identifies this category within the categories \l plugin.
*/
void QDeclarativeCategory::setCategoryId(const QString &id)
{
if (m_category.categoryId() != id) {
m_category.setCategoryId(id);
emit categoryIdChanged();
}
}
QString QDeclarativeCategory::categoryId() const
{
return m_category.categoryId();
}
/*!
\qmlproperty string Category::name
This property holds name of the category.
*/
void QDeclarativeCategory::setName(const QString &name)
{
if (m_category.name() != name) {
m_category.setName(name);
emit nameChanged();
}
}
QString QDeclarativeCategory::name() const
{
return m_category.name();
}
/*!
\qmlproperty enumeration Category::visibility
This property holds the visibility of the category. It can be one of:
\table
\row
\o Category.UnspecifiedVisibility
\o The visibility of the category is unspecified, the default visibility of the plugin
will be used.
\row
\o Category.DeviceVisibility
\o The category is limited to the current device. The category will not be transferred
off of the device.
\row
\o Category.PrivateVisibility
\o The category is private to the current user. The category may be transferred to an
online service but is only ever visible to the current user.
\row
\o Category.PublicVisibility
\o The category is public.
\endtable
*/
QDeclarativeCategory::Visibility QDeclarativeCategory::visibility() const
{
return static_cast<QDeclarativeCategory::Visibility>(m_category.visibility());
}
void QDeclarativeCategory::setVisibility(Visibility visibility)
{
if (static_cast<QDeclarativeCategory::Visibility>(m_category.visibility()) == visibility)
return;
m_category.setVisibility(static_cast<QtLocation::Visibility>(visibility));
emit visibilityChanged();
}
/*!
\qmlproperty PlaceIcon Category::icon
This property holds the icon associated with the category.
*/
QDeclarativePlaceIcon *QDeclarativeCategory::icon() const
{
return m_icon;
}
void QDeclarativeCategory::setIcon(QDeclarativePlaceIcon *icon)
{
if (m_icon == icon)
return;
if (m_icon && m_icon->parent() == this)
delete m_icon;
m_icon = icon;
emit iconChanged();
}
/*!
\qmlmethod string Category::errorString()
Returns a string description of the error of the last operation.
If the last operation completed successfully then the string is empty.
*/
QString QDeclarativeCategory::errorString() const
{
return m_errorString;
}
/*!
\qmlproperty enumeration Category::status
This property holds the status of the category. It can be one of:
\table
\row
\o Category.Ready
\o No Error occurred during the last operation, further operations may be performed on
the category.
\row
\o Category.Saving
\o The category is currently being saved, no other operations may be perfomed until the
current operation completes.
\row
\o Category.Removing
\o The category is currently being removed, no other operations can be performed until
the current operation completes.
\row
\o Category.Error
\o An error occurred during the last operation, further operations can still be
performed on the category.
\endtable
*/
void QDeclarativeCategory::setStatus(Status status)
{
if (m_status != status) {
m_status = status;
emit statusChanged();
}
}
QDeclarativeCategory::Status QDeclarativeCategory::status() const
{
return m_status;
}
/*!
\qmlmethod void Category::save()
This method saves the category to the backend service.
*/
void QDeclarativeCategory::save(const QString &parentId)
{
QPlaceManager *placeManager = manager();
if (!placeManager)
return;
m_reply = placeManager->saveCategory(category(), parentId);
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
setStatus(QDeclarativeCategory::Saving);
}
/*!
\qmlmethod void Category::remove()
This method permanently removes the category from the backend service.
*/
void QDeclarativeCategory::remove()
{
QPlaceManager *placeManager = manager();
if (!placeManager)
return;
m_reply = placeManager->removeCategory(m_category.categoryId());
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
setStatus(QDeclarativeCategory::Removing);
}
void QDeclarativeCategory::replyFinished()
{
if (!m_reply)
return;
if (m_reply->error() == QPlaceReply::NoError) {
switch (m_reply->type()) {
case (QPlaceReply::IdReply) : {
QPlaceIdReply *idReply = qobject_cast<QPlaceIdReply *>(m_reply);
switch (idReply->operationType()) {
case QPlaceIdReply::SaveCategory:
setCategoryId(idReply->id());
break;
case QPlaceIdReply::RemoveCategory:
setCategoryId(QString());
break;
default:
//Other operation types shouldn't ever be received.
break;
}
break;
}
default:
//other types of replies shouldn't ever be received.
break;
}
m_errorString.clear();
m_reply->deleteLater();
m_reply = 0;
setStatus(QDeclarativeCategory::Ready);
} else {
m_errorString = m_reply->errorString();
m_reply->deleteLater();
m_reply = 0;
setStatus(QDeclarativeCategory::Error);
}
}
/*
Helper function to return the manager, this manager is intended to be used
to perform the next operation.
*/
QPlaceManager *QDeclarativeCategory::manager()
{
if (m_status != QDeclarativeCategory::Ready && m_status != QDeclarativeCategory::Error)
return 0;
if (m_reply) {
m_reply->abort();
m_reply->deleteLater();
m_reply = 0;
}
if (!m_plugin) {
qmlInfo(this) << tr("Plugin not assigned to category");
return 0;
}
QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
if (!serviceProvider)
return 0;
QPlaceManager *placeManager = serviceProvider->placeManager();
if (!placeManager) {
qmlInfo(this) << tr("Places not supported by %1 Plugin.").arg(m_plugin->name());
return 0;
}
return placeManager;
}
<commit_msg>Fix uninitialized member variables in Category element.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used 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. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecategory_p.h"
#include "qdeclarativeplaceicon_p.h"
#include "qdeclarativegeoserviceprovider_p.h"
#include <QtDeclarative/QDeclarativeInfo>
#include <QtLocation/QGeoServiceProvider>
#include <QtLocation/QPlaceManager>
QT_USE_NAMESPACE
/*!
\qmlclass Category QDeclarativeCategory
\inqmlmodule QtLocation 5
\ingroup qml-QtLocation5-places
\since QtLocation 5.0
\brief The Category element represents a category that a \l Place can be associated with.
Categories are used to search for places based on the categories they are associated with. The
list of available categories can be obtained from the \l CategoryModel. The
\l PlaceSearchModel has a \l {PlaceSearchModel::categories}{categories} property that is used
to limit the search results to places with the specified categories.
If the \l Plugin supports it, categories can be created or removed. To create a new category
construct a new Category object and set its properties, then invoke the \l save() method.
\snippet snippets/declarative/places.qml QtLocation import
\codeline
\snippet snippets/declarative/places.qml Category
\dots 0
\snippet snippets/declarative/places.qml Category save
To remove a category ensure that the \l plugin and categoryId properties are set and call the
\l remove() method.
\sa CategoryModel
*/
QDeclarativeCategory::QDeclarativeCategory(QObject* parent)
: QObject(parent), m_icon(0), m_plugin(0), m_reply(0), m_complete(false), m_status(Ready)
{
}
QDeclarativeCategory::QDeclarativeCategory(const QPlaceCategory &category,
QDeclarativeGeoServiceProvider *plugin,
QObject *parent)
: QObject(parent), m_category(category), m_icon(0), m_plugin(plugin), m_reply(0),
m_complete(false), m_status(Ready)
{
Q_ASSERT(plugin);
setCategory(category);
}
QDeclarativeCategory::~QDeclarativeCategory() {}
// From QDeclarativeParserStatus
void QDeclarativeCategory::componentComplete()
{
m_complete = true;
}
/*!
\qmlproperty Plugin Category::plugin
This property holds the plugin to which the category belongs.
*/
void QDeclarativeCategory::setPlugin(QDeclarativeGeoServiceProvider *plugin)
{
if (m_plugin == plugin)
return;
m_plugin = plugin;
if (m_complete)
emit pluginChanged();
QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
QPlaceManager *placeManager = serviceProvider->placeManager();
if (!placeManager || serviceProvider->error() != QGeoServiceProvider::NoError) {
qmlInfo(this) << tr("Warning: Plugin does not support places.");
return;
}
}
QDeclarativeGeoServiceProvider* QDeclarativeCategory::plugin() const
{
return m_plugin;
}
/*!
\qmlproperty QPlaceCategory Category::category
This property is used to provide an interface between C++ and QML code. First a pointer to a
Category object must be obtained from C++, then use the \l {QObject::property()}{property()} and
\l {QObject::setProperty()}{setProperty()} functions to get and set the \c category property.
The following gets the QPlaceCategory representing this object from C++:
\snippet snippets/cpp/cppqml.cpp Category get
The following sets the properties of this object based on a QPlaceCategory object from C++:
\snippet snippets/cpp/cppqml.cpp Category set
*/
void QDeclarativeCategory::setCategory(const QPlaceCategory &category)
{
QPlaceCategory previous = m_category;
m_category = category;
if (category.name() != previous.name())
emit nameChanged();
if (category.categoryId() != previous.categoryId())
emit categoryIdChanged();
if (m_icon && m_icon->parent() == this) {
m_icon->setPlugin(m_plugin);
m_icon->setBaseUrl(m_category.icon().baseUrl());
m_icon->setFullUrl(m_category.icon().fullUrl());
} else if (!m_icon || m_icon->parent() != this){
m_icon = new QDeclarativePlaceIcon(m_category.icon(), m_plugin, this);
emit iconChanged();
}
}
QPlaceCategory QDeclarativeCategory::category()
{
m_category.setIcon(m_icon ? m_icon->icon() : QPlaceIcon());
return m_category;
}
/*!
\qmlproperty string Category::categoryId
This property holds the id of the category. The categoryId is a string which uniquely
identifies this category within the categories \l plugin.
*/
void QDeclarativeCategory::setCategoryId(const QString &id)
{
if (m_category.categoryId() != id) {
m_category.setCategoryId(id);
emit categoryIdChanged();
}
}
QString QDeclarativeCategory::categoryId() const
{
return m_category.categoryId();
}
/*!
\qmlproperty string Category::name
This property holds name of the category.
*/
void QDeclarativeCategory::setName(const QString &name)
{
if (m_category.name() != name) {
m_category.setName(name);
emit nameChanged();
}
}
QString QDeclarativeCategory::name() const
{
return m_category.name();
}
/*!
\qmlproperty enumeration Category::visibility
This property holds the visibility of the category. It can be one of:
\table
\row
\o Category.UnspecifiedVisibility
\o The visibility of the category is unspecified, the default visibility of the plugin
will be used.
\row
\o Category.DeviceVisibility
\o The category is limited to the current device. The category will not be transferred
off of the device.
\row
\o Category.PrivateVisibility
\o The category is private to the current user. The category may be transferred to an
online service but is only ever visible to the current user.
\row
\o Category.PublicVisibility
\o The category is public.
\endtable
*/
QDeclarativeCategory::Visibility QDeclarativeCategory::visibility() const
{
return static_cast<QDeclarativeCategory::Visibility>(m_category.visibility());
}
void QDeclarativeCategory::setVisibility(Visibility visibility)
{
if (static_cast<QDeclarativeCategory::Visibility>(m_category.visibility()) == visibility)
return;
m_category.setVisibility(static_cast<QtLocation::Visibility>(visibility));
emit visibilityChanged();
}
/*!
\qmlproperty PlaceIcon Category::icon
This property holds the icon associated with the category.
*/
QDeclarativePlaceIcon *QDeclarativeCategory::icon() const
{
return m_icon;
}
void QDeclarativeCategory::setIcon(QDeclarativePlaceIcon *icon)
{
if (m_icon == icon)
return;
if (m_icon && m_icon->parent() == this)
delete m_icon;
m_icon = icon;
emit iconChanged();
}
/*!
\qmlmethod string Category::errorString()
Returns a string description of the error of the last operation.
If the last operation completed successfully then the string is empty.
*/
QString QDeclarativeCategory::errorString() const
{
return m_errorString;
}
/*!
\qmlproperty enumeration Category::status
This property holds the status of the category. It can be one of:
\table
\row
\o Category.Ready
\o No Error occurred during the last operation, further operations may be performed on
the category.
\row
\o Category.Saving
\o The category is currently being saved, no other operations may be perfomed until the
current operation completes.
\row
\o Category.Removing
\o The category is currently being removed, no other operations can be performed until
the current operation completes.
\row
\o Category.Error
\o An error occurred during the last operation, further operations can still be
performed on the category.
\endtable
*/
void QDeclarativeCategory::setStatus(Status status)
{
if (m_status != status) {
m_status = status;
emit statusChanged();
}
}
QDeclarativeCategory::Status QDeclarativeCategory::status() const
{
return m_status;
}
/*!
\qmlmethod void Category::save()
This method saves the category to the backend service.
*/
void QDeclarativeCategory::save(const QString &parentId)
{
QPlaceManager *placeManager = manager();
if (!placeManager)
return;
m_reply = placeManager->saveCategory(category(), parentId);
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
setStatus(QDeclarativeCategory::Saving);
}
/*!
\qmlmethod void Category::remove()
This method permanently removes the category from the backend service.
*/
void QDeclarativeCategory::remove()
{
QPlaceManager *placeManager = manager();
if (!placeManager)
return;
m_reply = placeManager->removeCategory(m_category.categoryId());
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
setStatus(QDeclarativeCategory::Removing);
}
void QDeclarativeCategory::replyFinished()
{
if (!m_reply)
return;
if (m_reply->error() == QPlaceReply::NoError) {
switch (m_reply->type()) {
case (QPlaceReply::IdReply) : {
QPlaceIdReply *idReply = qobject_cast<QPlaceIdReply *>(m_reply);
switch (idReply->operationType()) {
case QPlaceIdReply::SaveCategory:
setCategoryId(idReply->id());
break;
case QPlaceIdReply::RemoveCategory:
setCategoryId(QString());
break;
default:
//Other operation types shouldn't ever be received.
break;
}
break;
}
default:
//other types of replies shouldn't ever be received.
break;
}
m_errorString.clear();
m_reply->deleteLater();
m_reply = 0;
setStatus(QDeclarativeCategory::Ready);
} else {
m_errorString = m_reply->errorString();
m_reply->deleteLater();
m_reply = 0;
setStatus(QDeclarativeCategory::Error);
}
}
/*
Helper function to return the manager, this manager is intended to be used
to perform the next operation.
*/
QPlaceManager *QDeclarativeCategory::manager()
{
if (m_status != QDeclarativeCategory::Ready && m_status != QDeclarativeCategory::Error)
return 0;
if (m_reply) {
m_reply->abort();
m_reply->deleteLater();
m_reply = 0;
}
if (!m_plugin) {
qmlInfo(this) << tr("Plugin not assigned to category");
return 0;
}
QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
if (!serviceProvider)
return 0;
QPlaceManager *placeManager = serviceProvider->placeManager();
if (!placeManager) {
qmlInfo(this) << tr("Places not supported by %1 Plugin.").arg(m_plugin->name());
return 0;
}
return placeManager;
}
<|endoftext|> |
<commit_before>#include "storehouse/s3/s3_storage.h"
#include <aws/s3/model/Bucket.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/core/Aws.h>
#include <fstream>
#include <sstream>
#include <fcntl.h>
namespace storehouse {
using Aws::S3::S3Client;
class S3RandomReadFile : public RandomReadFile {
public:
S3RandomReadFile(const std::string& name, const std::string& bucket,
S3Client* client)
: name_(name), bucket_(bucket), client_(client) {}
StoreResult read(uint64_t offset, size_t requested_size, uint8_t* data,
size_t& size_read) override {
uint64_t file_size;
auto result = get_size(file_size);
int64_t size_to_read = std::min((int64_t)(file_size - offset), (int64_t)requested_size);
size_to_read = std::max(size_to_read, (int64_t)0);
size_read = 0;
if (result != StoreResult::Success
|| (size_to_read == 0 && requested_size == 0)) {
return result;
}
if (size_to_read == 0 && requested_size > 0) {
return StoreResult::EndOfFile;
}
Aws::S3::Model::GetObjectRequest object_request;
std::stringstream range_request;
range_request << "bytes=" << offset << "-" << (offset + size_to_read - 1);
object_request.WithBucket(bucket_).WithKey(name_).WithRange(range_request.str());
auto get_object_outcome = client_->GetObject(object_request);
if (get_object_outcome.IsSuccess()) {
size_read = get_object_outcome.GetResult().GetContentLength();
get_object_outcome.GetResult().GetBody().
rdbuf()->sgetn((char*)data, size_read);
if (size_read != requested_size) {
return StoreResult::EndOfFile;
}
return StoreResult::Success;
} else {
auto error = get_object_outcome.GetError();
LOG(WARNING) << "Error opening file: " <<
get_full_path() << " - " <<
error.GetMessage();
return StoreResult::TransientFailure;
}
}
StoreResult get_size(uint64_t& size) override {
Aws::S3::Model::HeadObjectRequest object_request;
object_request.WithBucket(bucket_).WithKey(name_);
auto head_object_outcome = client_->HeadObject(object_request);
if (head_object_outcome.IsSuccess()) {
size = (uint64_t)head_object_outcome.GetResult().GetContentLength();
} else {
LOG(WARNING) << "Error getting size - HeadObject error: " <<
head_object_outcome.GetError().GetExceptionName() << " " <<
head_object_outcome.GetError().GetMessage() <<
" for object: " << get_full_path();
return StoreResult::TransientFailure;
}
return StoreResult::Success;
}
const std::string path() override { return name_; }
private:
std::string bucket_;
std::string name_;
S3Client* client_;
std::string get_full_path() {
return bucket_ + "/" + name_;
}
};
class S3WriteFile : public WriteFile {
public:
S3WriteFile(const std::string& name, const std::string& bucket,
S3Client* client)
: name_(name), bucket_(bucket), client_(client), tfd_(-1) {
tmpfilename_ = strdup("/tmp/scannerXXXXXX");
tfd_ = mkstemp(tmpfilename_);
LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
<< "Failed to create temp file for writing";
tfp_ = fdopen(tfd_, "wb+");
LOG_IF(FATAL, tfp_ == NULL) << "Failed to open temp file for writing";
has_changed_ = true;
}
~S3WriteFile() {
save();
int err;
err = std::fclose(tfp_);
LOG_IF(FATAL, err < 0)
<< "fclose temp file " << tmpfilename_ << " "
<< "failed with error: " << strerror(errno);
err = unlink(tmpfilename_);
LOG_IF(FATAL, err < 0)
<< "unlink temp file " << tmpfilename_ << " "
<< "failed with error: " << strerror(errno);
free(tmpfilename_);
}
StoreResult append(size_t size, const uint8_t* data) override {
LOG_IF(FATAL, tfp_ == NULL) << "assertion failure: null file pointer";
LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
<< "S3WriteFile: closed file descriptor for " << get_full_path();
size_t size_written = fwrite(data, sizeof(uint8_t), size, tfp_);
LOG_IF(FATAL, size_written != size)
<< "S3WriteFile: did not write all " << size << " "
<< "bytes to tmp file for file " << get_full_path() << " "
<< "with error: " << strerror(errno);
has_changed_ = true;
return StoreResult::Success;
}
StoreResult save() override {
if (!has_changed_) { return StoreResult::Success; }
std::fflush(tfp_);
auto input_data = Aws::MakeShared<Aws::FStream>("PutObjectInputStream",
tmpfilename_, std::ios_base::in | std::ios_base::binary);
Aws::S3::Model::PutObjectRequest put_object_request;
put_object_request.WithKey(name_).WithBucket(bucket_);
put_object_request.SetBody(input_data);
auto put_object_outcome = client_->PutObject(put_object_request);
if(!put_object_outcome.IsSuccess()) {
auto error = put_object_outcome.GetError();
LOG(WARNING) << "Save Error: error while putting object: " <<
get_full_path() << " - " <<
error.GetExceptionName() << " " <<
error.GetMessage();
return StoreResult::TransientFailure;
}
has_changed_ = false;
return StoreResult::Success;
}
const std::string path() override { return name_; }
private:
std::string bucket_;
std::string name_;
S3Client* client_;
int tfd_;
FILE* tfp_;
char* tmpfilename_;
bool has_changed_;
std::string get_full_path() {
return bucket_ + "/" + name_;
}
};
uint64_t S3Storage::num_clients = 0;
std::mutex S3Storage::num_clients_mutex;
S3Storage::S3Storage(S3Config config) : bucket_(config.bucket) {
std::lock_guard<std::mutex> guard(num_clients_mutex);
if (num_clients == 0) {
Aws::InitAPI(sdk_options_);
}
num_clients++;
Aws::Client::ClientConfiguration cc;
cc.scheme = Aws::Http::Scheme::HTTPS;
cc.region = config.endpointRegion;
cc.endpointOverride = config.endpointOverride;
cc.connectTimeoutMs = 1000 * 60 * 10;
cc.requestTimeoutMs = 1000 * 60 * 10;
client_ = new S3Client(cc);
}
S3Storage::~S3Storage() {
std::lock_guard<std::mutex> guard(num_clients_mutex);
delete client_;
num_clients--;
if (num_clients == 0) {
Aws::ShutdownAPI(sdk_options_);
}
}
StoreResult S3Storage::get_file_info(const std::string& name,
FileInfo& file_info) {
S3RandomReadFile s3read_file(name, bucket_, client_);
file_info.file_exists = false;
file_info.file_is_folder = (name[name.length()-1] == '/');
auto result = s3read_file.get_size(file_info.size);
if (result == StoreResult::Success) {
file_info.file_exists = true;
}
return result;
}
StoreResult S3Storage::make_random_read_file(const std::string& name,
RandomReadFile*& file) {
file = new S3RandomReadFile(name, bucket_, client_);
return StoreResult::Success;
}
StoreResult S3Storage::make_write_file(const std::string& name,
WriteFile*& file) {
file = new S3WriteFile(name, bucket_, client_);
return StoreResult::Success;
}
StoreResult S3Storage::make_dir(const std::string& name) {
Aws::S3::Model::PutObjectRequest put_object_request;
put_object_request.WithKey(name + "/").WithBucket(bucket_);
auto put_object_outcome = client_->PutObject(put_object_request);
if(!put_object_outcome.IsSuccess()) {
LOG(WARNING) << "Save Error: error while making dir: " <<
bucket_ << "/" << name << " - " <<
put_object_outcome.GetError().GetExceptionName() << " " <<
put_object_outcome.GetError().GetMessage();
return StoreResult::TransientFailure;
}
return StoreResult::Success;
}
StoreResult S3Storage::delete_file(const std::string& name) {
return StoreResult::Success;
}
StoreResult S3Storage::delete_dir(const std::string& name, bool recursive) {
return StoreResult::Success;
}
}
<commit_msg>Fix handling of transient failures in s3 backend<commit_after>#include "storehouse/s3/s3_storage.h"
#include <aws/s3/model/Bucket.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/core/Aws.h>
#include <fstream>
#include <sstream>
#include <fcntl.h>
namespace storehouse {
using Aws::S3::S3Client;
class S3RandomReadFile : public RandomReadFile {
public:
S3RandomReadFile(const std::string& name, const std::string& bucket,
S3Client* client)
: name_(name), bucket_(bucket), client_(client) {}
StoreResult read(uint64_t offset, size_t requested_size, uint8_t* data,
size_t& size_read) override {
uint64_t file_size;
auto result = get_size(file_size);
int64_t size_to_read = std::min((int64_t)(file_size - offset), (int64_t)requested_size);
size_to_read = std::max(size_to_read, (int64_t)0);
size_read = 0;
if (result != StoreResult::Success
|| (size_to_read == 0 && requested_size == 0)) {
return result;
}
if (size_to_read == 0 && requested_size > 0) {
return StoreResult::EndOfFile;
}
Aws::S3::Model::GetObjectRequest object_request;
std::stringstream range_request;
range_request << "bytes=" << offset << "-" << (offset + size_to_read - 1);
object_request.WithBucket(bucket_).WithKey(name_).WithRange(range_request.str());
auto get_object_outcome = client_->GetObject(object_request);
if (get_object_outcome.IsSuccess()) {
size_read = get_object_outcome.GetResult().GetContentLength();
get_object_outcome.GetResult().GetBody().
rdbuf()->sgetn((char*)data, size_read);
if (size_read != requested_size) {
return StoreResult::EndOfFile;
}
return StoreResult::Success;
} else {
auto error = get_object_outcome.GetError();
LOG(WARNING) << "Error opening file: " <<
get_full_path() << " - " <<
error.GetMessage();
if (error.ShouldRetry()) {
return StoreResult::TransientFailure;
} else {
return StoreResult::ReadFailure;
}
}
}
StoreResult get_size(uint64_t& size) override {
Aws::S3::Model::HeadObjectRequest object_request;
object_request.WithBucket(bucket_).WithKey(name_);
auto head_object_outcome = client_->HeadObject(object_request);
if (head_object_outcome.IsSuccess()) {
size = (uint64_t)head_object_outcome.GetResult().GetContentLength();
} else {
LOG(WARNING) << "Error getting size - HeadObject error: " <<
head_object_outcome.GetError().GetExceptionName() << " " <<
head_object_outcome.GetError().GetMessage() <<
" for object: " << get_full_path();
if (head_object_outcome.GetError().ShouldRetry()) {
return StoreResult::TransientFailure;
} else {
return StoreResult::ReadFailure;
}
}
return StoreResult::Success;
}
const std::string path() override { return name_; }
private:
std::string bucket_;
std::string name_;
S3Client* client_;
std::string get_full_path() {
return bucket_ + "/" + name_;
}
};
class S3WriteFile : public WriteFile {
public:
S3WriteFile(const std::string& name, const std::string& bucket,
S3Client* client)
: name_(name), bucket_(bucket), client_(client), tfd_(-1) {
tmpfilename_ = strdup("/tmp/scannerXXXXXX");
tfd_ = mkstemp(tmpfilename_);
LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
<< "Failed to create temp file for writing";
tfp_ = fdopen(tfd_, "wb+");
LOG_IF(FATAL, tfp_ == NULL) << "Failed to open temp file for writing";
has_changed_ = true;
}
~S3WriteFile() {
save();
int err;
err = std::fclose(tfp_);
LOG_IF(FATAL, err < 0)
<< "fclose temp file " << tmpfilename_ << " "
<< "failed with error: " << strerror(errno);
err = unlink(tmpfilename_);
LOG_IF(FATAL, err < 0)
<< "unlink temp file " << tmpfilename_ << " "
<< "failed with error: " << strerror(errno);
free(tmpfilename_);
}
StoreResult append(size_t size, const uint8_t* data) override {
LOG_IF(FATAL, tfp_ == NULL) << "assertion failure: null file pointer";
LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
<< "S3WriteFile: closed file descriptor for " << get_full_path();
size_t size_written = fwrite(data, sizeof(uint8_t), size, tfp_);
LOG_IF(FATAL, size_written != size)
<< "S3WriteFile: did not write all " << size << " "
<< "bytes to tmp file for file " << get_full_path() << " "
<< "with error: " << strerror(errno);
has_changed_ = true;
return StoreResult::Success;
}
StoreResult save() override {
if (!has_changed_) { return StoreResult::Success; }
std::fflush(tfp_);
auto input_data = Aws::MakeShared<Aws::FStream>("PutObjectInputStream",
tmpfilename_, std::ios_base::in | std::ios_base::binary);
Aws::S3::Model::PutObjectRequest put_object_request;
put_object_request.WithKey(name_).WithBucket(bucket_);
put_object_request.SetBody(input_data);
auto put_object_outcome = client_->PutObject(put_object_request);
if(!put_object_outcome.IsSuccess()) {
auto error = put_object_outcome.GetError();
LOG(WARNING) << "Save Error: error while putting object: " <<
get_full_path() << " - " <<
error.GetExceptionName() << " " <<
error.GetMessage();
if (error.ShouldRetry()) {
return StoreResult::TransientFailure;
} else {
return StoreResult::SaveFailure;
}
}
has_changed_ = false;
return StoreResult::Success;
}
const std::string path() override { return name_; }
private:
std::string bucket_;
std::string name_;
S3Client* client_;
int tfd_;
FILE* tfp_;
char* tmpfilename_;
bool has_changed_;
std::string get_full_path() {
return bucket_ + "/" + name_;
}
};
uint64_t S3Storage::num_clients = 0;
std::mutex S3Storage::num_clients_mutex;
S3Storage::S3Storage(S3Config config) : bucket_(config.bucket) {
std::lock_guard<std::mutex> guard(num_clients_mutex);
if (num_clients == 0) {
Aws::InitAPI(sdk_options_);
}
num_clients++;
Aws::Client::ClientConfiguration cc;
cc.scheme = Aws::Http::Scheme::HTTPS;
cc.region = config.endpointRegion;
cc.endpointOverride = config.endpointOverride;
cc.connectTimeoutMs = 1000 * 60 * 10;
cc.requestTimeoutMs = 1000 * 60 * 10;
client_ = new S3Client(cc);
}
S3Storage::~S3Storage() {
std::lock_guard<std::mutex> guard(num_clients_mutex);
delete client_;
num_clients--;
if (num_clients == 0) {
Aws::ShutdownAPI(sdk_options_);
}
}
StoreResult S3Storage::get_file_info(const std::string& name,
FileInfo& file_info) {
S3RandomReadFile s3read_file(name, bucket_, client_);
file_info.file_exists = false;
file_info.file_is_folder = (name[name.length()-1] == '/');
auto result = s3read_file.get_size(file_info.size);
if (result == StoreResult::Success) {
file_info.file_exists = true;
}
return result;
}
StoreResult S3Storage::make_random_read_file(const std::string& name,
RandomReadFile*& file) {
file = new S3RandomReadFile(name, bucket_, client_);
return StoreResult::Success;
}
StoreResult S3Storage::make_write_file(const std::string& name,
WriteFile*& file) {
file = new S3WriteFile(name, bucket_, client_);
return StoreResult::Success;
}
StoreResult S3Storage::make_dir(const std::string& name) {
Aws::S3::Model::PutObjectRequest put_object_request;
put_object_request.WithKey(name + "/").WithBucket(bucket_);
auto put_object_outcome = client_->PutObject(put_object_request);
if(!put_object_outcome.IsSuccess()) {
LOG(WARNING) << "Save Error: error while making dir: " <<
bucket_ << "/" << name << " - " <<
put_object_outcome.GetError().GetExceptionName() << " " <<
put_object_outcome.GetError().GetMessage();
if (put_object_outcome.GetError().ShouldRetry()) {
return StoreResult::TransientFailure;
} else {
return StoreResult::MkDirFailure;
}
}
return StoreResult::Success;
}
StoreResult S3Storage::delete_file(const std::string& name) {
return StoreResult::Success;
}
StoreResult S3Storage::delete_dir(const std::string& name, bool recursive) {
return StoreResult::Success;
}
}
<|endoftext|> |
<commit_before>
//
// ===============================================================================
// clReflect
// -------------------------------------------------------------------------------
// Copyright (c) 2011 Don Williamson
//
// 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 <clcpp\Database.h>
#include "DatabaseLoader.h"
namespace
{
int CompareNames(clcpp::Name name, unsigned int hash)
{
return hash - name.hash;
}
int ComparePrimitives(const clcpp::Primitive* primitive, unsigned int hash)
{
return hash - primitive->name.hash;
}
int ComparePrimitives(const clcpp::Primitive& primitive, unsigned int hash)
{
return hash - primitive.name.hash;
}
template <typename ARRAY_TYPE, typename COMPARE_L_TYPE, typename COMPARE_R_TYPE, int (COMPARE_FUNC)(COMPARE_L_TYPE, COMPARE_R_TYPE)>
int BinarySearch(const clcpp::CArray<ARRAY_TYPE>& entries, COMPARE_R_TYPE compare_value)
{
// TODO: Return multiple entries
int first = 0;
int last = entries.size() - 1;
// Binary search
while (first <= last)
{
// Identify the mid point
int mid = (first + last) / 2;
int cmp = COMPARE_FUNC(entries[mid], compare_value);
if (cmp > 0)
{
// Shift search to local upper half
first = mid + 1;
}
else if (cmp < 0)
{
// Shift search to local lower half
last = mid - 1;
}
else
{
// Exact match found
return mid;
}
}
return -1;
}
}
const clcpp::Primitive* clcpp::internal::FindPrimitive(const CArray<const Primitive*>& primitives, unsigned int hash)
{
int index = BinarySearch<const Primitive*, const Primitive*, unsigned int, ComparePrimitives>(primitives, hash);
if (index == -1)
{
return 0;
}
return primitives[index];
}
clcpp::Database::Database()
: m_DatabaseMem(0)
, m_Allocator(0)
{
}
clcpp::Database::~Database()
{
if (m_DatabaseMem)
{
m_Allocator->Free(m_DatabaseMem);
}
}
clcpp::Name clcpp::Database::GetName(const char* text) const
{
// Null pointer
if (text == 0)
{
return clcpp::Name();
}
// Hash and exit on no value
unsigned int hash = internal::HashNameString(text);
if (hash == 0)
{
return clcpp::Name();
}
// Lookup the name by hash and see
int index = BinarySearch<Name, Name, unsigned int, CompareNames>(m_DatabaseMem->names, hash);
if (index == -1)
{
return clcpp::Name();
}
return m_DatabaseMem->names[index];
}
const clcpp::Type* clcpp::Database::GetType(unsigned int hash) const
{
return FindPrimitive(m_DatabaseMem->type_primitives, hash);
}
const clcpp::Namespace* clcpp::Database::GetNamespace(unsigned int hash) const
{
int index = BinarySearch<Namespace, const Primitive&, unsigned int, ComparePrimitives>(m_DatabaseMem->namespaces, hash);
if (index == -1)
{
return 0;
}
return &m_DatabaseMem->namespaces[index];
}
const clcpp::Function* clcpp::Database::GetFunction(unsigned int hash) const
{
int index = BinarySearch<Function, const Primitive&, unsigned int, ComparePrimitives>(m_DatabaseMem->functions, hash);
if (index == -1)
{
return 0;
}
return &m_DatabaseMem->functions[index];
}
bool clcpp::Database::Load(IFile* file, IAllocator* allocator)
{
internal::Assert(m_DatabaseMem == 0 && "Database already loaded");
m_Allocator = allocator;
m_DatabaseMem = internal::LoadMemoryMappedDatabase(file, m_Allocator);
return m_DatabaseMem != 0;
}
<commit_msg>Fixed subtract bug with the binary search and larger than int range hashes.<commit_after>
//
// ===============================================================================
// clReflect
// -------------------------------------------------------------------------------
// Copyright (c) 2011 Don Williamson
//
// 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 <clcpp\Database.h>
#include "DatabaseLoader.h"
namespace
{
unsigned int GetNameHash(clcpp::Name name)
{
return name.hash;
}
unsigned int GetPrimitiveHash(const clcpp::Primitive& primitive)
{
return primitive.name.hash;
}
unsigned int GetPrimitivePtrHash(const clcpp::Primitive* primitive)
{
return primitive->name.hash;
}
template <typename ARRAY_TYPE, typename COMPARE_L_TYPE, unsigned int (GET_HASH_FUNC)(COMPARE_L_TYPE)>
int BinarySearch(const clcpp::CArray<ARRAY_TYPE>& entries, unsigned int compare_hash)
{
// TODO: Return multiple entries
int first = 0;
int last = entries.size() - 1;
// Binary search
while (first <= last)
{
// Identify the mid point
int mid = (first + last) / 2;
unsigned entry_hash = GET_HASH_FUNC(entries[mid]);
if (compare_hash > entry_hash)
{
// Shift search to local upper half
first = mid + 1;
}
else if (compare_hash < entry_hash)
{
// Shift search to local lower half
last = mid - 1;
}
else
{
// Exact match found
return mid;
}
}
return -1;
}
}
const clcpp::Primitive* clcpp::internal::FindPrimitive(const CArray<const Primitive*>& primitives, unsigned int hash)
{
int index = BinarySearch<const Primitive*, const Primitive*, GetPrimitivePtrHash>(primitives, hash);
if (index == -1)
{
return 0;
}
return primitives[index];
}
clcpp::Database::Database()
: m_DatabaseMem(0)
, m_Allocator(0)
{
}
clcpp::Database::~Database()
{
if (m_DatabaseMem)
{
m_Allocator->Free(m_DatabaseMem);
}
}
clcpp::Name clcpp::Database::GetName(const char* text) const
{
// Null pointer
if (text == 0)
{
return clcpp::Name();
}
// Hash and exit on no value
unsigned int hash = internal::HashNameString(text);
if (hash == 0)
{
return clcpp::Name();
}
// Lookup the name by hash and see
int index = BinarySearch<Name, Name, GetNameHash>(m_DatabaseMem->names, hash);
if (index == -1)
{
return clcpp::Name();
}
return m_DatabaseMem->names[index];
}
const clcpp::Type* clcpp::Database::GetType(unsigned int hash) const
{
return FindPrimitive(m_DatabaseMem->type_primitives, hash);
}
const clcpp::Namespace* clcpp::Database::GetNamespace(unsigned int hash) const
{
int index = BinarySearch<Namespace, const Primitive&, GetPrimitiveHash>(m_DatabaseMem->namespaces, hash);
if (index == -1)
{
return 0;
}
return &m_DatabaseMem->namespaces[index];
}
const clcpp::Function* clcpp::Database::GetFunction(unsigned int hash) const
{
int index = BinarySearch<Function, const Primitive&, GetPrimitiveHash>(m_DatabaseMem->functions, hash);
if (index == -1)
{
return 0;
}
return &m_DatabaseMem->functions[index];
}
bool clcpp::Database::Load(IFile* file, IAllocator* allocator)
{
internal::Assert(m_DatabaseMem == 0 && "Database already loaded");
m_Allocator = allocator;
m_DatabaseMem = internal::LoadMemoryMappedDatabase(file, m_Allocator);
return m_DatabaseMem != 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/task.h"
#include "base/timer.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
namespace {
class OneShotTimerTester {
public:
OneShotTimerTester(bool* did_run, unsigned milliseconds = 10)
: did_run_(did_run),
delay_ms_(milliseconds) {
}
void Start() {
timer_.Start(TimeDelta::FromMilliseconds(delay_ms_), this,
&OneShotTimerTester::Run);
}
private:
void Run() {
*did_run_ = true;
MessageLoop::current()->Quit();
}
bool* did_run_;
base::OneShotTimer<OneShotTimerTester> timer_;
const unsigned delay_ms_;
};
class OneShotSelfDeletingTimerTester {
public:
OneShotSelfDeletingTimerTester(bool* did_run) :
did_run_(did_run),
timer_(new base::OneShotTimer<OneShotSelfDeletingTimerTester>()) {
}
void Start() {
timer_->Start(TimeDelta::FromMilliseconds(10), this,
&OneShotSelfDeletingTimerTester::Run);
}
private:
void Run() {
*did_run_ = true;
timer_.reset();
MessageLoop::current()->Quit();
}
bool* did_run_;
scoped_ptr<base::OneShotTimer<OneShotSelfDeletingTimerTester> > timer_;
};
class RepeatingTimerTester {
public:
RepeatingTimerTester(bool* did_run) : did_run_(did_run), counter_(10) {
}
void Start() {
timer_.Start(TimeDelta::FromMilliseconds(10), this,
&RepeatingTimerTester::Run);
}
private:
void Run() {
if (--counter_ == 0) {
*did_run_ = true;
MessageLoop::current()->Quit();
}
}
bool* did_run_;
int counter_;
base::RepeatingTimer<RepeatingTimerTester> timer_;
};
void RunTest_OneShotTimer(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run = false;
OneShotTimerTester f(&did_run);
f.Start();
MessageLoop::current()->Run();
EXPECT_TRUE(did_run);
}
void RunTest_OneShotTimer_Cancel(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run_a = false;
OneShotTimerTester* a = new OneShotTimerTester(&did_run_a);
// This should run before the timer expires.
MessageLoop::current()->DeleteSoon(FROM_HERE, a);
// Now start the timer.
a->Start();
bool did_run_b = false;
OneShotTimerTester b(&did_run_b);
b.Start();
MessageLoop::current()->Run();
EXPECT_FALSE(did_run_a);
EXPECT_TRUE(did_run_b);
}
void RunTest_OneShotSelfDeletingTimer(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run = false;
OneShotSelfDeletingTimerTester f(&did_run);
f.Start();
MessageLoop::current()->Run();
EXPECT_TRUE(did_run);
}
void RunTest_RepeatingTimer(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run = false;
RepeatingTimerTester f(&did_run);
f.Start();
MessageLoop::current()->Run();
EXPECT_TRUE(did_run);
}
void RunTest_RepeatingTimer_Cancel(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run_a = false;
RepeatingTimerTester* a = new RepeatingTimerTester(&did_run_a);
// This should run before the timer expires.
MessageLoop::current()->DeleteSoon(FROM_HERE, a);
// Now start the timer.
a->Start();
bool did_run_b = false;
RepeatingTimerTester b(&did_run_b);
b.Start();
MessageLoop::current()->Run();
EXPECT_FALSE(did_run_a);
EXPECT_TRUE(did_run_b);
}
class DelayTimerTarget {
public:
DelayTimerTarget()
: signaled_(false) {
}
bool signaled() const { return signaled_; }
void Signal() {
ASSERT_FALSE(signaled_);
signaled_ = true;
}
private:
bool signaled_;
};
void RunTest_DelayTimer_NoCall(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
// If Delay is never called, the timer shouldn't go off.
DelayTimerTarget target;
base::DelayTimer<DelayTimerTarget> timer(
TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
bool did_run = false;
OneShotTimerTester tester(&did_run);
tester.Start();
MessageLoop::current()->Run();
ASSERT_FALSE(target.signaled());
}
void RunTest_DelayTimer_OneCall(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
DelayTimerTarget target;
base::DelayTimer<DelayTimerTarget> timer(
TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
timer.Reset();
bool did_run = false;
OneShotTimerTester tester(&did_run, 100 /* milliseconds */);
tester.Start();
MessageLoop::current()->Run();
ASSERT_TRUE(target.signaled());
}
struct ResetHelper {
ResetHelper(base::DelayTimer<DelayTimerTarget>* timer,
DelayTimerTarget* target)
: timer_(timer),
target_(target) {
}
void Reset() {
ASSERT_FALSE(target_->signaled());
timer_->Reset();
}
private:
base::DelayTimer<DelayTimerTarget> *const timer_;
DelayTimerTarget *const target_;
};
void RunTest_DelayTimer_Reset(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
// If Delay is never called, the timer shouldn't go off.
DelayTimerTarget target;
base::DelayTimer<DelayTimerTarget> timer(
TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
timer.Reset();
ResetHelper reset_helper(&timer, &target);
base::OneShotTimer<ResetHelper> timers[20];
for (size_t i = 0; i < arraysize(timers); ++i) {
timers[i].Start(TimeDelta::FromMilliseconds(i * 10), &reset_helper,
&ResetHelper::Reset);
}
bool did_run = false;
OneShotTimerTester tester(&did_run, 300);
tester.Start();
MessageLoop::current()->Run();
ASSERT_TRUE(target.signaled());
}
} // namespace
//-----------------------------------------------------------------------------
// Each test is run against each type of MessageLoop. That way we are sure
// that timers work properly in all configurations.
TEST(TimerTest, OneShotTimer) {
RunTest_OneShotTimer(MessageLoop::TYPE_DEFAULT);
RunTest_OneShotTimer(MessageLoop::TYPE_UI);
RunTest_OneShotTimer(MessageLoop::TYPE_IO);
}
TEST(TimerTest, OneShotTimer_Cancel) {
RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_DEFAULT);
RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_UI);
RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_IO);
}
// If underline timer does not handle properly, we will crash or fail
// in full page heap or purify environment.
TEST(TimerTest, OneShotSelfDeletingTimer) {
RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_DEFAULT);
RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_UI);
RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_IO);
}
TEST(TimerTest, RepeatingTimer) {
RunTest_RepeatingTimer(MessageLoop::TYPE_DEFAULT);
RunTest_RepeatingTimer(MessageLoop::TYPE_UI);
RunTest_RepeatingTimer(MessageLoop::TYPE_IO);
}
TEST(TimerTest, RepeatingTimer_Cancel) {
RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_DEFAULT);
RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_UI);
RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_IO);
}
TEST(TimerTest, DelayTimer_NoCall) {
RunTest_DelayTimer_NoCall(MessageLoop::TYPE_DEFAULT);
RunTest_DelayTimer_NoCall(MessageLoop::TYPE_UI);
RunTest_DelayTimer_NoCall(MessageLoop::TYPE_IO);
}
TEST(TimerTest, DelayTimer_OneCall) {
RunTest_DelayTimer_OneCall(MessageLoop::TYPE_DEFAULT);
RunTest_DelayTimer_OneCall(MessageLoop::TYPE_UI);
RunTest_DelayTimer_OneCall(MessageLoop::TYPE_IO);
}
TEST(TimerTest, DelayTimer_Reset) {
RunTest_DelayTimer_Reset(MessageLoop::TYPE_DEFAULT);
RunTest_DelayTimer_Reset(MessageLoop::TYPE_UI);
RunTest_DelayTimer_Reset(MessageLoop::TYPE_IO);
}
TEST(TimerTest, MessageLoopShutdown) {
// This test is designed to verify that shutdown of the
// message loop does not cause crashes if there were pending
// timers not yet fired. It may only trigger exceptions
// if debug heap checking (or purify) is enabled.
bool did_run = false;
{
OneShotTimerTester a(&did_run);
OneShotTimerTester b(&did_run);
OneShotTimerTester c(&did_run);
OneShotTimerTester d(&did_run);
{
MessageLoop loop(MessageLoop::TYPE_DEFAULT);
a.Start();
b.Start();
} // MessageLoop destructs by falling out of scope.
} // OneShotTimers destruct. SHOULD NOT CRASH, of course.
EXPECT_EQ(false, did_run);
}
<commit_msg>Build fix<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/task.h"
#include "base/timer.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
namespace {
class OneShotTimerTester {
public:
OneShotTimerTester(bool* did_run, unsigned milliseconds = 10)
: did_run_(did_run),
delay_ms_(milliseconds) {
}
void Start() {
timer_.Start(TimeDelta::FromMilliseconds(delay_ms_), this,
&OneShotTimerTester::Run);
}
private:
void Run() {
*did_run_ = true;
MessageLoop::current()->Quit();
}
bool* did_run_;
base::OneShotTimer<OneShotTimerTester> timer_;
const unsigned delay_ms_;
};
class OneShotSelfDeletingTimerTester {
public:
OneShotSelfDeletingTimerTester(bool* did_run) :
did_run_(did_run),
timer_(new base::OneShotTimer<OneShotSelfDeletingTimerTester>()) {
}
void Start() {
timer_->Start(TimeDelta::FromMilliseconds(10), this,
&OneShotSelfDeletingTimerTester::Run);
}
private:
void Run() {
*did_run_ = true;
timer_.reset();
MessageLoop::current()->Quit();
}
bool* did_run_;
scoped_ptr<base::OneShotTimer<OneShotSelfDeletingTimerTester> > timer_;
};
class RepeatingTimerTester {
public:
RepeatingTimerTester(bool* did_run) : did_run_(did_run), counter_(10) {
}
void Start() {
timer_.Start(TimeDelta::FromMilliseconds(10), this,
&RepeatingTimerTester::Run);
}
private:
void Run() {
if (--counter_ == 0) {
*did_run_ = true;
MessageLoop::current()->Quit();
}
}
bool* did_run_;
int counter_;
base::RepeatingTimer<RepeatingTimerTester> timer_;
};
void RunTest_OneShotTimer(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run = false;
OneShotTimerTester f(&did_run);
f.Start();
MessageLoop::current()->Run();
EXPECT_TRUE(did_run);
}
void RunTest_OneShotTimer_Cancel(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run_a = false;
OneShotTimerTester* a = new OneShotTimerTester(&did_run_a);
// This should run before the timer expires.
MessageLoop::current()->DeleteSoon(FROM_HERE, a);
// Now start the timer.
a->Start();
bool did_run_b = false;
OneShotTimerTester b(&did_run_b);
b.Start();
MessageLoop::current()->Run();
EXPECT_FALSE(did_run_a);
EXPECT_TRUE(did_run_b);
}
void RunTest_OneShotSelfDeletingTimer(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run = false;
OneShotSelfDeletingTimerTester f(&did_run);
f.Start();
MessageLoop::current()->Run();
EXPECT_TRUE(did_run);
}
void RunTest_RepeatingTimer(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run = false;
RepeatingTimerTester f(&did_run);
f.Start();
MessageLoop::current()->Run();
EXPECT_TRUE(did_run);
}
void RunTest_RepeatingTimer_Cancel(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
bool did_run_a = false;
RepeatingTimerTester* a = new RepeatingTimerTester(&did_run_a);
// This should run before the timer expires.
MessageLoop::current()->DeleteSoon(FROM_HERE, a);
// Now start the timer.
a->Start();
bool did_run_b = false;
RepeatingTimerTester b(&did_run_b);
b.Start();
MessageLoop::current()->Run();
EXPECT_FALSE(did_run_a);
EXPECT_TRUE(did_run_b);
}
class DelayTimerTarget {
public:
DelayTimerTarget()
: signaled_(false) {
}
bool signaled() const { return signaled_; }
void Signal() {
ASSERT_FALSE(signaled_);
signaled_ = true;
}
private:
bool signaled_;
};
void RunTest_DelayTimer_NoCall(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
// If Delay is never called, the timer shouldn't go off.
DelayTimerTarget target;
base::DelayTimer<DelayTimerTarget> timer(
TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
bool did_run = false;
OneShotTimerTester tester(&did_run);
tester.Start();
MessageLoop::current()->Run();
ASSERT_FALSE(target.signaled());
}
void RunTest_DelayTimer_OneCall(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
DelayTimerTarget target;
base::DelayTimer<DelayTimerTarget> timer(
TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
timer.Reset();
bool did_run = false;
OneShotTimerTester tester(&did_run, 100 /* milliseconds */);
tester.Start();
MessageLoop::current()->Run();
ASSERT_TRUE(target.signaled());
}
struct ResetHelper {
ResetHelper(base::DelayTimer<DelayTimerTarget>* timer,
DelayTimerTarget* target)
: timer_(timer),
target_(target) {
}
void Reset() {
ASSERT_FALSE(target_->signaled());
timer_->Reset();
}
private:
base::DelayTimer<DelayTimerTarget> *const timer_;
DelayTimerTarget *const target_;
};
void RunTest_DelayTimer_Reset(MessageLoop::Type message_loop_type) {
MessageLoop loop(message_loop_type);
// If Delay is never called, the timer shouldn't go off.
DelayTimerTarget target;
base::DelayTimer<DelayTimerTarget> timer(
TimeDelta::FromMilliseconds(50), &target, &DelayTimerTarget::Signal);
timer.Reset();
ResetHelper reset_helper(&timer, &target);
base::OneShotTimer<ResetHelper> timers[20];
for (size_t i = 0; i < arraysize(timers); ++i) {
timers[i].Start(TimeDelta::FromMilliseconds(i * 10), &reset_helper,
&ResetHelper::Reset);
}
bool did_run = false;
OneShotTimerTester tester(&did_run, 300);
tester.Start();
MessageLoop::current()->Run();
ASSERT_TRUE(target.signaled());
}
} // namespace
//-----------------------------------------------------------------------------
// Each test is run against each type of MessageLoop. That way we are sure
// that timers work properly in all configurations.
TEST(TimerTest, OneShotTimer) {
RunTest_OneShotTimer(MessageLoop::TYPE_DEFAULT);
RunTest_OneShotTimer(MessageLoop::TYPE_UI);
RunTest_OneShotTimer(MessageLoop::TYPE_IO);
}
TEST(TimerTest, OneShotTimer_Cancel) {
RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_DEFAULT);
RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_UI);
RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_IO);
}
// If underline timer does not handle properly, we will crash or fail
// in full page heap or purify environment.
TEST(TimerTest, OneShotSelfDeletingTimer) {
RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_DEFAULT);
RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_UI);
RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_IO);
}
TEST(TimerTest, RepeatingTimer) {
RunTest_RepeatingTimer(MessageLoop::TYPE_DEFAULT);
RunTest_RepeatingTimer(MessageLoop::TYPE_UI);
RunTest_RepeatingTimer(MessageLoop::TYPE_IO);
}
TEST(TimerTest, RepeatingTimer_Cancel) {
RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_DEFAULT);
RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_UI);
RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_IO);
}
TEST(TimerTest, DelayTimer_NoCall) {
RunTest_DelayTimer_NoCall(MessageLoop::TYPE_DEFAULT);
RunTest_DelayTimer_NoCall(MessageLoop::TYPE_UI);
RunTest_DelayTimer_NoCall(MessageLoop::TYPE_IO);
}
TEST(TimerTest, DelayTimer_OneCall) {
RunTest_DelayTimer_OneCall(MessageLoop::TYPE_DEFAULT);
RunTest_DelayTimer_OneCall(MessageLoop::TYPE_UI);
RunTest_DelayTimer_OneCall(MessageLoop::TYPE_IO);
}
TEST(TimerTest, DelayTimer_Reset) {
RunTest_DelayTimer_Reset(MessageLoop::TYPE_DEFAULT);
RunTest_DelayTimer_Reset(MessageLoop::TYPE_UI);
RunTest_DelayTimer_Reset(MessageLoop::TYPE_IO);
}
TEST(TimerTest, MessageLoopShutdown) {
// This test is designed to verify that shutdown of the
// message loop does not cause crashes if there were pending
// timers not yet fired. It may only trigger exceptions
// if debug heap checking (or purify) is enabled.
bool did_run = false;
{
OneShotTimerTester a(&did_run);
OneShotTimerTester b(&did_run);
OneShotTimerTester c(&did_run);
OneShotTimerTester d(&did_run);
{
MessageLoop loop(MessageLoop::TYPE_DEFAULT);
a.Start();
b.Start();
} // MessageLoop destructs by falling out of scope.
} // OneShotTimers destruct. SHOULD NOT CRASH, of course.
EXPECT_EQ(false, did_run);
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QSettings>
#include <QLabel>
#include <QWSServer>
#include <QProgressBar>
#include "choiceview.h"
#include "spawner.h"
#include "footer.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QRect max(0, 0, 600, 800 - 26);
QWSServer::setMaxWindowRect(max);
// app.setStyleSheet("ChoiceView { background: white }");
QSettings settings("runcible", "lobby");
QString browsePath = settings.value("browse-path", "/home").toString();
QUrl browseUrl("file:" + browsePath);
Footer statusBar;
statusBar.setWindowFlags(Qt::FramelessWindowHint);
statusBar.move(0, 800-26);
statusBar.resize(600, 26);
statusBar.show();
ChoiceView view;
view.setWindowFlags(Qt::FramelessWindowHint);
view.setChoices(QList<Choice>()
<< Choice(QObject::tr("Browse"), browseUrl.toString())
);
Spawner spawner;
QObject::connect(&view, SIGNAL(back()), &app, SLOT(quit()));
QObject::connect(&view, SIGNAL(choiceMade(Choice)), &spawner, SLOT(openId(Choice)));
QObject::connect(QWSServer::instance(), SIGNAL(windowEvent(QWSWindow *, QWSServer::WindowEvent)),
&statusBar, SLOT(windowEvent(QWSWindow *, QWSServer::WindowEvent)));
view.setWindowTitle("Lobby");
view.setWindowFlags(Qt::FramelessWindowHint);
view.showMaximized();
return app.exec();
}
<commit_msg>Removed unnecessary includes<commit_after>#include <QApplication>
#include <QSettings>
#include <QWSServer>
#include "choiceview.h"
#include "spawner.h"
#include "footer.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QRect max(0, 0, 600, 800 - 26);
QWSServer::setMaxWindowRect(max);
// app.setStyleSheet("ChoiceView { background: white }");
QSettings settings("runcible", "lobby");
QString browsePath = settings.value("browse-path", "/home").toString();
QUrl browseUrl("file:" + browsePath);
Footer statusBar;
statusBar.setWindowFlags(Qt::FramelessWindowHint);
statusBar.move(0, 800-26);
statusBar.resize(600, 26);
statusBar.show();
ChoiceView view;
view.setWindowFlags(Qt::FramelessWindowHint);
view.setChoices(QList<Choice>()
<< Choice(QObject::tr("Browse"), browseUrl.toString())
);
Spawner spawner;
QObject::connect(&view, SIGNAL(back()), &app, SLOT(quit()));
QObject::connect(&view, SIGNAL(choiceMade(Choice)), &spawner, SLOT(openId(Choice)));
QObject::connect(QWSServer::instance(), SIGNAL(windowEvent(QWSWindow *, QWSServer::WindowEvent)),
&statusBar, SLOT(windowEvent(QWSWindow *, QWSServer::WindowEvent)));
view.setWindowTitle("Lobby");
view.setWindowFlags(Qt::FramelessWindowHint);
view.showMaximized();
return app.exec();
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;
fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));
l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
}
else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
{
l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
}
{
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
}
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
{
l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_def_mn_freq_ratio <= literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
}
else if ((l_def_mn_freq_ratio > literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
{
l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>HCODE: DD21 makefile changes for CME,PGPE and SGPE<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;
fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));
l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
}
else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
}
{
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
}
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
{
l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_def_mn_freq_ratio <= literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
}
else if ((l_def_mn_freq_ratio > literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/**********************************************************\
This file is distributed under the MIT License.
See accompanying file LICENSE for details.
tests/SimpleTreeTester.cpp
\**********************************************************/
#include "TestSettings.h"
#ifdef TEST_SIMPLE_TREE
#undef NDEBUG
#include "../../momo/TreeSet.h"
#include "../../momo/TreeMap.h"
#include <string>
#include <iostream>
class SimpleTreeTester
{
public:
static void TestAll()
{
std::cout << "TreeSet: " << std::flush;
TestStrTreeSet();
std::cout << "ok" << std::endl;
std::cout << "TreeMap: " << std::flush;
TestStrTreeMap();
std::cout << "ok" << std::endl;
}
static void TestStrTreeSet()
{
typedef momo::TreeSet<std::string> TreeSet;
std::string s1 = "s1";
TreeSet set = { s1, "s2" };
set.Insert("s3");
set = set;
set = std::move(set);
assert(set.GetCount() == 3);
assert(set.HasKey("s2"));
typename TreeSet::ConstIterator iter = set.Find("s1");
assert(*iter == "s1");
typename TreeSet::ExtractedItem rs;
set.Remove(iter, rs);
assert(rs.GetItem() == "s1");
iter = set.Find("s1");
assert(iter == set.GetEnd());
set.Insert(&s1, &s1 + 1);
set.ResetKey(set.LowerBound("s1"), s1);
set.ResetKey(set.UpperBound(s1), "s2");
set.Remove("s2");
for (const std::string& s : set)
assert(s == "s1" || s == "s3");
set.Clear();
assert(set.IsEmpty());
}
static void TestStrTreeMap()
{
typedef momo::TreeMap<std::string, std::string> TreeMap;
std::string s1 = "s1";
std::string s2 = "s2";
std::string s3 = "s3";
std::string s4 = "s4";
std::string s5 = "s5";
TreeMap map = { {"s1", "s1"}, {"s2", s2} };
map.Insert(s3, "s3");
map.Insert(s4, s4);
map[s5] = "s5";
assert((std::string)map["s5"] == s5);
map["s6"] = "s6";
map.ResetKey(map.LowerBound("s1"), s1);
map.ResetKey(map.UpperBound(s1), "s2");
map = map;
map = std::move(map);
assert(map.GetCount() == 6);
assert(map.HasKey(s2));
typename TreeMap::ConstIterator iter1 = map.Find(s1);
assert(iter1->key == s1 && iter1->value == s1);
map.Remove(s1);
typename TreeMap::Iterator iter2 = map.Find("s5");
assert(iter2->key == s5 && iter2->value == s5);
map.Remove(iter2);
map.Remove(s3);
map.Remove("s4");
std::pair<std::string, std::string> pair("s4", s4);
map.InsertFS(&pair, &pair + 1);
map.InsertKV(map.Find(s2), std::next(map.Find(s2))); //?
assert(map.GetCount() == 3);
map.Remove(s4);
for (auto ref : map)
assert(ref.value == "s2" || ref.value == "s6");
for (auto ref : (const TreeMap&)map)
assert(ref.value == "s2" || ref.value == "s6");
assert(map.GetCount() == 2);
map.Clear();
assert(map.IsEmpty());
}
};
static int testSimpleTree = (SimpleTreeTester::TestAll(), 0);
#endif // TEST_SIMPLE_TREE
<commit_msg>SimpleTreeTester<commit_after>/**********************************************************\
This file is distributed under the MIT License.
See accompanying file LICENSE for details.
tests/SimpleTreeTester.cpp
\**********************************************************/
#include "TestSettings.h"
#ifdef TEST_SIMPLE_TREE
#undef NDEBUG
#include "../../momo/TreeSet.h"
#include "../../momo/TreeMap.h"
#include <string>
#include <iostream>
class SimpleTreeTester
{
public:
static void TestAll()
{
std::cout << "momo::TreeSet: " << std::flush;
TestStrTreeSet();
std::cout << "ok" << std::endl;
std::cout << "momo::TreeMap: " << std::flush;
TestStrTreeMap();
std::cout << "ok" << std::endl;
}
static void TestStrTreeSet()
{
typedef momo::TreeSet<std::string> TreeSet;
std::string s1 = "s1";
TreeSet set = { s1, "s2" };
set.Insert("s3");
set = set;
set = std::move(set);
assert(set.GetCount() == 3);
assert(set.HasKey("s2"));
typename TreeSet::ConstIterator iter = set.Find("s1");
assert(*iter == "s1");
typename TreeSet::ExtractedItem rs;
set.Remove(iter, rs);
assert(rs.GetItem() == "s1");
iter = set.Find("s1");
assert(iter == set.GetEnd());
set.Insert(&s1, &s1 + 1);
set.ResetKey(set.LowerBound("s1"), s1);
set.ResetKey(set.UpperBound(s1), "s2");
set.Remove("s2");
for (const std::string& s : set)
assert(s == "s1" || s == "s3");
set.Clear();
assert(set.IsEmpty());
}
static void TestStrTreeMap()
{
typedef momo::TreeMap<std::string, std::string> TreeMap;
std::string s1 = "s1";
std::string s2 = "s2";
std::string s3 = "s3";
std::string s4 = "s4";
std::string s5 = "s5";
TreeMap map = { {"s1", "s1"}, {"s2", s2} };
map.Insert(s3, "s3");
map.Insert(s4, s4);
map[s5] = "s5";
assert((std::string)map["s5"] == s5);
map["s6"] = "s6";
map.ResetKey(map.LowerBound("s1"), s1);
map.ResetKey(map.UpperBound(s1), "s2");
map = map;
map = std::move(map);
assert(map.GetCount() == 6);
assert(map.HasKey(s2));
typename TreeMap::ConstIterator iter1 = map.Find(s1);
assert(iter1->key == s1 && iter1->value == s1);
map.Remove(s1);
typename TreeMap::Iterator iter2 = map.Find("s5");
assert(iter2->key == s5 && iter2->value == s5);
map.Remove(iter2);
map.Remove(s3);
map.Remove("s4");
std::pair<std::string, std::string> pair("s4", s4);
map.InsertFS(&pair, &pair + 1);
map.InsertKV(map.Find(s2), std::next(map.Find(s2))); //?
assert(map.GetCount() == 3);
map.Remove(s4);
for (auto ref : map)
assert(ref.value == "s2" || ref.value == "s6");
for (auto ref : (const TreeMap&)map)
assert(ref.value == "s2" || ref.value == "s6");
assert(map.GetCount() == 2);
map.Clear();
assert(map.IsEmpty());
}
};
static int testSimpleTree = (SimpleTreeTester::TestAll(), 0);
#endif // TEST_SIMPLE_TREE
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#include <info.hpp>
#include <cmdline.hpp>
#include <kdb.hpp>
#include <modules.hpp>
#include <plugin.hpp>
#include <iostream>
using namespace std;
using namespace kdb;
using namespace kdb::tools;
InfoCommand::InfoCommand ()
{
}
int InfoCommand::execute (Cmdline const & cl)
{
std::string subkey;
if (cl.arguments.size () == 1)
{
}
else if (cl.arguments.size () == 2)
{
subkey = cl.arguments[1];
}
else
{
throw invalid_argument ("Need at 1 or 2 argument(s)");
}
std::string name = cl.arguments[0];
KeySet conf;
Key parentKey (std::string ("system/elektra/modules/") + name, KEY_END);
if (!cl.load)
{
kdb.get (conf, parentKey);
}
if (!conf.lookup (parentKey))
{
if (!cl.load)
{
cerr << "Module does not seem to be loaded." << endl;
cerr << "Now in fallback code. Will directly load config from plugin." << endl;
}
Modules modules;
KeySet ks = cl.getPluginsConfig ();
PluginPtr plugin;
if (ks.size () == 0)
{
plugin = modules.load (name);
}
else
{
plugin = modules.load (name, ks);
}
conf.append (plugin->getInfo ());
}
Key root (std::string ("system/elektra/modules/") + name + "/exports", KEY_END);
if (!subkey.empty ())
{
root.setName (std::string ("system/elektra/modules/") + name + "/infos/" + subkey);
Key k = conf.lookup (root);
if (k)
{
cout << k.getString () << std::endl;
return 0;
}
else
{
cerr << "clause not found" << std::endl;
return 1;
}
}
root.setName (std::string ("system/elektra/modules/") + name + "/exports");
Key k = conf.lookup (root);
if (k)
{
cout << "Exported symbols: ";
while ((k = conf.next ()) && k.isBelow (root))
{
cout << k.getBaseName () << " ";
}
cout << endl;
}
else
cout << "no exported symbols found" << endl;
root.setName (std::string ("system/elektra/modules/") + name + "/infos");
k = conf.lookup (root);
if (k)
{
while ((k = conf.next ()) && k.isBelow (root))
{
cout << k.getBaseName () << ": " << k.getString () << endl;
}
}
else
cout << "no information found" << endl;
return 0;
}
InfoCommand::~InfoCommand ()
{
}
<commit_msg>fix name for virtual plugins<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#include <info.hpp>
#include <cmdline.hpp>
#include <kdb.hpp>
#include <modules.hpp>
#include <plugin.hpp>
#include <iostream>
using namespace std;
using namespace kdb;
using namespace kdb::tools;
InfoCommand::InfoCommand ()
{
}
int InfoCommand::execute (Cmdline const & cl)
{
std::string subkey;
if (cl.arguments.size () == 1)
{
}
else if (cl.arguments.size () == 2)
{
subkey = cl.arguments[1];
}
else
{
throw invalid_argument ("Need at 1 or 2 argument(s)");
}
std::string name = cl.arguments[0];
KeySet conf;
Key parentKey (std::string ("system/elektra/modules/") + name, KEY_END);
if (!cl.load)
{
kdb.get (conf, parentKey);
}
if (!conf.lookup (parentKey))
{
if (!cl.load)
{
cerr << "Module does not seem to be loaded." << endl;
cerr << "Now in fallback code. Will directly load config from plugin." << endl;
}
Modules modules;
KeySet ks = cl.getPluginsConfig ();
PluginPtr plugin;
if (ks.size () == 0)
{
plugin = modules.load (name);
}
else
{
plugin = modules.load (name, ks);
}
// fix name for virtual plugins
if (name != plugin->name ())
{
std::cerr << "Will use name " << plugin->name () << " for virtual plugin named " << name << std::endl;
name = plugin->name ();
}
conf.append (plugin->getInfo ());
}
Key root (std::string ("system/elektra/modules/") + name + "/exports", KEY_END);
if (!subkey.empty ())
{
root.setName (std::string ("system/elektra/modules/") + name + "/infos/" + subkey);
Key k = conf.lookup (root);
if (k)
{
cout << k.getString () << std::endl;
return 0;
}
else
{
cerr << "clause not found" << std::endl;
return 1;
}
}
root.setName (std::string ("system/elektra/modules/") + name + "/exports");
Key k = conf.lookup (root);
if (k)
{
cout << "Exported symbols: ";
while ((k = conf.next ()) && k.isBelow (root))
{
cout << k.getBaseName () << " ";
}
cout << endl;
}
else
cout << "no exported symbols found" << endl;
root.setName (std::string ("system/elektra/modules/") + name + "/infos");
k = conf.lookup (root);
if (k)
{
while ((k = conf.next ()) && k.isBelow (root))
{
cout << k.getBaseName () << ": " << k.getString () << endl;
}
}
else
cout << "no information found" << endl;
return 0;
}
InfoCommand::~InfoCommand ()
{
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fillpropertiesgroupcontext.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2008-01-17 08:05:45 $
*
* 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
*
************************************************************************/
#ifndef OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
#define OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
#ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_
#include <com/sun/star/drawing/FillStyle.hpp>
#endif
#ifndef OOX_CORE_CONTEXT_HXX
#include "oox/core/context.hxx"
#endif
#include "oox/drawingml/fillproperties.hxx"
#include <com/sun/star/drawing/BitmapMode.hpp>
namespace oox { namespace core {
class PropertyMap;
} }
namespace oox { namespace drawingml {
// ---------------------------------------------------------------------
class FillPropertiesGroupContext : public ::oox::core::Context
{
public:
FillPropertiesGroupContext( const oox::core::FragmentHandlerRef& xHandler, ::com::sun::star::drawing::FillStyle eFillStyle, ::oox::drawingml::FillProperties& rFillProperties ) throw();
static ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > StaticCreateContext( const oox::core::FragmentHandlerRef& xHandler,
::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs, ::oox::drawingml::FillProperties& rFillProperties )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
protected:
FillProperties& mrFillProperties;
};
// ---------------------------------------------------------------------
class BlipFillPropertiesContext : public FillPropertiesGroupContext
{
public:
BlipFillPropertiesContext( const oox::core::FragmentHandlerRef& xHandler,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes,
::oox::drawingml::FillProperties& rFillProperties ) throw();
virtual void SAL_CALL endFastElement( sal_Int32 aElementToken )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( sal_Int32 aElementToken,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttribs )
throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
private:
::com::sun::star::drawing::BitmapMode meBitmapMode;
sal_Int32 mnWidth, mnHeight;
rtl::OUString msEmbed;
rtl::OUString msLink;
};
} }
#endif // OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
<commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/02/14 18:47:59 sj 1.2.4.3: completet gradient/tile fill 2008/02/12 17:40:58 sj 1.2.4.2: added gradient fillstyle 2008/02/04 13:31:33 dr 1.2.4.1: rework of fragment handler/context handler base classes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fillpropertiesgroupcontext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:40:41 $
*
* 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
*
************************************************************************/
#ifndef OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
#define OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
#include "oox/core/contexthandler.hxx"
#include "oox/drawingml/fillproperties.hxx"
namespace oox { namespace core {
class PropertyMap;
} }
namespace oox { namespace drawingml {
// ---------------------------------------------------------------------
class FillPropertiesGroupContext : public ::oox::core::ContextHandler
{
public:
FillPropertiesGroupContext( oox::core::ContextHandler& rParent, ::com::sun::star::drawing::FillStyle eFillStyle, FillProperties& rFillProperties ) throw();
static ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > StaticCreateContext( oox::core::ContextHandler& rParent,
::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs, FillProperties& rFillProperties )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
protected:
FillProperties& mrFillProperties;
};
// ---------------------------------------------------------------------
class BlipFillPropertiesContext : public FillPropertiesGroupContext
{
public:
BlipFillPropertiesContext( oox::core::ContextHandler& rParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes,
FillProperties& rFillProperties ) throw();
virtual void SAL_CALL endFastElement( sal_Int32 aElementToken )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( sal_Int32 aElementToken,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttribs )
throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
private:
::com::sun::star::drawing::BitmapMode meBitmapMode;
rtl::OUString msEmbed;
rtl::OUString msLink;
};
} }
#endif // OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b111 = 0b111;
constexpr uint64_t literal_0x6 = 0x6;
constexpr uint64_t literal_0x7 = 0x7;
fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
fapi2::ATTR_LINK_TRAIN_Type l_TGT0_ATTR_LINK_TRAIN;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_TRAIN, TGT0, l_TGT0_ATTR_LINK_TRAIN));
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));
if ((l_TGT0_ATTR_LINK_TRAIN == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH))
{
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );
}
else if (literal_1)
{
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF = 0x0;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF );
}
constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
}
else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
|| ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6)
&& (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12))
|| ((l_chip_id == 0x6) && (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
}
l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0xF );
constexpr auto l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x6 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b111 );
}
else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
|| ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6)
&& (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12))
|| ((l_chip_id == 0x6) && (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
}
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x7 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>initCompiler updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b111 = 0b111;
constexpr uint64_t literal_0x6 = 0x6;
constexpr uint64_t literal_0x7 = 0x7;
fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
fapi2::ATTR_LINK_TRAIN_Type l_TGT0_ATTR_LINK_TRAIN;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_TRAIN, TGT0, l_TGT0_ATTR_LINK_TRAIN));
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));
if ((l_TGT0_ATTR_LINK_TRAIN == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH))
{
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );
}
else if (literal_1)
{
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF = 0x0;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF );
}
constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
&& (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10))
|| ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12)) || ((l_chip_id == 0x6)
&& (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
}
l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0xF );
constexpr auto l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x6 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
&& (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10))
|| ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12)) || ((l_chip_id == 0x6)
&& (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b111 );
}
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x7 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before><commit_msg>endo prezi 100%<commit_after><|endoftext|> |
<commit_before>// RUN: %clangxx_tsan -O1 %s -o %t && not %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
struct A {
A() {
sem_init(&sem_, 0, 0);
}
virtual void F() {
}
void Done() {
sem_post(&sem_);
}
virtual ~A() {
sem_wait(&sem_);
sem_destroy(&sem_);
}
sem_t sem_;
};
struct B : A {
virtual void F() {
}
virtual ~B() { }
};
static A *obj = new B;
static void (A::*fn)() = &A::F;
void *Thread1(void *x) {
sleep(1);
(obj->*fn)();
obj->Done();
return NULL;
}
void *Thread2(void *x) {
delete obj;
return NULL;
}
int main() {
pthread_t t[2];
pthread_create(&t[0], NULL, Thread1, NULL);
pthread_create(&t[1], NULL, Thread2, NULL);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
}
// CHECK: WARNING: ThreadSanitizer: data race
// but should be:
// WARNING: ThreadSanitizer: data race on vptr
// see http://llvm.org/bugs/show_bug.cgi?id=19113
<commit_msg>tsan: update the test since the bug is fixed http://llvm.org/bugs/show_bug.cgi?id=19113 is fixed, so enable the better CHECK<commit_after>// RUN: %clangxx_tsan -O1 %s -o %t && not %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
struct A {
A() {
sem_init(&sem_, 0, 0);
}
virtual void F() {
}
void Done() {
sem_post(&sem_);
}
virtual ~A() {
sem_wait(&sem_);
sem_destroy(&sem_);
}
sem_t sem_;
};
struct B : A {
virtual void F() {
}
virtual ~B() { }
};
static A *obj = new B;
static void (A::*fn)() = &A::F;
void *Thread1(void *x) {
sleep(1);
(obj->*fn)();
obj->Done();
return NULL;
}
void *Thread2(void *x) {
delete obj;
return NULL;
}
int main() {
pthread_t t[2];
pthread_create(&t[0], NULL, Thread1, NULL);
pthread_create(&t[1], NULL, Thread2, NULL);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
}
// CHECK: WARNING: ThreadSanitizer: data race on vptr
<|endoftext|> |
<commit_before>/** \brief Utility for updating SQL schemata etc.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 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 <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "DbConnection.h"
#include "StringUtil.h"
#include "util.h"
namespace {
void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table,
unsigned * const version)
{
std::vector<std::string> parts;
if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3))
LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!");
*database = parts[0];
*table = parts[1];
*version = StringUtil::ToUnsigned(parts[2]);
}
__attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) {
const auto first_plus_pos(compound_table_name.find('+'));
return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos);
}
// The filenames being compared are assumed to have the "structure database.table.version"
bool FileNameCompare(const std::string &filename1, const std::string &filename2) {
std::string database1, table1;
unsigned version1;
SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1);
std::string database2, table2;
unsigned version2;
SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2);
// Compare database names:
if (database1 < database2)
return true;
if (database1 > database2)
return false;
// Compare table names:
if (GetFirstTableName(table1) < GetFirstTableName(table2))
return true;
if (GetFirstTableName(table1) > GetFirstTableName(table2))
return false;
return version1 < version2;
}
void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) {
FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+");
for (const auto &entry : directory)
update_filenames->emplace_back(entry.getName());
std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare);
}
std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) {
std::vector<std::string> all_table_names;
StringUtil::Split(compound_table_name, '+', &all_table_names);
return all_table_names;
}
void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) {
std::string database, tables;
unsigned update_version;
SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version);
db_connection->queryOrDie("START TRANSACTION");
db_connection->queryFileOrDie(update_directory_path + "/" + update_filename);
bool can_update(true);
for (const auto &table : GetAllTableNames(tables)) {
unsigned current_version(0);
db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='"
+ db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'");
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty()) {
db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('"
+ db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)");
LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions.");
} else
current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]);
if (update_version <= current_version) {
if (unlikely(not can_update))
LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!");
can_update = false;
continue;
}
db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version)
+ " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='"
+ db_connection->escapeString(table) + "'");
if (unlikely(update_version != current_version + 1))
LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version)
+ " for table \"" + database + "." + table + "\"!");
LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\".");
}
db_connection->queryOrDie("COMMIT");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 2)
::Usage("[--verbose] update_directory_path");
std::vector<std::string> update_filenames;
const std::string update_directory_path(argv[1]);
LoadAndSortUpdateFilenames(update_directory_path, &update_filenames);
DbConnection db_connection;
if (not db_connection.tableExists("ub_tools", "table_versions")) {
db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, "
"table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_bin");
LOG_INFO("Created the ub_tools.table_versions table.");
}
for (const auto &update_filename : update_filenames)
ApplyUpdate(&db_connection, update_directory_path, update_filename);
return EXIT_SUCCESS;
}
<commit_msg>Fixed ordering problem.<commit_after>/** \brief Utility for updating SQL schemata etc.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 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 <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "DbConnection.h"
#include "StringUtil.h"
#include "util.h"
namespace {
void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table,
unsigned * const version)
{
std::vector<std::string> parts;
if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3))
LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!");
*database = parts[0];
*table = parts[1];
*version = StringUtil::ToUnsigned(parts[2]);
}
__attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) {
const auto first_plus_pos(compound_table_name.find('+'));
return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos);
}
// The filenames being compared are assumed to have the "structure database.table.version"
bool FileNameCompare(const std::string &filename1, const std::string &filename2) {
std::string database1, table1;
unsigned version1;
SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1);
std::string database2, table2;
unsigned version2;
SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2);
// Compare database names:
if (database1 < database2)
return true;
if (database1 > database2)
return false;
// Compare table names:
if (GetFirstTableName(table1) < GetFirstTableName(table2))
return true;
if (GetFirstTableName(table1) > GetFirstTableName(table2))
return false;
return version1 < version2;
}
void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) {
FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+");
for (const auto &entry : directory)
update_filenames->emplace_back(entry.getName());
std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare);
}
std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) {
std::vector<std::string> all_table_names;
StringUtil::Split(compound_table_name, '+', &all_table_names);
return all_table_names;
}
void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) {
std::string database, tables;
unsigned update_version;
SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version);
db_connection->queryOrDie("START TRANSACTION");
bool can_update(true);
for (const auto &table : GetAllTableNames(tables)) {
unsigned current_version(0);
db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='"
+ db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'");
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty()) {
db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('"
+ db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)");
LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions.");
} else
current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]);
if (update_version <= current_version) {
if (unlikely(not can_update))
LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!");
can_update = false;
continue;
}
db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version)
+ " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='"
+ db_connection->escapeString(table) + "'");
if (unlikely(update_version != current_version + 1))
LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version)
+ " for table \"" + database + "." + table + "\"!");
LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\".");
}
if (can_update) {
db_connection->queryFileOrDie(update_directory_path + "/" + update_filename);
db_connection->queryOrDie("COMMIT");
} else
db_connection->queryOrDie("ROLLBACK");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 2)
::Usage("[--verbose] update_directory_path");
std::vector<std::string> update_filenames;
const std::string update_directory_path(argv[1]);
LoadAndSortUpdateFilenames(update_directory_path, &update_filenames);
DbConnection db_connection;
if (not db_connection.tableExists("ub_tools", "table_versions")) {
db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, "
"table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_bin");
LOG_INFO("Created the ub_tools.table_versions table.");
}
for (const auto &update_filename : update_filenames)
ApplyUpdate(&db_connection, update_directory_path, update_filename);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* libjson-rpc-cpp
*************************************************************************
* @file test_client.cpp
* @date 28.09.2013
* @author Peter Spiess-Knafl <[email protected]>
* @license See attached LICENSE.txt
************************************************************************/
#define BOOST_TEST_MODULE
#include <boost/test/unit_test.hpp>
#include <jsonrpccpp/client.h>
#include "mockclientconnector.h"
using namespace jsonrpc;
using namespace std;
bool check_exception1(JsonRpcException const&ex)
{
return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR;
}
bool check_exception2(JsonRpcException const&ex)
{
return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE;
}
bool check_exception3(JsonRpcException const&ex)
{
return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST;
}
BOOST_AUTO_TEST_SUITE(client)
BOOST_AUTO_TEST_CASE(test_client_method_success)
{
MockClientConnector c;
Client client(c);
Json::Value params;
params.append(23);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23}");
Json::Value response = client.CallMethod("abcd", params);
Json::Value v = c.GetJsonRequest();
BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
BOOST_CHECK_EQUAL(v["id"].asInt(), 1);
BOOST_CHECK_EQUAL(response.asInt(),23);
}
BOOST_AUTO_TEST_CASE(test_client_notification_success)
{
MockClientConnector c;
Client client(c);
Json::Value params;
params.append(23);
client.CallNotification("abcd", params);
Json::Value v = c.GetJsonRequest();
BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
BOOST_CHECK_EQUAL(v.isMember("id"), false);
}
BOOST_AUTO_TEST_CASE(test_client_error)
{
MockClientConnector c;
Client client(c);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"error\": {\"code\": -32600, \"message\": \"Invalid Request\"}, \"id\": null}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3);
}
BOOST_AUTO_TEST_CASE(test_client_invalidjson)
{
MockClientConnector c;
Client client(c);
c.SetResponse("{\"method\":234");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1);
}
BOOST_AUTO_TEST_CASE(test_client_invalidresponse)
{
MockClientConnector c;
Client client(c);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"resulto\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"jsonrpc\":\"1.0\", \"id\": 1, \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"id\": 1, \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("[]");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("23");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
}
BOOST_AUTO_TEST_CASE(test_client_batchcall_success)
{
MockClientConnector c;
Client client(c);
BatchCall bc;
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, true), -1);
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),2);
c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"result\": 24}]");
BatchResponse response = client.CallProcedures(bc);
BOOST_CHECK_EQUAL(response.hasErrors(), false);
BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
BOOST_CHECK_EQUAL(response.getResult(2).asInt(), 24);
BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
}
BOOST_AUTO_TEST_CASE(test_client_batchcall_error)
{
MockClientConnector c;
Client client(c);
BatchCall bc;
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, false),2);
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),3);
c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"error\": {\"code\": -32001, \"message\": \"error1\"}},{\"jsonrpc\":\"2.0\", \"id\": null, \"error\": {\"code\": -32002, \"message\": \"error2\"}}]");
BatchResponse response = client.CallProcedures(bc);
BOOST_CHECK_EQUAL(response.hasErrors(), true);
BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
BOOST_CHECK_EQUAL(response.getResult(2).isNull(), true);
BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>extended batchcall testcases<commit_after>/*************************************************************************
* libjson-rpc-cpp
*************************************************************************
* @file test_client.cpp
* @date 28.09.2013
* @author Peter Spiess-Knafl <[email protected]>
* @license See attached LICENSE.txt
************************************************************************/
#define BOOST_TEST_MODULE
#include <boost/test/unit_test.hpp>
#include <jsonrpccpp/client.h>
#include "mockclientconnector.h"
using namespace jsonrpc;
using namespace std;
bool check_exception1(JsonRpcException const&ex)
{
return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR;
}
bool check_exception2(JsonRpcException const&ex)
{
return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE;
}
bool check_exception3(JsonRpcException const&ex)
{
return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST;
}
BOOST_AUTO_TEST_SUITE(client)
BOOST_AUTO_TEST_CASE(test_client_method_success)
{
MockClientConnector c;
Client client(c);
Json::Value params;
params.append(23);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23}");
Json::Value response = client.CallMethod("abcd", params);
Json::Value v = c.GetJsonRequest();
BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
BOOST_CHECK_EQUAL(v["id"].asInt(), 1);
BOOST_CHECK_EQUAL(response.asInt(),23);
}
BOOST_AUTO_TEST_CASE(test_client_notification_success)
{
MockClientConnector c;
Client client(c);
Json::Value params;
params.append(23);
client.CallNotification("abcd", params);
Json::Value v = c.GetJsonRequest();
BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
BOOST_CHECK_EQUAL(v.isMember("id"), false);
}
BOOST_AUTO_TEST_CASE(test_client_error)
{
MockClientConnector c;
Client client(c);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"error\": {\"code\": -32600, \"message\": \"Invalid Request\"}, \"id\": null}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3);
}
BOOST_AUTO_TEST_CASE(test_client_invalidjson)
{
MockClientConnector c;
Client client(c);
c.SetResponse("{\"method\":234");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1);
}
BOOST_AUTO_TEST_CASE(test_client_invalidresponse)
{
MockClientConnector c;
Client client(c);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"resulto\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"jsonrpc\":\"1.0\", \"id\": 1, \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"id\": 1, \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{\"jsonrpc\":\"2.0\", \"result\": 23}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("{}");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("[]");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
c.SetResponse("23");
BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
}
BOOST_AUTO_TEST_CASE(test_client_batchcall_success)
{
MockClientConnector c;
Client client(c);
BatchCall bc;
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, true), -1);
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),2);
c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"result\": 24}]");
BatchResponse response = client.CallProcedures(bc);
BOOST_CHECK_EQUAL(response.hasErrors(), false);
BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
BOOST_CHECK_EQUAL(response.getResult(2).asInt(), 24);
BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
Json::Value request = c.GetJsonRequest();
BOOST_CHECK_EQUAL(request.size(), 3);
BOOST_CHECK_EQUAL(request[0]["method"].asString(), "abc");
BOOST_CHECK_EQUAL(request[0]["id"].asInt(), 1);
BOOST_CHECK_EQUAL(request[1]["method"].asString(), "def");
BOOST_CHECK_EQUAL(request[1]["id"].isNull(), true);
BOOST_CHECK_EQUAL(request[2]["id"].asInt(), 2);
}
BOOST_AUTO_TEST_CASE(test_client_batchcall_error)
{
MockClientConnector c;
Client client(c);
BatchCall bc;
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, false),2);
BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),3);
c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"error\": {\"code\": -32001, \"message\": \"error1\"}},{\"jsonrpc\":\"2.0\", \"id\": null, \"error\": {\"code\": -32002, \"message\": \"error2\"}}]");
BatchResponse response = client.CallProcedures(bc);
BOOST_CHECK_EQUAL(response.hasErrors(), true);
BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
BOOST_CHECK_EQUAL(response.getResult(2).isNull(), true);
BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
struct Input {
int r, c, l, h;
vector<vector<bool>> tomatoes;
};
struct Slice {
int r1, c1, r2, c2;
};
struct Output {
vector<Slice> slices;
};
void solveSimple(Input& input, Output& output) {
//TODO add code here
}
void solveDP(Input& input, Output& output) {
//TODO add code here
}
int main() {
ios::sync_with_stdio(false);
//read input
Input input;
cin >> input.r >> input.c >> input.l >> input.h;
for(int i = 0; i < input.r; i++) {
vector<bool> row(input.c);
for(int j = 0; j < input.c; j++) {
char cell;
cin >> cell;
row[j] = cell == 'T';
}
input.tomatoes.push_back(row);
//TODO do we read line breaks?
}
//solve problem
Output output;
solve(input, output);
//print output
cout << output.slices.size() << endl;
};
<commit_msg>Added simple slice function that cuts pizza row by row with stencil size dimension 1 x H<commit_after>#include <iostream>
#include <vector>
using namespace std;
struct Input {
int r, c, l, h;
vector<vector<bool>> tomatoes;
};
struct Slice {
int r1, c1, r2, c2;
};
struct Output {
vector<Slice> slices;
};
void solveSimple(Input& input, Output& output) {
for (int i = 0; i < input.r; i++)
{
for (int j = 0; j < input.c; j += input.h)
{
Slice s;
s.r1 = i;
s.c1 = j;
s.r2 = i;
s.c2 = min(j+input.h-1, input.c-1);
output.slices.push_back(s);
}
}
}
void solveDP(Input& input, Output& output) {
//TODO add code here
}
int main() {
ios::sync_with_stdio(false);
//read input
Input input;
cin >> input.r >> input.c >> input.l >> input.h;
for(int i = 0; i < input.r; i++) {
vector<bool> row(input.c);
for(int j = 0; j < input.c; j++) {
char cell;
cin >> cell;
row[j] = cell == 'T';
}
input.tomatoes.push_back(row);
//TODO do we read line breaks?
}
//solve problem
Output output;
solve(input, output);
//print output
cout << output.slices.size() << endl;
};
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_occ_sram_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_pm_occ_sram_init.C
/// @brief Initialize the SRAM in the OCC
///
// *HWP HWP Owner: Greg Still <[email protected]>
// *HWP FW Owner: Sangeetha T S <[email protected]>
// *HWP Team: PM
// *HWP Level: 1
// *HWP Consumed by: FSP:HS
//
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_pm_occ_sram_init.H>
// -----------------------------------------------------------------------------
// Function definitions
// -----------------------------------------------------------------------------
fapi2::ReturnCode p9_pm_occ_sram_init(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const p9pm::PM_FLOW_MODE i_mode)
{
FAPI_INF("Entering p9_pm_occ_sram_init...");
// Initialization: perform order or dynamic operations to initialize
// the OCC SRAM using necessary Platform or Feature attributes.
if (i_mode == p9pm::PM_INIT)
{
FAPI_INF("OCC SRAM initialization...");
}
// Reset: perform reset of OCC SRAM so that it can reconfigured and
// reinitialized
else if (i_mode == p9pm::PM_RESET)
{
FAPI_INF("OCC SRAM reset...");
}
// Unsupported Mode
else
{
FAPI_ASSERT(false, fapi2::PM_OCCSRAM_BAD_MODE().set_MODE(i_mode),
"ERROR; Unknown mode passed to p9_pm_occ_sram_init. Mode %x",
i_mode);
}
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Level 3 : OCB & OCC procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_occ_sram_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_pm_occ_sram_init.C
/// @brief Initialize the SRAM in the OCC
///
// *HWP HWP Owner: Greg Still <[email protected]>
// *HWP HWP Backup Owner: Amit Kumar <[email protected]>
// *HWP FW Owner: Sangeetha T S <[email protected]>
// *HWP Team: PM
// *HWP Level: 3
// *HWP Consumed by: HS
//
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_pm_occ_sram_init.H>
// -----------------------------------------------------------------------------
// Function definitions
// -----------------------------------------------------------------------------
fapi2::ReturnCode p9_pm_occ_sram_init(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const p9pm::PM_FLOW_MODE i_mode)
{
FAPI_INF("Entering p9_pm_occ_sram_init...");
// Initialization: perform order or dynamic operations to initialize
// the OCC SRAM using necessary Platform or Feature attributes.
if (i_mode == p9pm::PM_INIT)
{
FAPI_INF("OCC SRAM initialization...");
}
// Reset: perform reset of OCC SRAM so that it can reconfigured and
// reinitialized
else if (i_mode == p9pm::PM_RESET)
{
FAPI_INF("OCC SRAM reset...");
}
// Unsupported Mode
else
{
FAPI_ASSERT(false, fapi2::PM_OCCSRAM_BAD_MODE().set_MODE(i_mode),
"ERROR; Unknown mode passed to p9_pm_occ_sram_init. Mode %x",
i_mode);
}
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: Legend.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: bm $ $Date: 2003-10-20 09:59:31 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "Legend.hxx"
#include "macros.hxx"
#include "algohelper.hxx"
#include "LineProperties.hxx"
#include "FillProperties.hxx"
#include "CharacterProperties.hxx"
#include "UserDefinedProperties.hxx"
#include "LegendHelper.hxx"
#include "LayoutDefaults.hxx"
#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_ALIGNMENT_HPP_
#include <drafts/com/sun/star/layout/Alignment.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_STRETCHMODE_HPP_
#include <drafts/com/sun/star/layout/StretchMode.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDPOSITION_HPP_
#include <drafts/com/sun/star/chart2/LegendPosition.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDEXPANSION_HPP_
#include <drafts/com/sun/star/chart2/LegendExpansion.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star;
using namespace ::com::sun::star::beans::PropertyAttribute;
using namespace ::drafts::com::sun::star;
using ::com::sun::star::beans::Property;
namespace
{
static const ::rtl::OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart2.Legend" ));
enum
{
PROP_LEGEND_POSITION,
PROP_LEGEND_PREFERRED_EXPANSION,
PROP_LEGEND_SHOW
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "Position" ),
PROP_LEGEND_POSITION,
::getCppuType( reinterpret_cast< const chart2::LegendPosition * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "Expansion" ),
PROP_LEGEND_PREFERRED_EXPANSION,
::getCppuType( reinterpret_cast< const chart2::LegendExpansion * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "Show" ),
PROP_LEGEND_SHOW,
::getBooleanCppuType(),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::helper::tPropertyValueMap & rOutMap )
{
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_POSITION ));
rOutMap[ PROP_LEGEND_POSITION ] =
uno::makeAny( chart2::LegendPosition_LINE_END );
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_SHOW ));
rOutMap[ PROP_LEGEND_SHOW ] =
uno::makeAny( sal_True );
}
const uno::Sequence< Property > & lcl_GetPropertySequence()
{
static uno::Sequence< Property > aPropSeq;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
::chart::LineProperties::AddPropertiesToVector(
aProperties, /* bIncludeStyleProperties = */ false );
::chart::FillProperties::AddPropertiesToVector(
aProperties, /* bIncludeStyleProperties = */ false );
::chart::CharacterProperties::AddPropertiesToVector(
aProperties, /* bIncludeStyleProperties = */ false );
::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::helper::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::helper::VectorToSequence( aProperties );
}
return aPropSeq;
}
::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper(
lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
} // anonymous namespace
namespace chart
{
Legend::Legend( uno::Reference< uno::XComponentContext > const & xContext ) :
::property::OPropertySet( m_aMutex ),
m_aIdentifier( LegendHelper::getIdentifierForLegend() )
{
setAnchorAndRelposFromProperty( GetDefaultValue( PROP_LEGEND_POSITION ));
}
Legend::~Legend()
{
}
// ____ XLegend ____
void SAL_CALL Legend::registerEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
throw (lang::IllegalArgumentException,
uno::RuntimeException)
{
if( ::std::find( m_aLegendEntries.begin(),
m_aLegendEntries.end(),
xEntry ) != m_aLegendEntries.end())
throw lang::IllegalArgumentException();
m_aLegendEntries.push_back( xEntry );
}
void SAL_CALL Legend::revokeEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
throw (container::NoSuchElementException,
uno::RuntimeException)
{
tLegendEntries::iterator aIt(
::std::find( m_aLegendEntries.begin(),
m_aLegendEntries.end(),
xEntry ));
if( aIt == m_aLegendEntries.end())
throw container::NoSuchElementException();
m_aLegendEntries.erase( aIt );
}
uno::Sequence< uno::Reference< chart2::XLegendEntry > > SAL_CALL Legend::getEntries()
throw (uno::RuntimeException)
{
return ::chart::helper::VectorToSequence( m_aLegendEntries );
}
::rtl::OUString SAL_CALL Legend::getIdentifier()
throw (uno::RuntimeException)
{
return m_aIdentifier;
}
// ____ XAnchoredObject ____
void SAL_CALL Legend::setAnchor( const layout::AnchorPoint& aAnchor )
throw (uno::RuntimeException)
{
m_aAnchor = aAnchor;
}
layout::AnchorPoint SAL_CALL Legend::getAnchor()
throw (uno::RuntimeException)
{
return m_aAnchor;
}
void SAL_CALL Legend::setRelativePosition( const layout::RelativePoint& aPosition )
throw (uno::RuntimeException)
{
m_aRelativePosition = aPosition;
}
layout::RelativePoint SAL_CALL Legend::getRelativePosition()
throw (uno::RuntimeException)
{
return m_aRelativePosition;
}
// private
void Legend::setAnchorAndRelposFromProperty( const uno::Any & rValue )
{
chart2::LegendPosition ePos;
if( rValue >>= ePos )
{
m_aAnchor.AnchorHolder = uno::Reference< layout::XAnchor >();
// shift legend about 2% into the primary direction
m_aRelativePosition.Primary = 0.02;
m_aRelativePosition.Secondary = 0.0;
switch( ePos )
{
case chart2::LegendPosition_LINE_START:
m_aAnchor.Alignment = ::layout_defaults::const_aLineStart;
m_aAnchor.EscapeDirection = 0.0;
break;
case chart2::LegendPosition_LINE_END:
m_aAnchor.Alignment = ::layout_defaults::const_aLineEnd;
m_aAnchor.EscapeDirection = 180.0;
break;
case chart2::LegendPosition_PAGE_START:
m_aAnchor.Alignment = ::layout_defaults::const_aPageStart;
m_aAnchor.EscapeDirection = 270.0;
break;
case chart2::LegendPosition_PAGE_END:
m_aAnchor.Alignment = ::layout_defaults::const_aPageEnd;
m_aAnchor.EscapeDirection = 90.0;
break;
case chart2::LegendPosition_CUSTOM:
// to avoid warning
case chart2::LegendPosition_MAKE_FIXED_SIZE:
// nothing to be set
break;
}
}
}
// ================================================================================
uno::Sequence< ::rtl::OUString > Legend::getSupportedServiceNames_Static()
{
uno::Sequence< ::rtl::OUString > aServices( 5 );
aServices[ 0 ] = C2U( "drafts.com.sun.star.chart2.Legend" );
aServices[ 1 ] = C2U( "com.sun.star.beans.PropertySet" );
aServices[ 2 ] = C2U( "com.sun.star.drawing.FillProperties" );
aServices[ 3 ] = C2U( "com.sun.star.drawing.LineProperties" );
aServices[ 4 ] = C2U( "drafts.com.sun.star.layout.LayoutElement" );
return aServices;
}
// ____ OPropertySet ____
uno::Any Legend::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static helper::tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
lcl_AddDefaultsToMap( aStaticDefaults );
LineProperties::AddDefaultsToMap(
aStaticDefaults,
/* bIncludeStyleProperties = */ false );
FillProperties::AddDefaultsToMap(
aStaticDefaults,
/* bIncludeStyleProperties = */ false );
CharacterProperties::AddDefaultsToMap(
aStaticDefaults,
/* bIncludeStyleProperties = */ false );
}
helper::tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
::cppu::IPropertyArrayHelper & SAL_CALL Legend::getInfoHelper()
{
return lcl_getInfoHelper();
}
// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
Legend::getPropertySetInfo()
throw (uno::RuntimeException)
{
static uno::Reference< beans::XPropertySetInfo > xInfo;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
void SAL_CALL Legend::setFastPropertyValue_NoBroadcast
( sal_Int32 nHandle, const uno::Any& rValue )
throw (uno::Exception)
{
if( nHandle == PROP_LEGEND_POSITION )
setAnchorAndRelposFromProperty( rValue );
OPropertySet::setFastPropertyValue_NoBroadcast( nHandle, rValue );
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( Legend, lcl_aServiceName );
// needed by MSC compiler
using impl::Legend_Base;
IMPLEMENT_FORWARD_XINTERFACE2( Legend, Legend_Base, ::property::OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( Legend, Legend_Base, ::property::OPropertySet )
} // namespace chart
<commit_msg>XAnchor removed from AnchorPoint<commit_after>/*************************************************************************
*
* $RCSfile: Legend.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: bm $ $Date: 2003-10-29 09:49:09 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "Legend.hxx"
#include "macros.hxx"
#include "algohelper.hxx"
#include "LineProperties.hxx"
#include "FillProperties.hxx"
#include "CharacterProperties.hxx"
#include "UserDefinedProperties.hxx"
#include "LegendHelper.hxx"
#include "LayoutDefaults.hxx"
#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_ALIGNMENT_HPP_
#include <drafts/com/sun/star/layout/Alignment.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_STRETCHMODE_HPP_
#include <drafts/com/sun/star/layout/StretchMode.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDPOSITION_HPP_
#include <drafts/com/sun/star/chart2/LegendPosition.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDEXPANSION_HPP_
#include <drafts/com/sun/star/chart2/LegendExpansion.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star;
using namespace ::com::sun::star::beans::PropertyAttribute;
using namespace ::drafts::com::sun::star;
using ::com::sun::star::beans::Property;
namespace
{
static const ::rtl::OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart2.Legend" ));
enum
{
PROP_LEGEND_POSITION,
PROP_LEGEND_PREFERRED_EXPANSION,
PROP_LEGEND_SHOW
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "Position" ),
PROP_LEGEND_POSITION,
::getCppuType( reinterpret_cast< const chart2::LegendPosition * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "Expansion" ),
PROP_LEGEND_PREFERRED_EXPANSION,
::getCppuType( reinterpret_cast< const chart2::LegendExpansion * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "Show" ),
PROP_LEGEND_SHOW,
::getBooleanCppuType(),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::helper::tPropertyValueMap & rOutMap )
{
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_POSITION ));
rOutMap[ PROP_LEGEND_POSITION ] =
uno::makeAny( chart2::LegendPosition_LINE_END );
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_SHOW ));
rOutMap[ PROP_LEGEND_SHOW ] =
uno::makeAny( sal_True );
}
const uno::Sequence< Property > & lcl_GetPropertySequence()
{
static uno::Sequence< Property > aPropSeq;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
::chart::LineProperties::AddPropertiesToVector(
aProperties, /* bIncludeStyleProperties = */ false );
::chart::FillProperties::AddPropertiesToVector(
aProperties, /* bIncludeStyleProperties = */ false );
::chart::CharacterProperties::AddPropertiesToVector(
aProperties, /* bIncludeStyleProperties = */ false );
::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::helper::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::helper::VectorToSequence( aProperties );
}
return aPropSeq;
}
::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper(
lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
} // anonymous namespace
namespace chart
{
Legend::Legend( uno::Reference< uno::XComponentContext > const & xContext ) :
::property::OPropertySet( m_aMutex ),
m_aIdentifier( LegendHelper::getIdentifierForLegend() )
{
setAnchorAndRelposFromProperty( GetDefaultValue( PROP_LEGEND_POSITION ));
}
Legend::~Legend()
{
}
// ____ XLegend ____
void SAL_CALL Legend::registerEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
throw (lang::IllegalArgumentException,
uno::RuntimeException)
{
if( ::std::find( m_aLegendEntries.begin(),
m_aLegendEntries.end(),
xEntry ) != m_aLegendEntries.end())
throw lang::IllegalArgumentException();
m_aLegendEntries.push_back( xEntry );
}
void SAL_CALL Legend::revokeEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
throw (container::NoSuchElementException,
uno::RuntimeException)
{
tLegendEntries::iterator aIt(
::std::find( m_aLegendEntries.begin(),
m_aLegendEntries.end(),
xEntry ));
if( aIt == m_aLegendEntries.end())
throw container::NoSuchElementException();
m_aLegendEntries.erase( aIt );
}
uno::Sequence< uno::Reference< chart2::XLegendEntry > > SAL_CALL Legend::getEntries()
throw (uno::RuntimeException)
{
return ::chart::helper::VectorToSequence( m_aLegendEntries );
}
::rtl::OUString SAL_CALL Legend::getIdentifier()
throw (uno::RuntimeException)
{
return m_aIdentifier;
}
// ____ XAnchoredObject ____
void SAL_CALL Legend::setAnchor( const layout::AnchorPoint& aAnchor )
throw (uno::RuntimeException)
{
m_aAnchor = aAnchor;
}
layout::AnchorPoint SAL_CALL Legend::getAnchor()
throw (uno::RuntimeException)
{
return m_aAnchor;
}
void SAL_CALL Legend::setRelativePosition( const layout::RelativePoint& aPosition )
throw (uno::RuntimeException)
{
m_aRelativePosition = aPosition;
}
layout::RelativePoint SAL_CALL Legend::getRelativePosition()
throw (uno::RuntimeException)
{
return m_aRelativePosition;
}
// private
void Legend::setAnchorAndRelposFromProperty( const uno::Any & rValue )
{
chart2::LegendPosition ePos;
if( rValue >>= ePos )
{
// shift legend about 2% into the primary direction
m_aRelativePosition.Primary = 0.02;
m_aRelativePosition.Secondary = 0.0;
switch( ePos )
{
case chart2::LegendPosition_LINE_START:
m_aAnchor.Alignment = ::layout_defaults::const_aLineStart;
m_aAnchor.EscapeDirection = 0.0;
break;
case chart2::LegendPosition_LINE_END:
m_aAnchor.Alignment = ::layout_defaults::const_aLineEnd;
m_aAnchor.EscapeDirection = 180.0;
break;
case chart2::LegendPosition_PAGE_START:
m_aAnchor.Alignment = ::layout_defaults::const_aPageStart;
m_aAnchor.EscapeDirection = 270.0;
break;
case chart2::LegendPosition_PAGE_END:
m_aAnchor.Alignment = ::layout_defaults::const_aPageEnd;
m_aAnchor.EscapeDirection = 90.0;
break;
case chart2::LegendPosition_CUSTOM:
// to avoid warning
case chart2::LegendPosition_MAKE_FIXED_SIZE:
// nothing to be set
break;
}
}
}
// ================================================================================
uno::Sequence< ::rtl::OUString > Legend::getSupportedServiceNames_Static()
{
uno::Sequence< ::rtl::OUString > aServices( 5 );
aServices[ 0 ] = C2U( "drafts.com.sun.star.chart2.Legend" );
aServices[ 1 ] = C2U( "com.sun.star.beans.PropertySet" );
aServices[ 2 ] = C2U( "com.sun.star.drawing.FillProperties" );
aServices[ 3 ] = C2U( "com.sun.star.drawing.LineProperties" );
aServices[ 4 ] = C2U( "drafts.com.sun.star.layout.LayoutElement" );
return aServices;
}
// ____ OPropertySet ____
uno::Any Legend::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static helper::tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
lcl_AddDefaultsToMap( aStaticDefaults );
LineProperties::AddDefaultsToMap(
aStaticDefaults,
/* bIncludeStyleProperties = */ false );
FillProperties::AddDefaultsToMap(
aStaticDefaults,
/* bIncludeStyleProperties = */ false );
CharacterProperties::AddDefaultsToMap(
aStaticDefaults,
/* bIncludeStyleProperties = */ false );
}
helper::tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
::cppu::IPropertyArrayHelper & SAL_CALL Legend::getInfoHelper()
{
return lcl_getInfoHelper();
}
// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
Legend::getPropertySetInfo()
throw (uno::RuntimeException)
{
static uno::Reference< beans::XPropertySetInfo > xInfo;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
void SAL_CALL Legend::setFastPropertyValue_NoBroadcast
( sal_Int32 nHandle, const uno::Any& rValue )
throw (uno::Exception)
{
if( nHandle == PROP_LEGEND_POSITION )
setAnchorAndRelposFromProperty( rValue );
OPropertySet::setFastPropertyValue_NoBroadcast( nHandle, rValue );
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( Legend, lcl_aServiceName );
// needed by MSC compiler
using impl::Legend_Base;
IMPLEMENT_FORWARD_XINTERFACE2( Legend, Legend_Base, ::property::OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( Legend, Legend_Base, ::property::OPropertySet )
} // namespace chart
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageDifference.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkImageDifference.h"
#include "stdlib.h"
// Description:
// Construct object to extract all of the input data.
vtkImageDifference::vtkImageDifference()
{
this->Error = 0;
this->ThresholdedError = 0.0;
this->Image = NULL;
this->Threshold = 51;
this->AllowShift = 1;
}
// simple macro for calculating error
#define vtkImageDifferenceComputeError(c1,c2) \
r1 = abs(c1[0] - c2[0]); g1 = abs(c1[1] - c2[1]); b1 = abs(c1[2] - c2[2]); \
if ((r1+g1+b1) < (tr+tg+tb)) { tr = r1; tg = g1; tb = b1; }
void vtkImageDifference::Execute()
{
vtkStructuredPoints *input = (vtkStructuredPoints *)this->Input;
vtkPointData *pd1 = input->GetPointData();
vtkPointData *pd2 = this->Image->GetPointData();
vtkStructuredPoints *output=(vtkStructuredPoints *)this->Output;
vtkPointData *outPD=output->GetPointData();
int *dims1, *dims2, sliceSize;
int row, col, idx;
vtkScalars *s1, *s2;
float color1[4], color2[4], outColor[4];
int tr, tg, tb, r1, g1, b1;
vtkScalars *outScalars = vtkScalars::New(VTK_UNSIGNED_CHAR,3);
vtkDebugMacro(<< "Comparing Images");
dims1 = input->GetDimensions();
dims2 = this->Image->GetDimensions();
if ((dims1[0] != dims2[0]) ||
(dims1[1] != dims2[1]) ||
(dims1[2] != dims2[2]))
{
vtkWarningMacro(<< "Images are not the same size: " <<
dims1[0] << ", " << dims1[1] << ", " << dims1[2] << " != " <<
dims2[0] << ", " << dims2[1] << ", " << dims2[2] );
this->Error = 1;
this->ThresholdedError = 1;
return;
}
// make sure the images are of the correct type
s1 = pd1->GetScalars();
s2 = pd2->GetScalars();
//
// Allocate necessary objects
//
output->SetDimensions(dims1);
sliceSize = dims1[0]*dims1[1];
this->Error = 0;
this->ThresholdedError = 0;
for (row = 0; row < dims1[1]; row++)
{
idx = row*dims1[0];
for (col = 0; col < dims1[0]; col++)
{
tr = 1000;
tg = 1000;
tb = 1000;
s2->GetData()->GetTuple(idx+col,color2);
/* check the exact match pixel */
s1->GetData()->GetTuple(idx+col,color1);
vtkImageDifferenceComputeError(color1,color2);
/* If AllowShift, then we examine neighboring pixels to
find the least difference. This feature is used to
allow images to shift slightly between different graphics
systems, like between opengl and starbase. */
if (this->AllowShift)
{
/* check the pixel to the left */
if (col)
{
s1->GetData()->GetTuple(idx + col - 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the pixel to the right */
if (col < (dims1[0] -1))
{
s1->GetData()->GetTuple(idx + col + 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the line above if there is one */
if (row)
{
/* check the exact match pixel */
s1->GetData()->GetTuple(idx - dims1[0] + col, color1);
vtkImageDifferenceComputeError(color1,color2);
/* check the pixel to the left */
if (col)
{
s1->GetData()->GetTuple(idx - dims1[0] + col - 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the pixel to the right */
if (col < (dims1[0] -1))
{
s1->GetData()->GetTuple(idx - dims1[0] + col + 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
}
/* check the line below if there is one */
if (row < (dims1[1] - 1))
{
/* check the exact match pixel */
s1->GetData()->GetTuple(idx + dims1[0] + col, color1);
vtkImageDifferenceComputeError(color1,color2);
/* check the pixel to the left */
if (col)
{
s1->GetData()->GetTuple(idx + dims1[0] + col - 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the pixel to the right */
if (col < (dims1[0] -1))
{
s1->GetData()->GetTuple(idx + dims1[0] + col + 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
}
}
this->Error = this->Error + (tr + tg + tb)/(3.0*255);
tr -= this->Threshold;
if (tr < 0) tr = 0;
tg -= this->Threshold;
if (tg < 0) tg = 0;
tb -= this->Threshold;
if (tb < 0) tb = 0;
outColor[0] = tr;
outColor[1] = tg;
outColor[2] = tb;
this->ThresholdedError =
this->ThresholdedError + (tr + tg + tb)/(3.0*255.0);
outScalars->GetData()->InsertNextTuple(outColor);
}
}
outPD->SetScalars(outScalars);
outScalars->Delete();
}
void vtkImageDifference::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredPointsFilter::PrintSelf(os,indent);
os << indent << "Error: " << this->Error << "\n";
os << indent << "ThresholdedError: " << this->ThresholdedError << "\n";
os << indent << "Threshold: " << this->Threshold << "\n";
os << indent << "AllowShift: " << this->AllowShift << "\n";
}
// Description:
// Override update method because execution can branch two ways (Input
// and Image)
void vtkImageDifference::Update()
{
// make sure input is available
if ( this->Input == NULL || this->Image == NULL)
{
vtkErrorMacro(<< "No input...can't execute!");
return;
}
// prevent chasing our tail
if (this->Updating) return;
this->Updating = 1;
this->Input->Update();
this->Image->Update();
this->Updating = 0;
if (this->Input->GetMTime() > this->ExecuteTime ||
this->Image->GetMTime() > this->ExecuteTime ||
this->GetMTime() > this->ExecuteTime || this->GetDataReleased() )
{
if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
this->Output->Initialize(); //clear output
// reset AbortExecute flag and Progress
this->AbortExecute = 0;
this->Progress = 0.0;
this->Execute();
this->ExecuteTime.Modified();
this->SetDataReleased(0);
if ( !this->AbortExecute ) this->UpdateProgress(1.0);
if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
}
if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();
if ( this->Image->ShouldIReleaseData() ) this->Image->ReleaseData();
}
<commit_msg>BUG: minor compile bug<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageDifference.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkImageDifference.h"
#include "stdlib.h"
// Description:
// Construct object to extract all of the input data.
vtkImageDifference::vtkImageDifference()
{
this->Error = 0;
this->ThresholdedError = 0.0;
this->Image = NULL;
this->Threshold = 51;
this->AllowShift = 1;
}
// simple macro for calculating error
#define vtkImageDifferenceComputeError(c1,c2) \
r1 = abs((int)(c1[0] - c2[0])); g1 = abs((int)(c1[1] - c2[1])); b1 = abs((int)(c1[2] - c2[2])); \
if ((r1+g1+b1) < (tr+tg+tb)) { tr = r1; tg = g1; tb = b1; }
void vtkImageDifference::Execute()
{
vtkStructuredPoints *input = (vtkStructuredPoints *)this->Input;
vtkPointData *pd1 = input->GetPointData();
vtkPointData *pd2 = this->Image->GetPointData();
vtkStructuredPoints *output=(vtkStructuredPoints *)this->Output;
vtkPointData *outPD=output->GetPointData();
int *dims1, *dims2, sliceSize;
int row, col, idx;
vtkScalars *s1, *s2;
float color1[4], color2[4], outColor[4];
int tr, tg, tb, r1, g1, b1;
vtkScalars *outScalars = vtkScalars::New(VTK_UNSIGNED_CHAR,3);
vtkDebugMacro(<< "Comparing Images");
dims1 = input->GetDimensions();
dims2 = this->Image->GetDimensions();
if ((dims1[0] != dims2[0]) ||
(dims1[1] != dims2[1]) ||
(dims1[2] != dims2[2]))
{
vtkWarningMacro(<< "Images are not the same size: " <<
dims1[0] << ", " << dims1[1] << ", " << dims1[2] << " != " <<
dims2[0] << ", " << dims2[1] << ", " << dims2[2] );
this->Error = 1;
this->ThresholdedError = 1;
return;
}
// make sure the images are of the correct type
s1 = pd1->GetScalars();
s2 = pd2->GetScalars();
//
// Allocate necessary objects
//
output->SetDimensions(dims1);
sliceSize = dims1[0]*dims1[1];
this->Error = 0;
this->ThresholdedError = 0;
for (row = 0; row < dims1[1]; row++)
{
idx = row*dims1[0];
for (col = 0; col < dims1[0]; col++)
{
tr = 1000;
tg = 1000;
tb = 1000;
s2->GetData()->GetTuple(idx+col,color2);
/* check the exact match pixel */
s1->GetData()->GetTuple(idx+col,color1);
vtkImageDifferenceComputeError(color1,color2);
/* If AllowShift, then we examine neighboring pixels to
find the least difference. This feature is used to
allow images to shift slightly between different graphics
systems, like between opengl and starbase. */
if (this->AllowShift)
{
/* check the pixel to the left */
if (col)
{
s1->GetData()->GetTuple(idx + col - 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the pixel to the right */
if (col < (dims1[0] -1))
{
s1->GetData()->GetTuple(idx + col + 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the line above if there is one */
if (row)
{
/* check the exact match pixel */
s1->GetData()->GetTuple(idx - dims1[0] + col, color1);
vtkImageDifferenceComputeError(color1,color2);
/* check the pixel to the left */
if (col)
{
s1->GetData()->GetTuple(idx - dims1[0] + col - 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the pixel to the right */
if (col < (dims1[0] -1))
{
s1->GetData()->GetTuple(idx - dims1[0] + col + 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
}
/* check the line below if there is one */
if (row < (dims1[1] - 1))
{
/* check the exact match pixel */
s1->GetData()->GetTuple(idx + dims1[0] + col, color1);
vtkImageDifferenceComputeError(color1,color2);
/* check the pixel to the left */
if (col)
{
s1->GetData()->GetTuple(idx + dims1[0] + col - 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
/* check the pixel to the right */
if (col < (dims1[0] -1))
{
s1->GetData()->GetTuple(idx + dims1[0] + col + 1, color1);
vtkImageDifferenceComputeError(color1,color2);
}
}
}
this->Error = this->Error + (tr + tg + tb)/(3.0*255);
tr -= this->Threshold;
if (tr < 0) tr = 0;
tg -= this->Threshold;
if (tg < 0) tg = 0;
tb -= this->Threshold;
if (tb < 0) tb = 0;
outColor[0] = tr;
outColor[1] = tg;
outColor[2] = tb;
this->ThresholdedError =
this->ThresholdedError + (tr + tg + tb)/(3.0*255.0);
outScalars->GetData()->InsertNextTuple(outColor);
}
}
outPD->SetScalars(outScalars);
outScalars->Delete();
}
void vtkImageDifference::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredPointsFilter::PrintSelf(os,indent);
os << indent << "Error: " << this->Error << "\n";
os << indent << "ThresholdedError: " << this->ThresholdedError << "\n";
os << indent << "Threshold: " << this->Threshold << "\n";
os << indent << "AllowShift: " << this->AllowShift << "\n";
}
// Description:
// Override update method because execution can branch two ways (Input
// and Image)
void vtkImageDifference::Update()
{
// make sure input is available
if ( this->Input == NULL || this->Image == NULL)
{
vtkErrorMacro(<< "No input...can't execute!");
return;
}
// prevent chasing our tail
if (this->Updating) return;
this->Updating = 1;
this->Input->Update();
this->Image->Update();
this->Updating = 0;
if (this->Input->GetMTime() > this->ExecuteTime ||
this->Image->GetMTime() > this->ExecuteTime ||
this->GetMTime() > this->ExecuteTime || this->GetDataReleased() )
{
if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
this->Output->Initialize(); //clear output
// reset AbortExecute flag and Progress
this->AbortExecute = 0;
this->Progress = 0.0;
this->Execute();
this->ExecuteTime.Modified();
this->SetDataReleased(0);
if ( !this->AbortExecute ) this->UpdateProgress(1.0);
if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
}
if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();
if ( this->Image->ShouldIReleaseData() ) this->Image->ReleaseData();
}
<|endoftext|> |
<commit_before>// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include <memory>
#include <vector>
#include "core/fpdfapi/fpdf_parser/include/cpdf_array.h"
#include "core/fpdfapi/fpdf_parser/include/cpdf_document.h"
#include "core/fpdfapi/fpdf_parser/include/cpdf_string.h"
#include "core/fpdfdoc/include/fpdf_doc.h"
CPDF_Bookmark CPDF_BookmarkTree::GetFirstChild(
const CPDF_Bookmark& parent) const {
if (!parent.GetDict()) {
CPDF_Dictionary* pRoot = m_pDocument->GetRoot()->GetDictBy("Outlines");
if (!pRoot)
return CPDF_Bookmark();
return CPDF_Bookmark(pRoot->GetDictBy("First"));
}
return CPDF_Bookmark(parent.GetDict()->GetDictBy("First"));
}
CPDF_Bookmark CPDF_BookmarkTree::GetNextSibling(
const CPDF_Bookmark& bookmark) const {
if (!bookmark.GetDict())
return CPDF_Bookmark();
CPDF_Dictionary* pNext = bookmark.GetDict()->GetDictBy("Next");
return pNext == bookmark.GetDict() ? CPDF_Bookmark() : CPDF_Bookmark(pNext);
}
uint32_t CPDF_Bookmark::GetColorRef() const {
if (!m_pDict) {
return 0;
}
CPDF_Array* pColor = m_pDict->GetArrayBy("C");
if (!pColor) {
return FXSYS_RGB(0, 0, 0);
}
int r = FXSYS_round(pColor->GetNumberAt(0) * 255);
int g = FXSYS_round(pColor->GetNumberAt(1) * 255);
int b = FXSYS_round(pColor->GetNumberAt(2) * 255);
return FXSYS_RGB(r, g, b);
}
uint32_t CPDF_Bookmark::GetFontStyle() const {
if (!m_pDict) {
return 0;
}
return m_pDict->GetIntegerBy("F");
}
CFX_WideString CPDF_Bookmark::GetTitle() const {
if (!m_pDict) {
return CFX_WideString();
}
CPDF_String* pString = ToString(m_pDict->GetDirectObjectBy("Title"));
if (!pString)
return CFX_WideString();
CFX_WideString title = pString->GetUnicodeText();
int len = title.GetLength();
if (!len) {
return CFX_WideString();
}
std::unique_ptr<FX_WCHAR[]> buf(new FX_WCHAR[len]);
for (int i = 0; i < len; i++) {
FX_WCHAR w = title[i];
buf[i] = w > 0x20 ? w : 0x20;
}
return CFX_WideString(buf.get(), len);
}
CPDF_Dest CPDF_Bookmark::GetDest(CPDF_Document* pDocument) const {
if (!m_pDict)
return CPDF_Dest();
CPDF_Object* pDest = m_pDict->GetDirectObjectBy("Dest");
if (!pDest)
return CPDF_Dest();
if (pDest->IsString() || pDest->IsName()) {
CPDF_NameTree name_tree(pDocument, "Dests");
return CPDF_Dest(name_tree.LookupNamedDest(pDocument, pDest->GetString()));
}
if (CPDF_Array* pArray = pDest->AsArray())
return CPDF_Dest(pArray);
return CPDF_Dest();
}
CPDF_Action CPDF_Bookmark::GetAction() const {
if (!m_pDict) {
return CPDF_Action();
}
return CPDF_Action(m_pDict->GetDictBy("A"));
}
<commit_msg>Fix a nullptr deref in CPDF_BookmarkTree::GetFirstChild().<commit_after>// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include <memory>
#include <vector>
#include "core/fpdfapi/fpdf_parser/include/cpdf_array.h"
#include "core/fpdfapi/fpdf_parser/include/cpdf_document.h"
#include "core/fpdfapi/fpdf_parser/include/cpdf_string.h"
#include "core/fpdfdoc/include/fpdf_doc.h"
CPDF_Bookmark CPDF_BookmarkTree::GetFirstChild(
const CPDF_Bookmark& parent) const {
CPDF_Dictionary* pParentDict = parent.GetDict();
if (pParentDict)
return CPDF_Bookmark(pParentDict->GetDictBy("First"));
CPDF_Dictionary* pRoot = m_pDocument->GetRoot();
if (!pRoot)
return CPDF_Bookmark();
CPDF_Dictionary* pOutlines = pRoot->GetDictBy("Outlines");
if (!pOutlines)
return CPDF_Bookmark();
return CPDF_Bookmark(pOutlines->GetDictBy("First"));
}
CPDF_Bookmark CPDF_BookmarkTree::GetNextSibling(
const CPDF_Bookmark& bookmark) const {
CPDF_Dictionary* pDict = bookmark.GetDict();
if (!pDict)
return CPDF_Bookmark();
CPDF_Dictionary* pNext = pDict->GetDictBy("Next");
return pNext == pDict ? CPDF_Bookmark() : CPDF_Bookmark(pNext);
}
uint32_t CPDF_Bookmark::GetColorRef() const {
if (!m_pDict)
return FXSYS_RGB(0, 0, 0);
CPDF_Array* pColor = m_pDict->GetArrayBy("C");
if (!pColor)
return FXSYS_RGB(0, 0, 0);
int r = FXSYS_round(pColor->GetNumberAt(0) * 255);
int g = FXSYS_round(pColor->GetNumberAt(1) * 255);
int b = FXSYS_round(pColor->GetNumberAt(2) * 255);
return FXSYS_RGB(r, g, b);
}
uint32_t CPDF_Bookmark::GetFontStyle() const {
return m_pDict ? m_pDict->GetIntegerBy("F") : 0;
}
CFX_WideString CPDF_Bookmark::GetTitle() const {
if (!m_pDict) {
return CFX_WideString();
}
CPDF_String* pString = ToString(m_pDict->GetDirectObjectBy("Title"));
if (!pString)
return CFX_WideString();
CFX_WideString title = pString->GetUnicodeText();
int len = title.GetLength();
if (!len) {
return CFX_WideString();
}
std::unique_ptr<FX_WCHAR[]> buf(new FX_WCHAR[len]);
for (int i = 0; i < len; i++) {
FX_WCHAR w = title[i];
buf[i] = w > 0x20 ? w : 0x20;
}
return CFX_WideString(buf.get(), len);
}
CPDF_Dest CPDF_Bookmark::GetDest(CPDF_Document* pDocument) const {
if (!m_pDict)
return CPDF_Dest();
CPDF_Object* pDest = m_pDict->GetDirectObjectBy("Dest");
if (!pDest)
return CPDF_Dest();
if (pDest->IsString() || pDest->IsName()) {
CPDF_NameTree name_tree(pDocument, "Dests");
return CPDF_Dest(name_tree.LookupNamedDest(pDocument, pDest->GetString()));
}
if (CPDF_Array* pArray = pDest->AsArray())
return CPDF_Dest(pArray);
return CPDF_Dest();
}
CPDF_Action CPDF_Bookmark::GetAction() const {
if (!m_pDict) {
return CPDF_Action();
}
return CPDF_Action(m_pDict->GetDictBy("A"));
}
<|endoftext|> |
<commit_before><commit_msg>Increase the % coverage for coalescing for paint rects.<commit_after><|endoftext|> |
<commit_before>#include <atomic>
static int test()
{
std::atomic<int> x;
return x;
}
int main()
{
return test();
}
<commit_msg>cmake: use 'long long' for atomic check<commit_after>#include <atomic>
static int test()
{
std::atomic<long long> x;
return x;
}
int main()
{
return test();
}
<|endoftext|> |
<commit_before>#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexBuffer9.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.h"
#include "libGLESv2/renderer/d3d/d3d9/formatutils9.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
SafeRelease(mVertexDeclCache[i].vertexDeclaration);
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DCAPS9 caps;
device->GetDeviceCaps(&caps);
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
gl::VertexFormat vertexFormat(*attributes[i].attribute, GL_FLOAT);
const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexFormat);
element->Stream = stream;
element->Offset = 0;
element->Type = d3d9VertexInfo.nativeFormat;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
SafeRelease(lastCache->vertexDeclaration);
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
<commit_msg>Fix application of vertex divisor for non-instanced draws in D3D9<commit_after>#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexBuffer9.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.h"
#include "libGLESv2/renderer/d3d/d3d9/formatutils9.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
SafeRelease(mVertexDeclCache[i].vertexDeclaration);
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances == 0)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; ++i)
{
if (attributes[i].divisor != 0)
{
// If a divisor is set, it still applies even if an instanced draw was not used, so treat
// as a single-instance draw.
instances = 1;
break;
}
}
}
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DCAPS9 caps;
device->GetDeviceCaps(&caps);
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
gl::VertexFormat vertexFormat(*attributes[i].attribute, GL_FLOAT);
const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexFormat);
element->Stream = stream;
element->Offset = 0;
element->Type = d3d9VertexInfo.nativeFormat;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
SafeRelease(lastCache->vertexDeclaration);
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
<|endoftext|> |
<commit_before>// @(#)root/gui:$Id$
// Author: Fons Rademakers 15/07/98
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootEmbeddedCanvas //
// //
// This class creates a TGCanvas in which a TCanvas is created. Use //
// GetCanvas() to get a pointer to the TCanvas. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TRootEmbeddedCanvas.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "Riostream.h"
#include "TStyle.h"
#include "TPluginManager.h"
#include "TVirtualGL.h"
#include "TGDNDManager.h"
#include "TBufferFile.h"
#include "TImage.h"
#include "TClass.h"
#include "TUrl.h"
//////////////////////////////////////////////////////////////////////////
// //
// TRootEmbeddedContainer //
// //
// Utility class used by TRootEmbeddedCanvas. The TRootEmbeddedContainer//
// is the frame embedded in the TGCanvas widget. The ROOT graphics goes //
// into this frame. This class is used to enable input events on this //
// graphics frame and forward the events to the TRootEmbeddedCanvas //
// handlers. //
// //
//////////////////////////////////////////////////////////////////////////
class TRootEmbeddedContainer : public TGCompositeFrame {
private:
TRootEmbeddedCanvas *fCanvas; // pointer back to embedded canvas
public:
TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id, const TGWindow *parent);
Bool_t HandleButton(Event_t *ev)
{ return fCanvas->HandleContainerButton(ev); }
Bool_t HandleDoubleClick(Event_t *ev)
{ return fCanvas->HandleContainerDoubleClick(ev); }
Bool_t HandleConfigureNotify(Event_t *ev)
{ TGFrame::HandleConfigureNotify(ev);
return fCanvas->HandleContainerConfigure(ev); }
Bool_t HandleKey(Event_t *ev)
{ return fCanvas->HandleContainerKey(ev); }
Bool_t HandleMotion(Event_t *ev)
{ return fCanvas->HandleContainerMotion(ev); }
Bool_t HandleExpose(Event_t *ev)
{ return fCanvas->HandleContainerExpose(ev); }
Bool_t HandleCrossing(Event_t *ev)
{ return fCanvas->HandleContainerCrossing(ev); }
void SetEditable(Bool_t) { }
};
//______________________________________________________________________________
TRootEmbeddedContainer::TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id,
const TGWindow *p) : TGCompositeFrame(gClient, id, p)
{
// Create a canvas container.
fCanvas = c;
gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,
kButtonPressMask | kButtonReleaseMask |
kPointerMotionMask, kNone, kNone);
AddInput(kKeyPressMask | kKeyReleaseMask | kPointerMotionMask |
kExposureMask | kStructureNotifyMask | kLeaveWindowMask);
fEditDisabled = kEditDisableGrab;
}
ClassImp(TRootEmbeddedCanvas)
//______________________________________________________________________________
TRootEmbeddedCanvas::TRootEmbeddedCanvas(const char *name, const TGWindow *p,
UInt_t w, UInt_t h, UInt_t options, ULong_t back)
: TGCanvas(p, w, h, options, back)
{
// Create an TCanvas embedded in a TGFrame. A pointer to the TCanvas can
// be obtained via the GetCanvas() member function. To embed a canvas
// derived from a TCanvas do the following:
// TRootEmbeddedCanvas *embedded = new TRootEmbeddedCanvas(0, p, w, h);
// [note name must be 0, not null string ""]
// Int_t wid = embedded->GetCanvasWindowId();
// TMyCanvas *myc = new TMyCanvas("myname", 10, 10, wid);
// embedded->AdoptCanvas(myc);
// [ the MyCanvas is adopted by the embedded canvas and will be
// destroyed by it ]
fCanvas = 0;
fButton = 0;
fAutoFit = kTRUE;
fEditDisabled = kEditDisableLayout;
fCWinId = -1;
if (gStyle->GetCanvasPreferGL()) {
//first, initialize GL (if not yet)
if (!gGLManager) {
TString x = "win32";
if (gVirtualX->InheritsFrom("TGX11"))
x = "x11";
TPluginHandler *ph = gROOT->GetPluginManager()->FindHandler("TGLManager", x);
if (ph && ph->LoadPlugin() != -1) {
if (!ph->ExecPlugin(0))
Warning("CreateCanvas",
"Cannot load GL, will use default canvas imp instead\n");
}
}
if (gGLManager) {
fCWinId = gGLManager->InitGLWindow((ULong_t)GetViewPort()->GetId());
}
}
if (fCWinId == -1)
fCWinId = gVirtualX->InitWindow((ULong_t)GetViewPort()->GetId());
Window_t win = gVirtualX->GetWindowID(fCWinId);
fCanvasContainer = new TRootEmbeddedContainer(this, win, GetViewPort());
SetContainer(fCanvasContainer);
fCanvas = new TCanvas(name ? name : Form("%s_canvas", GetName()), w, h, fCWinId);
// define DND types
fDNDTypeList = new Atom_t[3];
fDNDTypeList[0] = gVirtualX->InternAtom("application/root", kFALSE);
fDNDTypeList[1] = gVirtualX->InternAtom("text/uri-list", kFALSE);
fDNDTypeList[2] = 0;
gVirtualX->SetDNDAware(fId, fDNDTypeList);
SetDNDTarget(kTRUE);
if (!p) {
fCanvas->SetBorderMode(0);
MapSubwindows();
Resize(100, 100);
}
}
//______________________________________________________________________________
TRootEmbeddedCanvas::~TRootEmbeddedCanvas()
{
// Delete embedded ROOT canvas.
if (!MustCleanup()) {
delete fCanvas;
delete fCanvasContainer;
}
delete [] fDNDTypeList;
}
//______________________________________________________________________________
void TRootEmbeddedCanvas::AdoptCanvas(TCanvas *c)
{
// Canvas c is adopted from this embedded canvas.
if(c == 0) return;
c->EmbedInto(fCWinId, fWidth, fHeight);
fCanvas = c;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerButton(Event_t *event)
{
// Handle mouse button events in the canvas container.
if (!fCanvas) return kTRUE;
Int_t button = event->fCode;
Int_t x = event->fX;
Int_t y = event->fY;
if (event->fType == kButtonPress) {
fButton = button;
if (button == kButton1)
fCanvas->HandleInput(kButton1Down, x, y);
if (button == kButton2)
fCanvas->HandleInput(kButton2Down, x, y);
if (button == kButton3) {
fCanvas->HandleInput(kButton3Down, x, y);
fButton = 0; // button up is consumed by TContextMenu
}
} else if (event->fType == kButtonRelease) {
if (button == kButton1)
fCanvas->HandleInput(kButton1Up, x, y);
if (button == kButton2)
fCanvas->HandleInput(kButton2Up, x, y);
if (button == kButton3)
fCanvas->HandleInput(kButton3Up, x, y);
fButton = 0;
}
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerDoubleClick(Event_t *event)
{
// Handle mouse button double click events in the canvas container.
if (!fCanvas) return kTRUE;
Int_t button = event->fCode;
Int_t x = event->fX;
Int_t y = event->fY;
if (button == kButton1)
fCanvas->HandleInput(kButton1Double, x, y);
if (button == kButton2)
fCanvas->HandleInput(kButton2Double, x, y);
if (button == kButton3)
fCanvas->HandleInput(kButton3Double, x, y);
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerConfigure(Event_t *)
{
// Handle configure (i.e. resize) event.
if (fAutoFit && fCanvas) {
fCanvas->Resize();
fCanvas->Update();
}
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerKey(Event_t *event)
{
// Handle keyboard events in the canvas container.
if (!fCanvas) return kTRUE;
if (event->fType == kGKeyPress) {
fButton = event->fCode;
UInt_t keysym;
char str[2];
gVirtualX->LookupString(event, str, sizeof(str), keysym);
if (str[0] == 3) // ctrl-c sets the interrupt flag
gROOT->SetInterrupt();
fCanvas->HandleInput(kKeyPress, str[0], keysym);
} else if (event->fType == kKeyRelease)
fButton = 0;
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerMotion(Event_t *event)
{
// Handle mouse motion event in the canvas container.
if (!fCanvas) return kTRUE;
Int_t x = event->fX;
Int_t y = event->fY;
if (fButton == 0)
fCanvas->HandleInput(kMouseMotion, x, y);
if (fButton == kButton1)
fCanvas->HandleInput(kButton1Motion, x, y);
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerExpose(Event_t *event)
{
// Handle expose events.
if (!fCanvas) return kTRUE;
if (event->fCount == 0)
fCanvas->Flush();
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerCrossing(Event_t *event)
{
// Handle enter/leave events. Only leave is activated at the moment.
if (!fCanvas) return kTRUE;
Int_t x = event->fX;
Int_t y = event->fY;
// pointer grabs create also an enter and leave event but with fCode
// either kNotifyGrab or kNotifyUngrab, don't propagate these events
if (event->fType == kLeaveNotify && event->fCode == kNotifyNormal)
fCanvas->HandleInput(kMouseLeave, x, y);
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleDNDdrop(TDNDdata *data)
{
// Handle drop events.
static Atom_t rootObj = gVirtualX->InternAtom("application/root", kFALSE);
static Atom_t uriObj = gVirtualX->InternAtom("text/uri-list", kFALSE);
if (data->fDataType == rootObj) {
TBufferFile buf(TBuffer::kRead, data->fDataLength, (void *)data->fData);
buf.SetReadMode();
TObject *obj = (TObject *)buf.ReadObjectAny(TObject::Class());
gPad->Clear();
if (obj->InheritsFrom("TGraph"))
obj->Draw("ACP");
else if (obj->IsA()->GetMethodAllAny("Draw"))
obj->Draw();
gPad->Modified();
gPad->Update();
return kTRUE;
}
else if (data->fDataType == uriObj) {
TString sfname((char *)data->fData);
if (sfname.Length() > 7) {
sfname.ReplaceAll("\r\n", "");
TUrl uri(sfname.Data());
if (sfname.EndsWith(".bmp") ||
sfname.EndsWith(".gif") ||
sfname.EndsWith(".jpg") ||
sfname.EndsWith(".png") ||
sfname.EndsWith(".tiff") ||
sfname.EndsWith(".xpm")) {
TImage *img = TImage::Open(uri.GetFile());
if (img) {
img->Draw("xxx");
img->SetEditable(kTRUE);
}
}
gPad->Modified();
gPad->Update();
}
}
return kFALSE;
}
//______________________________________________________________________________
Atom_t TRootEmbeddedCanvas::HandleDNDposition(Int_t /*x*/, Int_t /*y*/, Atom_t action,
Int_t xroot, Int_t yroot)
{
// Handle dragging position events.
Int_t px = 0, py = 0;
Window_t wtarget;
gVirtualX->TranslateCoordinates(gClient->GetDefaultRoot()->GetId(),
gVirtualX->GetWindowID(fCanvas->GetCanvasID()),
xroot, yroot, px, py, wtarget);
TPad *pad = fCanvas->Pick(px, py, 0);
if (pad) {
pad->cd();
gROOT->SetSelectedPad(pad);
}
return action;
}
//______________________________________________________________________________
Atom_t TRootEmbeddedCanvas::HandleDNDenter(Atom_t *typelist)
{
// Handle drag enter events.
static Atom_t rootObj = gVirtualX->InternAtom("application/root", kFALSE);
static Atom_t uriObj = gVirtualX->InternAtom("text/uri-list", kFALSE);
Atom_t ret = kNone;
for (int i = 0; typelist[i] != kNone; ++i) {
if (typelist[i] == rootObj)
ret = rootObj;
if (typelist[i] == uriObj)
ret = uriObj;
}
return ret;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleDNDleave()
{
// Handle drag leave events.
return kTRUE;
}
//______________________________________________________________________________
void TRootEmbeddedCanvas::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
{
// Save an embedded canvas as a C++ statement(s) on output stream out.
if (!GetCanvas()) return;
if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);
char quote ='"';
out << endl << " // embedded canvas" << endl;
out << " TRootEmbeddedCanvas *";
out << GetName() << " = new TRootEmbeddedCanvas(0" << "," << fParent->GetName()
<< "," << GetWidth() << "," << GetHeight();
if (fBackground == GetDefaultFrameBackground()) {
if (GetOptions() == (kSunkenFrame | kDoubleBorder)) {
out <<");" << endl;
} else {
out << "," << GetOptionString() <<");" << endl;
}
} else {
out << "," << GetOptionString() << ",ucolor);" << endl;
}
out << " Int_t w" << GetName() << " = " << GetName()
<< "->GetCanvasWindowId();" << endl;
static int n = 123;
TString cname = Form("c%d", n);
out << " TCanvas *";
out << cname << " = new TCanvas(";
out << quote << cname.Data() << quote << ", 10, 10, w"
<< GetName() << ");" << endl;
out << " " << GetName() << "->AdoptCanvas(" << cname
<< ");" << endl;
n++;
//Next line is a connection to TCanvas::SavePrimitives()
//GetCanvas()->SavePrimitive(out,option);
}
<commit_msg>From Bertrand: Added handling TKey objects in HandleDNDdrop.<commit_after>// @(#)root/gui:$Id$
// Author: Fons Rademakers 15/07/98
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootEmbeddedCanvas //
// //
// This class creates a TGCanvas in which a TCanvas is created. Use //
// GetCanvas() to get a pointer to the TCanvas. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TRootEmbeddedCanvas.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "Riostream.h"
#include "TStyle.h"
#include "TPluginManager.h"
#include "TVirtualGL.h"
#include "TGDNDManager.h"
#include "TBufferFile.h"
#include "TImage.h"
#include "TClass.h"
#include "TUrl.h"
//////////////////////////////////////////////////////////////////////////
// //
// TRootEmbeddedContainer //
// //
// Utility class used by TRootEmbeddedCanvas. The TRootEmbeddedContainer//
// is the frame embedded in the TGCanvas widget. The ROOT graphics goes //
// into this frame. This class is used to enable input events on this //
// graphics frame and forward the events to the TRootEmbeddedCanvas //
// handlers. //
// //
//////////////////////////////////////////////////////////////////////////
class TRootEmbeddedContainer : public TGCompositeFrame {
private:
TRootEmbeddedCanvas *fCanvas; // pointer back to embedded canvas
public:
TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id, const TGWindow *parent);
Bool_t HandleButton(Event_t *ev)
{ return fCanvas->HandleContainerButton(ev); }
Bool_t HandleDoubleClick(Event_t *ev)
{ return fCanvas->HandleContainerDoubleClick(ev); }
Bool_t HandleConfigureNotify(Event_t *ev)
{ TGFrame::HandleConfigureNotify(ev);
return fCanvas->HandleContainerConfigure(ev); }
Bool_t HandleKey(Event_t *ev)
{ return fCanvas->HandleContainerKey(ev); }
Bool_t HandleMotion(Event_t *ev)
{ return fCanvas->HandleContainerMotion(ev); }
Bool_t HandleExpose(Event_t *ev)
{ return fCanvas->HandleContainerExpose(ev); }
Bool_t HandleCrossing(Event_t *ev)
{ return fCanvas->HandleContainerCrossing(ev); }
void SetEditable(Bool_t) { }
};
//______________________________________________________________________________
TRootEmbeddedContainer::TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id,
const TGWindow *p) : TGCompositeFrame(gClient, id, p)
{
// Create a canvas container.
fCanvas = c;
gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,
kButtonPressMask | kButtonReleaseMask |
kPointerMotionMask, kNone, kNone);
AddInput(kKeyPressMask | kKeyReleaseMask | kPointerMotionMask |
kExposureMask | kStructureNotifyMask | kLeaveWindowMask);
fEditDisabled = kEditDisableGrab;
}
ClassImp(TRootEmbeddedCanvas)
//______________________________________________________________________________
TRootEmbeddedCanvas::TRootEmbeddedCanvas(const char *name, const TGWindow *p,
UInt_t w, UInt_t h, UInt_t options, ULong_t back)
: TGCanvas(p, w, h, options, back)
{
// Create an TCanvas embedded in a TGFrame. A pointer to the TCanvas can
// be obtained via the GetCanvas() member function. To embed a canvas
// derived from a TCanvas do the following:
// TRootEmbeddedCanvas *embedded = new TRootEmbeddedCanvas(0, p, w, h);
// [note name must be 0, not null string ""]
// Int_t wid = embedded->GetCanvasWindowId();
// TMyCanvas *myc = new TMyCanvas("myname", 10, 10, wid);
// embedded->AdoptCanvas(myc);
// [ the MyCanvas is adopted by the embedded canvas and will be
// destroyed by it ]
fCanvas = 0;
fButton = 0;
fAutoFit = kTRUE;
fEditDisabled = kEditDisableLayout;
fCWinId = -1;
if (gStyle->GetCanvasPreferGL()) {
//first, initialize GL (if not yet)
if (!gGLManager) {
TString x = "win32";
if (gVirtualX->InheritsFrom("TGX11"))
x = "x11";
TPluginHandler *ph = gROOT->GetPluginManager()->FindHandler("TGLManager", x);
if (ph && ph->LoadPlugin() != -1) {
if (!ph->ExecPlugin(0))
Warning("CreateCanvas",
"Cannot load GL, will use default canvas imp instead\n");
}
}
if (gGLManager) {
fCWinId = gGLManager->InitGLWindow((ULong_t)GetViewPort()->GetId());
}
}
if (fCWinId == -1)
fCWinId = gVirtualX->InitWindow((ULong_t)GetViewPort()->GetId());
Window_t win = gVirtualX->GetWindowID(fCWinId);
fCanvasContainer = new TRootEmbeddedContainer(this, win, GetViewPort());
SetContainer(fCanvasContainer);
fCanvas = new TCanvas(name ? name : Form("%s_canvas", GetName()), w, h, fCWinId);
// define DND types
fDNDTypeList = new Atom_t[3];
fDNDTypeList[0] = gVirtualX->InternAtom("application/root", kFALSE);
fDNDTypeList[1] = gVirtualX->InternAtom("text/uri-list", kFALSE);
fDNDTypeList[2] = 0;
gVirtualX->SetDNDAware(fId, fDNDTypeList);
SetDNDTarget(kTRUE);
if (!p) {
fCanvas->SetBorderMode(0);
MapSubwindows();
Resize(100, 100);
}
}
//______________________________________________________________________________
TRootEmbeddedCanvas::~TRootEmbeddedCanvas()
{
// Delete embedded ROOT canvas.
if (!MustCleanup()) {
delete fCanvas;
delete fCanvasContainer;
}
delete [] fDNDTypeList;
}
//______________________________________________________________________________
void TRootEmbeddedCanvas::AdoptCanvas(TCanvas *c)
{
// Canvas c is adopted from this embedded canvas.
if(c == 0) return;
c->EmbedInto(fCWinId, fWidth, fHeight);
fCanvas = c;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerButton(Event_t *event)
{
// Handle mouse button events in the canvas container.
if (!fCanvas) return kTRUE;
Int_t button = event->fCode;
Int_t x = event->fX;
Int_t y = event->fY;
if (event->fType == kButtonPress) {
fButton = button;
if (button == kButton1)
fCanvas->HandleInput(kButton1Down, x, y);
if (button == kButton2)
fCanvas->HandleInput(kButton2Down, x, y);
if (button == kButton3) {
fCanvas->HandleInput(kButton3Down, x, y);
fButton = 0; // button up is consumed by TContextMenu
}
} else if (event->fType == kButtonRelease) {
if (button == kButton1)
fCanvas->HandleInput(kButton1Up, x, y);
if (button == kButton2)
fCanvas->HandleInput(kButton2Up, x, y);
if (button == kButton3)
fCanvas->HandleInput(kButton3Up, x, y);
fButton = 0;
}
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerDoubleClick(Event_t *event)
{
// Handle mouse button double click events in the canvas container.
if (!fCanvas) return kTRUE;
Int_t button = event->fCode;
Int_t x = event->fX;
Int_t y = event->fY;
if (button == kButton1)
fCanvas->HandleInput(kButton1Double, x, y);
if (button == kButton2)
fCanvas->HandleInput(kButton2Double, x, y);
if (button == kButton3)
fCanvas->HandleInput(kButton3Double, x, y);
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerConfigure(Event_t *)
{
// Handle configure (i.e. resize) event.
if (fAutoFit && fCanvas) {
fCanvas->Resize();
fCanvas->Update();
}
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerKey(Event_t *event)
{
// Handle keyboard events in the canvas container.
if (!fCanvas) return kTRUE;
if (event->fType == kGKeyPress) {
fButton = event->fCode;
UInt_t keysym;
char str[2];
gVirtualX->LookupString(event, str, sizeof(str), keysym);
if (str[0] == 3) // ctrl-c sets the interrupt flag
gROOT->SetInterrupt();
fCanvas->HandleInput(kKeyPress, str[0], keysym);
} else if (event->fType == kKeyRelease)
fButton = 0;
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerMotion(Event_t *event)
{
// Handle mouse motion event in the canvas container.
if (!fCanvas) return kTRUE;
Int_t x = event->fX;
Int_t y = event->fY;
if (fButton == 0)
fCanvas->HandleInput(kMouseMotion, x, y);
if (fButton == kButton1)
fCanvas->HandleInput(kButton1Motion, x, y);
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerExpose(Event_t *event)
{
// Handle expose events.
if (!fCanvas) return kTRUE;
if (event->fCount == 0)
fCanvas->Flush();
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleContainerCrossing(Event_t *event)
{
// Handle enter/leave events. Only leave is activated at the moment.
if (!fCanvas) return kTRUE;
Int_t x = event->fX;
Int_t y = event->fY;
// pointer grabs create also an enter and leave event but with fCode
// either kNotifyGrab or kNotifyUngrab, don't propagate these events
if (event->fType == kLeaveNotify && event->fCode == kNotifyNormal)
fCanvas->HandleInput(kMouseLeave, x, y);
return kTRUE;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleDNDdrop(TDNDdata *data)
{
// Handle drop events.
static Atom_t rootObj = gVirtualX->InternAtom("application/root", kFALSE);
static Atom_t uriObj = gVirtualX->InternAtom("text/uri-list", kFALSE);
if (data->fDataType == rootObj) {
TBufferFile buf(TBuffer::kRead, data->fDataLength, (void *)data->fData);
buf.SetReadMode();
TObject *obj = (TObject *)buf.ReadObjectAny(TObject::Class());
gPad->Clear();
if (obj->InheritsFrom("TGraph"))
obj->Draw("ACP");
else if (obj->InheritsFrom("TKey")) {
TObject *object = (TObject *)gROOT->ProcessLine(Form("((TKey *)0x%lx)->ReadObj();", obj));
if (object && object->IsA()->GetMethodAllAny("Draw"))
object->Draw();
}
else if (obj->IsA()->GetMethodAllAny("Draw"))
obj->Draw();
gPad->Modified();
gPad->Update();
return kTRUE;
}
else if (data->fDataType == uriObj) {
TString sfname((char *)data->fData);
if (sfname.Length() > 7) {
sfname.ReplaceAll("\r\n", "");
TUrl uri(sfname.Data());
if (sfname.EndsWith(".bmp") ||
sfname.EndsWith(".gif") ||
sfname.EndsWith(".jpg") ||
sfname.EndsWith(".png") ||
sfname.EndsWith(".tiff") ||
sfname.EndsWith(".xpm")) {
TImage *img = TImage::Open(uri.GetFile());
if (img) {
img->Draw("xxx");
img->SetEditable(kTRUE);
}
}
gPad->Modified();
gPad->Update();
}
}
return kFALSE;
}
//______________________________________________________________________________
Atom_t TRootEmbeddedCanvas::HandleDNDposition(Int_t /*x*/, Int_t /*y*/, Atom_t action,
Int_t xroot, Int_t yroot)
{
// Handle dragging position events.
Int_t px = 0, py = 0;
Window_t wtarget;
gVirtualX->TranslateCoordinates(gClient->GetDefaultRoot()->GetId(),
gVirtualX->GetWindowID(fCanvas->GetCanvasID()),
xroot, yroot, px, py, wtarget);
TPad *pad = fCanvas->Pick(px, py, 0);
if (pad) {
pad->cd();
gROOT->SetSelectedPad(pad);
}
return action;
}
//______________________________________________________________________________
Atom_t TRootEmbeddedCanvas::HandleDNDenter(Atom_t *typelist)
{
// Handle drag enter events.
static Atom_t rootObj = gVirtualX->InternAtom("application/root", kFALSE);
static Atom_t uriObj = gVirtualX->InternAtom("text/uri-list", kFALSE);
Atom_t ret = kNone;
for (int i = 0; typelist[i] != kNone; ++i) {
if (typelist[i] == rootObj)
ret = rootObj;
if (typelist[i] == uriObj)
ret = uriObj;
}
return ret;
}
//______________________________________________________________________________
Bool_t TRootEmbeddedCanvas::HandleDNDleave()
{
// Handle drag leave events.
return kTRUE;
}
//______________________________________________________________________________
void TRootEmbeddedCanvas::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
{
// Save an embedded canvas as a C++ statement(s) on output stream out.
if (!GetCanvas()) return;
if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);
char quote ='"';
out << endl << " // embedded canvas" << endl;
out << " TRootEmbeddedCanvas *";
out << GetName() << " = new TRootEmbeddedCanvas(0" << "," << fParent->GetName()
<< "," << GetWidth() << "," << GetHeight();
if (fBackground == GetDefaultFrameBackground()) {
if (GetOptions() == (kSunkenFrame | kDoubleBorder)) {
out <<");" << endl;
} else {
out << "," << GetOptionString() <<");" << endl;
}
} else {
out << "," << GetOptionString() << ",ucolor);" << endl;
}
out << " Int_t w" << GetName() << " = " << GetName()
<< "->GetCanvasWindowId();" << endl;
static int n = 123;
TString cname = Form("c%d", n);
out << " TCanvas *";
out << cname << " = new TCanvas(";
out << quote << cname.Data() << quote << ", 10, 10, w"
<< GetName() << ");" << endl;
out << " " << GetName() << "->AdoptCanvas(" << cname
<< ");" << endl;
n++;
//Next line is a connection to TCanvas::SavePrimitives()
//GetCanvas()->SavePrimitive(out,option);
}
<|endoftext|> |
<commit_before>#include "pointLight.h"
#include "glm/gtx/string_cast.hpp"
#include "platform.h"
#include "gl/shaderProgram.h"
#include "view/view.h"
namespace Tangram {
std::string PointLight::s_classBlock;
std::string PointLight::s_typeName = "PointLight";
PointLight::PointLight(const std::string& _name, bool _dynamic) :
Light(_name, _dynamic),
m_position(0.0),
m_attenuation(0.0),
m_innerRadius(0.0),
m_outerRadius(0.0) {
m_type = LightType::point;
}
PointLight::~PointLight() {}
void PointLight::setPosition(const glm::vec3 &_pos) {
m_position.x = _pos.x;
m_position.y = _pos.y;
m_position.z = _pos.z;
m_position.w = 0.0;
}
void PointLight::setAttenuation(float _att){
m_attenuation = _att;
}
void PointLight::setRadius(float _outer){
m_innerRadius = 0.0;
m_outerRadius = _outer;
}
void PointLight::setRadius(float _inner, float _outer){
m_innerRadius = _inner;
m_outerRadius = _outer;
}
std::unique_ptr<LightUniforms> PointLight::injectOnProgram(ShaderProgram& _shader) {
injectSourceBlocks(_shader);
if (!m_dynamic) { return nullptr; }
return std::make_unique<Uniforms>(_shader, getUniformName());
}
void PointLight::setupProgram(const View& _view, LightUniforms& _uniforms) {
Light::setupProgram(_view, _uniforms);
glm::vec4 position = m_position;
if (m_origin == LightOrigin::world) {
// For world origin, format is: [longitude, latitude, meters (default) or pixels w/px units]
// Move light's world position into camera space
glm::dvec2 camSpace = _view.getMapProjection().LonLatToMeters(glm::dvec2(m_position.x, m_position.y));
position.x = camSpace.x - (_view.getPosition().x + _view.getEye().x);
position.y = camSpace.y - (_view.getPosition().y + _view.getEye().y);
position.z = position.z - _view.getEye().z;
} else if (m_origin == LightOrigin::ground) {
// Leave light's xy in camera space, but z needs to be moved relative to ground plane
position.z = position.z - _view.getPosition().z;
}
if (m_origin == LightOrigin::world || m_origin == LightOrigin::ground) {
// Light position is a vector from the camera to the light in world space;
// we can transform this vector into camera space the same way we would with normals
position = _view.getViewMatrix() * position;
}
auto& u = static_cast<Uniforms&>(_uniforms);
u.shader.setUniformf(u.position, position);
if (m_attenuation != 0.0) {
u.shader.setUniformf(u.attenuation, m_attenuation);
}
if (m_innerRadius != 0.0) {
u.shader.setUniformf(u.innerRadius, m_innerRadius);
}
if (m_outerRadius != 0.0) {
u.shader.setUniformf(u.outerRadius, m_outerRadius);
}
}
std::string PointLight::getClassBlock() {
if (s_classBlock.empty()) {
s_classBlock = stringFromFile("shaders/pointLight.glsl", PathType::internal)+"\n";
}
return s_classBlock;
}
std::string PointLight::getInstanceDefinesBlock() {
std::string defines = "";
if (m_attenuation!=0.0) {
defines += "#define TANGRAM_POINTLIGHT_ATTENUATION_EXPONENT\n";
}
if (m_innerRadius!=0.0) {
defines += "#define TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n";
}
if (m_outerRadius!=0.0) {
defines += "#define TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n";
}
return defines;
}
std::string PointLight::getInstanceAssignBlock() {
std::string block = Light::getInstanceAssignBlock();
if (!m_dynamic) {
block += ", " + glm::to_string(m_position);
if (m_attenuation!=0.0) {
block += ", " + std::to_string(m_attenuation);
}
if (m_innerRadius!=0.0) {
block += ", " + std::to_string(m_innerRadius);
}
if (m_outerRadius!=0.0) {
block += ", " + std::to_string(m_outerRadius);
}
block += ")";
}
return block;
}
const std::string& PointLight::getTypeName() {
return s_typeName;
}
}
<commit_msg>core/Fix point light ground attachment on tilted view<commit_after>#include "pointLight.h"
#include "glm/gtx/string_cast.hpp"
#include "platform.h"
#include "gl/shaderProgram.h"
#include "view/view.h"
namespace Tangram {
std::string PointLight::s_classBlock;
std::string PointLight::s_typeName = "PointLight";
PointLight::PointLight(const std::string& _name, bool _dynamic) :
Light(_name, _dynamic),
m_position(0.0),
m_attenuation(0.0),
m_innerRadius(0.0),
m_outerRadius(0.0) {
m_type = LightType::point;
}
PointLight::~PointLight() {}
void PointLight::setPosition(const glm::vec3 &_pos) {
m_position.x = _pos.x;
m_position.y = _pos.y;
m_position.z = _pos.z;
m_position.w = 0.0;
}
void PointLight::setAttenuation(float _att){
m_attenuation = _att;
}
void PointLight::setRadius(float _outer){
m_innerRadius = 0.0;
m_outerRadius = _outer;
}
void PointLight::setRadius(float _inner, float _outer){
m_innerRadius = _inner;
m_outerRadius = _outer;
}
std::unique_ptr<LightUniforms> PointLight::injectOnProgram(ShaderProgram& _shader) {
injectSourceBlocks(_shader);
if (!m_dynamic) { return nullptr; }
return std::make_unique<Uniforms>(_shader, getUniformName());
}
void PointLight::setupProgram(const View& _view, LightUniforms& _uniforms) {
Light::setupProgram(_view, _uniforms);
glm::vec4 position = m_position;
if (m_origin == LightOrigin::world) {
// For world origin, format is: [longitude, latitude, meters (default) or pixels w/px units]
// Move light's world position into camera space
glm::dvec2 camSpace = _view.getMapProjection().LonLatToMeters(glm::dvec2(m_position.x, m_position.y));
position.x = camSpace.x - (_view.getPosition().x + _view.getEye().x);
position.y = camSpace.y - (_view.getPosition().y + _view.getEye().y);
position.z = position.z - _view.getEye().z;
} else if (m_origin == LightOrigin::ground) {
// Move light position relative to the eye position in world space
position -= glm::vec4(_view.getEye(), 0.0);
}
if (m_origin == LightOrigin::world || m_origin == LightOrigin::ground) {
// Light position is a vector from the camera to the light in world space;
// we can transform this vector into camera space the same way we would with normals
position = _view.getViewMatrix() * position;
}
auto& u = static_cast<Uniforms&>(_uniforms);
u.shader.setUniformf(u.position, position);
if (m_attenuation != 0.0) {
u.shader.setUniformf(u.attenuation, m_attenuation);
}
if (m_innerRadius != 0.0) {
u.shader.setUniformf(u.innerRadius, m_innerRadius);
}
if (m_outerRadius != 0.0) {
u.shader.setUniformf(u.outerRadius, m_outerRadius);
}
}
std::string PointLight::getClassBlock() {
if (s_classBlock.empty()) {
s_classBlock = stringFromFile("shaders/pointLight.glsl", PathType::internal)+"\n";
}
return s_classBlock;
}
std::string PointLight::getInstanceDefinesBlock() {
std::string defines = "";
if (m_attenuation!=0.0) {
defines += "#define TANGRAM_POINTLIGHT_ATTENUATION_EXPONENT\n";
}
if (m_innerRadius!=0.0) {
defines += "#define TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n";
}
if (m_outerRadius!=0.0) {
defines += "#define TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n";
}
return defines;
}
std::string PointLight::getInstanceAssignBlock() {
std::string block = Light::getInstanceAssignBlock();
if (!m_dynamic) {
block += ", " + glm::to_string(m_position);
if (m_attenuation!=0.0) {
block += ", " + std::to_string(m_attenuation);
}
if (m_innerRadius!=0.0) {
block += ", " + std::to_string(m_innerRadius);
}
if (m_outerRadius!=0.0) {
block += ", " + std::to_string(m_outerRadius);
}
block += ")";
}
return block;
}
const std::string& PointLight::getTypeName() {
return s_typeName;
}
}
<|endoftext|> |
<commit_before>#include "tileManager.h"
#include "data/dataSource.h"
#include "platform.h"
#include "scene/scene.h"
#include "tile/tile.h"
#include "view/view.h"
#include "tileCache.h"
#include "glm/gtx/norm.hpp"
#include <chrono>
#include <algorithm>
#define DBG(...)
//logMsg(__VA_ARGS__)
namespace Tangram {
TileManager::TileManager()
: m_loadPending(0) {
// Instantiate workers
m_workers = std::unique_ptr<TileWorker>(new TileWorker(*this, MAX_WORKERS));
m_tileCache = std::unique_ptr<TileCache>(new TileCache(DEFAULT_CACHE_SIZE));
m_dataCallback = [this](std::shared_ptr<TileTask>&& task){
if (setTileState(*task->tile, TileState::processing)) {
m_workers->enqueue(std::move(task));
}
};
}
TileManager::~TileManager() {
if (m_workers->isRunning()) {
m_workers->stop();
}
m_tileSets.clear();
}
void TileManager::addDataSource(std::shared_ptr<DataSource>&& dataSource) {
m_tileSets.push_back({dataSource});
}
void TileManager::tileProcessed(std::shared_ptr<TileTask>&& task) {
std::lock_guard<std::mutex> lock(m_readyTileMutex);
m_readyTiles.push_back(std::move(task));
}
bool TileManager::setTileState(Tile& tile, TileState state) {
std::lock_guard<std::mutex> lock(m_tileStateMutex);
switch (tile.getState()) {
case TileState::none:
if (state == TileState::loading) {
tile.setState(state);
m_loadPending++;
return true;
}
if (state == TileState::processing) {
tile.setState(state);
return true;
}
break;
case TileState::loading:
if (state == TileState::processing) {
tile.setState(state);
m_loadPending--;
return true;
}
if (state == TileState::canceled) {
tile.setState(state);
m_loadPending--;
return true;
}
break;
case TileState::processing:
if (state == TileState::ready) {
tile.setState(state);
return true;
}
break;
case TileState::canceled:
// Ignore any state change when tile was canceled
return false;
default:
break;
}
if (state == TileState::canceled) {
tile.setState(state);
return true;
}
logMsg("Wrong state change %d -> %d<<<", tile.getState(), state);
assert(false);
return false; // ...
}
void TileManager::clearTileSets() {
for (auto& tileSet : m_tileSets) {
for (auto& tile : tileSet.tiles) {
setTileState(*tile.second, TileState::canceled);
}
tileSet.tiles.clear();
}
m_tileCache->clear();
m_loadPending = 0;
}
void TileManager::updateTileSets() {
m_tileSetChanged = false;
m_tiles.clear();
for (auto& tileSet : m_tileSets) {
updateTileSet(tileSet);
}
loadTiles();
std::sort(m_tiles.begin(), m_tiles.end(), [](auto& a, auto& b){
return a->getID() < b->getID();
});
m_tiles.erase(std::unique(m_tiles.begin(), m_tiles.end()), m_tiles.end());
}
void TileManager::updateTileSet(TileSet& tileSet) {
auto& tiles = tileSet.tiles;
std::vector<TileID> removeTiles;
if (!m_readyTiles.empty()) {
std::lock_guard<std::mutex> lock(m_readyTileMutex);
auto it = m_readyTiles.begin();
while (it != m_readyTiles.end()) {
auto& task = *it;
auto& tile = *(task->tile);
if (tileSet.source.get() == task->source) {
if (setTileState(tile, TileState::ready)) {
clearProxyTiles(tileSet, tile, removeTiles);
m_tileSetChanged = true;
}
it = m_readyTiles.erase(it);
} else {
it++;
}
}
}
const std::set<TileID>& visibleTiles = m_view->getVisibleTiles();
glm::dvec2 viewCenter(m_view->getPosition().x, -m_view->getPosition().y);
if (m_view->changedOnLastUpdate() || m_tileSetChanged) {
// Loop over visibleTiles and add any needed tiles to tileSet
auto setTilesIter = tiles.begin();
auto visTilesIter = visibleTiles.begin();
while (visTilesIter != visibleTiles.end()) {
auto& visTileId = *visTilesIter;
auto& curTileId = setTilesIter == tiles.end() ? NOT_A_TILE : setTilesIter->first;
if (visTileId == curTileId) {
auto& tile = setTilesIter->second;
if (tile->hasState(TileState::none)) {
enqueueLoadTask(tileSet, visTileId, viewCenter);
} else if (tile->isReady()) {
m_tiles.push_back(tile);
}
tile->setVisible(true);
// tiles in both sets match
++setTilesIter;
++visTilesIter;
} else if (curTileId == NOT_A_TILE || visTileId < curTileId) {
// tileSet is missing an element present in visibleTiles
if (!addTile(tileSet, visTileId)) {
enqueueLoadTask(tileSet, visTileId, viewCenter);
}
++visTilesIter;
} else {
// visibleTiles is missing an element present in tileSet
auto& tile = setTilesIter->second;
tile->setVisible(false);
if (tile->getProxyCounter() <= 0) {
removeTiles.push_back(tile->getID());
} else if (tile->isReady()) {
m_tiles.push_back(tile);
}
++setTilesIter;
}
}
while (setTilesIter != tiles.end()) {
// more visibleTiles missing an element present in tileSet
auto& tile = setTilesIter->second;
tile->setVisible(false);
if (tile->getProxyCounter() <= 0) {
removeTiles.push_back(tile->getID());
} else if (tile->isReady()) {
m_tiles.push_back(tile);
}
++setTilesIter;
}
}
{
while (!removeTiles.empty()) {
auto tileIter = tiles.find(removeTiles.back());
removeTiles.pop_back();
if (tileIter != tiles.end()) {
if (tileIter->second->getProxyCounter() <= 0) {
removeTile(tileSet, tileIter, removeTiles);
}
}
}
}
// Update tile distance to map center for load priority
{
for (auto& entry : tiles) {
auto& tile = entry.second;
auto tileCenter = m_view->getMapProjection().TileCenter(tile->getID());
tile->setPriority(glm::length2(tileCenter - viewCenter));
}
}
}
void TileManager::enqueueLoadTask(const TileSet& tileSet, const TileID& tileID,
const glm::dvec2& viewCenter) {
// Keep the items sorted by distance
auto tileCenter = m_view->getMapProjection().TileCenter(tileID);
double distance = glm::length2(tileCenter - viewCenter);
auto iter = m_loadTasks.begin();
while (iter != m_loadTasks.end()) {
if (std::get<0>(*iter) > distance) {
break;
}
++iter;
}
if (iter == m_loadTasks.end()) {
m_loadTasks.push_back(std::make_tuple(distance, &tileSet, &tileID));
} else {
m_loadTasks.insert(iter, std::make_tuple(distance, &tileSet, &tileID));
}
}
void TileManager::loadTiles() {
for (auto& item : m_loadTasks) {
auto& id = *std::get<2>(item);
auto& tileSet = *std::get<1>(item);
auto it = tileSet.tiles.find(id);
if (it == tileSet.tiles.end()) {
DBG("[%d, %d, %d] Eeek\n", id.z, id.x, id.y);
continue;
}
auto& tile = it->second;
auto& source = tileSet.source;
auto task = std::make_shared<TileTask>(tile, source.get());
if (source->getTileData(task)) {
m_dataCallback(std::move(task));
} else if (m_loadPending < MAX_DOWNLOADS) {
setTileState(*tile, TileState::loading);
if (!source->loadTileData(std::move(task), m_dataCallback)) {
logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n",
id.z, id.x, id.y);
m_loadPending--;
}
}
}
//DBG("all:%d loading:%d pending:%d cached:%d cache: %fMB\n",
// m_tileSet.size(), m_loadTasks.size(),
// m_loadPending, m_tileCache->size(),
// (double(m_tileCache->getMemoryUsage()) / (1024 * 1024)));
m_loadTasks.clear();
}
bool TileManager::addTile(TileSet& tileSet, const TileID& _tileID) {
auto tile = m_tileCache->get(*tileSet.source.get(), _tileID);
bool fromCache = false;
if (tile) {
m_tiles.push_back(tile);
fromCache = true;
} else {
tile = std::shared_ptr<Tile>(new Tile(_tileID, m_view->getMapProjection()));
//Add Proxy if corresponding proxy MapTile ready
updateProxyTiles(tileSet, *tile);
}
tile->setVisible(true);
tileSet.tiles.emplace(_tileID, tile);
return fromCache;
}
void TileManager::removeTile(TileSet& tileSet, std::map<TileID,
std::shared_ptr<Tile>>::iterator& _tileIter,
std::vector<TileID>& _removes) {
const TileID& id = _tileIter->first;
auto& tile = _tileIter->second;
if (tile->hasState(TileState::loading) &&
setTileState(*tile, TileState::canceled)) {
// 1. Remove from Datasource. Make sure to cancel the network request
// associated with this tile.
tileSet.source->cancelLoadingTile(id);
}
clearProxyTiles(tileSet, *tile, _removes);
if (tile->hasState(TileState::ready)) {
// Add to cache
m_tileCache->put(*tileSet.source.get(), tile);
}
// Remove tile from set
_tileIter = tileSet.tiles.erase(_tileIter);
}
void TileManager::updateProxyTiles(TileSet& tileSet, Tile& _tile) {
const TileID& _tileID = _tile.getID();
auto& tiles = tileSet.tiles;
// Get current parent
auto parentID = _tileID.getParent();
{
const auto& it = tiles.find(parentID);
if (it != tiles.end()) {
auto& parent = it->second;
if (_tile.setProxy(Tile::parent)) {
parent->incProxyCounter();
DBG("USE PARENT PROXY\n");
if (parent->isReady()) {
m_tiles.push_back(parent);
}
}
return;
}
}
// Get parent proxy from cache
{
auto parent = m_tileCache->get(*tileSet.source.get(), parentID);
if (parent) {
_tile.setProxy(Tile::parent);
parent->incProxyCounter();
m_tiles.push_back(parent);
tiles.emplace(parentID, std::move(parent));
return;
}
}
if (m_view->s_maxZoom > _tileID.z) {
for (int i = 0; i < 4; i++) {
auto childID = _tileID.getChild(i);
const auto& it = tiles.find(childID);
if (it != tiles.end()) {
auto& child = it->second;
if (_tile.setProxy(static_cast<Tile::ProxyID>(1 << i))) {
child->incProxyCounter();
if (child->isReady()) {
m_tiles.push_back(child);
}
DBG("USE CHILD PROXY\n");
}
} else {
auto child = m_tileCache->get(*tileSet.source.get(), childID);
if (child) {
_tile.setProxy(static_cast<Tile::ProxyID>(1 << i));
child->incProxyCounter();
m_tiles.push_back(child);
tiles.emplace(childID, std::move(child));
}
}
}
}
}
void TileManager::clearProxyTiles(TileSet& tileSet, Tile& _tile, std::vector<TileID>& _removes) {
const TileID& _tileID = _tile.getID();
auto& tiles = tileSet.tiles;
// Check if parent proxy is present
if (_tile.unsetProxy(Tile::parent)) {
TileID parentID(_tileID.getParent());
auto it = tiles.find(parentID);
if (it != tiles.end()) {
auto& parent = it->second;
parent->decProxyCounter();
if (parent->getProxyCounter() == 0 && !parent->isVisible()) {
_removes.push_back(parentID);
}
}
}
// Check if child proxies are present
for (int i = 0; i < 4; i++) {
if (_tile.unsetProxy(static_cast<Tile::ProxyID>(1 << i))) {
TileID childID(_tileID.getChild(i));
auto it = tiles.find(childID);
if (it != tiles.end()) {
auto& child = it->second;
child->decProxyCounter();
if (child->getProxyCounter() == 0 && !child->isVisible()) {
_removes.push_back(childID);
}
}
}
}
}
void TileManager::setCacheSize(size_t _cacheSize) {
m_tileCache->limitCacheSize(_cacheSize);
}
}
<commit_msg>use std::upper_bound<commit_after>#include "tileManager.h"
#include "data/dataSource.h"
#include "platform.h"
#include "scene/scene.h"
#include "tile/tile.h"
#include "view/view.h"
#include "tileCache.h"
#include "glm/gtx/norm.hpp"
#include <chrono>
#include <algorithm>
#define DBG(...)
//logMsg(__VA_ARGS__)
namespace Tangram {
TileManager::TileManager()
: m_loadPending(0) {
// Instantiate workers
m_workers = std::unique_ptr<TileWorker>(new TileWorker(*this, MAX_WORKERS));
m_tileCache = std::unique_ptr<TileCache>(new TileCache(DEFAULT_CACHE_SIZE));
m_dataCallback = [this](std::shared_ptr<TileTask>&& task){
if (setTileState(*task->tile, TileState::processing)) {
m_workers->enqueue(std::move(task));
}
};
}
TileManager::~TileManager() {
if (m_workers->isRunning()) {
m_workers->stop();
}
m_tileSets.clear();
}
void TileManager::addDataSource(std::shared_ptr<DataSource>&& dataSource) {
m_tileSets.push_back({dataSource});
}
void TileManager::tileProcessed(std::shared_ptr<TileTask>&& task) {
std::lock_guard<std::mutex> lock(m_readyTileMutex);
m_readyTiles.push_back(std::move(task));
}
bool TileManager::setTileState(Tile& tile, TileState state) {
std::lock_guard<std::mutex> lock(m_tileStateMutex);
switch (tile.getState()) {
case TileState::none:
if (state == TileState::loading) {
tile.setState(state);
m_loadPending++;
return true;
}
if (state == TileState::processing) {
tile.setState(state);
return true;
}
break;
case TileState::loading:
if (state == TileState::processing) {
tile.setState(state);
m_loadPending--;
return true;
}
if (state == TileState::canceled) {
tile.setState(state);
m_loadPending--;
return true;
}
break;
case TileState::processing:
if (state == TileState::ready) {
tile.setState(state);
return true;
}
break;
case TileState::canceled:
// Ignore any state change when tile was canceled
return false;
default:
break;
}
if (state == TileState::canceled) {
tile.setState(state);
return true;
}
logMsg("Wrong state change %d -> %d<<<", tile.getState(), state);
assert(false);
return false; // ...
}
void TileManager::clearTileSets() {
for (auto& tileSet : m_tileSets) {
for (auto& tile : tileSet.tiles) {
setTileState(*tile.second, TileState::canceled);
}
tileSet.tiles.clear();
}
m_tileCache->clear();
m_loadPending = 0;
}
void TileManager::updateTileSets() {
m_tileSetChanged = false;
m_tiles.clear();
for (auto& tileSet : m_tileSets) {
updateTileSet(tileSet);
}
loadTiles();
std::sort(m_tiles.begin(), m_tiles.end(), [](auto& a, auto& b){
return a->getID() < b->getID();
});
m_tiles.erase(std::unique(m_tiles.begin(), m_tiles.end()), m_tiles.end());
}
void TileManager::updateTileSet(TileSet& tileSet) {
auto& tiles = tileSet.tiles;
std::vector<TileID> removeTiles;
if (!m_readyTiles.empty()) {
std::lock_guard<std::mutex> lock(m_readyTileMutex);
auto it = m_readyTiles.begin();
while (it != m_readyTiles.end()) {
auto& task = *it;
auto& tile = *(task->tile);
if (tileSet.source.get() == task->source) {
if (setTileState(tile, TileState::ready)) {
clearProxyTiles(tileSet, tile, removeTiles);
m_tileSetChanged = true;
}
it = m_readyTiles.erase(it);
} else {
it++;
}
}
}
const std::set<TileID>& visibleTiles = m_view->getVisibleTiles();
glm::dvec2 viewCenter(m_view->getPosition().x, -m_view->getPosition().y);
if (m_view->changedOnLastUpdate() || m_tileSetChanged) {
// Loop over visibleTiles and add any needed tiles to tileSet
auto setTilesIter = tiles.begin();
auto visTilesIter = visibleTiles.begin();
while (visTilesIter != visibleTiles.end()) {
auto& visTileId = *visTilesIter;
auto& curTileId = setTilesIter == tiles.end() ? NOT_A_TILE : setTilesIter->first;
if (visTileId == curTileId) {
auto& tile = setTilesIter->second;
if (tile->hasState(TileState::none)) {
enqueueLoadTask(tileSet, visTileId, viewCenter);
} else if (tile->isReady()) {
m_tiles.push_back(tile);
}
tile->setVisible(true);
// tiles in both sets match
++setTilesIter;
++visTilesIter;
} else if (curTileId == NOT_A_TILE || visTileId < curTileId) {
// tileSet is missing an element present in visibleTiles
if (!addTile(tileSet, visTileId)) {
enqueueLoadTask(tileSet, visTileId, viewCenter);
}
++visTilesIter;
} else {
// visibleTiles is missing an element present in tileSet
auto& tile = setTilesIter->second;
tile->setVisible(false);
if (tile->getProxyCounter() <= 0) {
removeTiles.push_back(tile->getID());
} else if (tile->isReady()) {
m_tiles.push_back(tile);
}
++setTilesIter;
}
}
while (setTilesIter != tiles.end()) {
// more visibleTiles missing an element present in tileSet
auto& tile = setTilesIter->second;
tile->setVisible(false);
if (tile->getProxyCounter() <= 0) {
removeTiles.push_back(tile->getID());
} else if (tile->isReady()) {
m_tiles.push_back(tile);
}
++setTilesIter;
}
}
{
while (!removeTiles.empty()) {
auto tileIter = tiles.find(removeTiles.back());
removeTiles.pop_back();
if (tileIter != tiles.end()) {
if (tileIter->second->getProxyCounter() <= 0) {
removeTile(tileSet, tileIter, removeTiles);
}
}
}
}
// Update tile distance to map center for load priority
{
for (auto& entry : tiles) {
auto& tile = entry.second;
auto tileCenter = m_view->getMapProjection().TileCenter(tile->getID());
tile->setPriority(glm::length2(tileCenter - viewCenter));
}
}
}
void TileManager::enqueueLoadTask(const TileSet& tileSet, const TileID& tileID,
const glm::dvec2& viewCenter) {
// Keep the items sorted by distance
auto tileCenter = m_view->getMapProjection().TileCenter(tileID);
double distance = glm::length2(tileCenter - viewCenter);
auto it = std::upper_bound(m_loadTasks.begin(), m_loadTasks.end(), distance,
[](auto& distance, auto& other){
return distance < std::get<0>(other);
});
m_loadTasks.insert(it, std::make_tuple(distance, &tileSet, &tileID));
}
void TileManager::loadTiles() {
for (auto& item : m_loadTasks) {
auto& id = *std::get<2>(item);
auto& tileSet = *std::get<1>(item);
auto it = tileSet.tiles.find(id);
if (it == tileSet.tiles.end()) {
DBG("[%d, %d, %d] Eeek\n", id.z, id.x, id.y);
continue;
}
auto& tile = it->second;
auto& source = tileSet.source;
auto task = std::make_shared<TileTask>(tile, source.get());
if (source->getTileData(task)) {
m_dataCallback(std::move(task));
} else if (m_loadPending < MAX_DOWNLOADS) {
setTileState(*tile, TileState::loading);
if (!source->loadTileData(std::move(task), m_dataCallback)) {
logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n",
id.z, id.x, id.y);
m_loadPending--;
}
}
}
//DBG("all:%d loading:%d pending:%d cached:%d cache: %fMB\n",
// m_tileSet.size(), m_loadTasks.size(),
// m_loadPending, m_tileCache->size(),
// (double(m_tileCache->getMemoryUsage()) / (1024 * 1024)));
m_loadTasks.clear();
}
bool TileManager::addTile(TileSet& tileSet, const TileID& _tileID) {
auto tile = m_tileCache->get(*tileSet.source.get(), _tileID);
bool fromCache = false;
if (tile) {
m_tiles.push_back(tile);
fromCache = true;
} else {
tile = std::shared_ptr<Tile>(new Tile(_tileID, m_view->getMapProjection()));
//Add Proxy if corresponding proxy MapTile ready
updateProxyTiles(tileSet, *tile);
}
tile->setVisible(true);
tileSet.tiles.emplace(_tileID, tile);
return fromCache;
}
void TileManager::removeTile(TileSet& tileSet, std::map<TileID,
std::shared_ptr<Tile>>::iterator& _tileIter,
std::vector<TileID>& _removes) {
const TileID& id = _tileIter->first;
auto& tile = _tileIter->second;
if (tile->hasState(TileState::loading) &&
setTileState(*tile, TileState::canceled)) {
// 1. Remove from Datasource. Make sure to cancel the network request
// associated with this tile.
tileSet.source->cancelLoadingTile(id);
}
clearProxyTiles(tileSet, *tile, _removes);
if (tile->hasState(TileState::ready)) {
// Add to cache
m_tileCache->put(*tileSet.source.get(), tile);
}
// Remove tile from set
_tileIter = tileSet.tiles.erase(_tileIter);
}
void TileManager::updateProxyTiles(TileSet& tileSet, Tile& _tile) {
const TileID& _tileID = _tile.getID();
auto& tiles = tileSet.tiles;
// Get current parent
auto parentID = _tileID.getParent();
{
const auto& it = tiles.find(parentID);
if (it != tiles.end()) {
auto& parent = it->second;
if (_tile.setProxy(Tile::parent)) {
parent->incProxyCounter();
DBG("USE PARENT PROXY\n");
if (parent->isReady()) {
m_tiles.push_back(parent);
}
}
return;
}
}
// Get parent proxy from cache
{
auto parent = m_tileCache->get(*tileSet.source.get(), parentID);
if (parent) {
_tile.setProxy(Tile::parent);
parent->incProxyCounter();
m_tiles.push_back(parent);
tiles.emplace(parentID, std::move(parent));
return;
}
}
if (m_view->s_maxZoom > _tileID.z) {
for (int i = 0; i < 4; i++) {
auto childID = _tileID.getChild(i);
const auto& it = tiles.find(childID);
if (it != tiles.end()) {
auto& child = it->second;
if (_tile.setProxy(static_cast<Tile::ProxyID>(1 << i))) {
child->incProxyCounter();
if (child->isReady()) {
m_tiles.push_back(child);
}
DBG("USE CHILD PROXY\n");
}
} else {
auto child = m_tileCache->get(*tileSet.source.get(), childID);
if (child) {
_tile.setProxy(static_cast<Tile::ProxyID>(1 << i));
child->incProxyCounter();
m_tiles.push_back(child);
tiles.emplace(childID, std::move(child));
}
}
}
}
}
void TileManager::clearProxyTiles(TileSet& tileSet, Tile& _tile, std::vector<TileID>& _removes) {
const TileID& _tileID = _tile.getID();
auto& tiles = tileSet.tiles;
// Check if parent proxy is present
if (_tile.unsetProxy(Tile::parent)) {
TileID parentID(_tileID.getParent());
auto it = tiles.find(parentID);
if (it != tiles.end()) {
auto& parent = it->second;
parent->decProxyCounter();
if (parent->getProxyCounter() == 0 && !parent->isVisible()) {
_removes.push_back(parentID);
}
}
}
// Check if child proxies are present
for (int i = 0; i < 4; i++) {
if (_tile.unsetProxy(static_cast<Tile::ProxyID>(1 << i))) {
TileID childID(_tileID.getChild(i));
auto it = tiles.find(childID);
if (it != tiles.end()) {
auto& child = it->second;
child->decProxyCounter();
if (child->getProxyCounter() == 0 && !child->isVisible()) {
_removes.push_back(childID);
}
}
}
}
}
void TileManager::setCacheSize(size_t _cacheSize) {
m_tileCache->limitCacheSize(_cacheSize);
}
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.1 1999/11/09 01:02:14 twl
* Initial revision
*
* Revision 1.3 1999/11/08 20:42:25 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <util/XMLString.hpp>
#include <util/URL.hpp>
#include <internal/URLInputSource.hpp>
#include <internal/XMLScanner.hpp>
#include <validators/DTD/DTDValidator.hpp>
#include "ParserTest.hpp"
// ---------------------------------------------------------------------------
// Global data
//
// errStrm
// outStrm
// The streams we use to output our test data and error info. These are
// simple classes used just for XML4C2 samples and debug. They are not
// sufficient for real applications, nor are they supported for
// production code use. They merely provide a simple and portable means
// to output the Unicode data from the parser on the local host.
// ---------------------------------------------------------------------------
XMLStdErr errStrm;
XMLStdOut outStrm;
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char** argV)
{
// Init the XML platform
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
errStrm << "Error during platform init! Message:\n"
<< toCatch.getMessage() << EndLn;
return 1;
}
//
// Create our test parser object. This guy implements the internal event
// APIs and is plugged into the scanner.
//
TestParser parserTest;
// Figure out the parameters
bool doValidation = false;
bool doNamespaces = false;
bool keepGoing = false;
XMLCh* urlPath = 0;
for (int index = 1; index < argC; index++)
{
if (!XMLString::compareIString(argV[index], "/Debug"))
parserTest.setOutputType(OutputType_Debug);
else if (!XMLString::compareIString(argV[index], "/Validate"))
doValidation = true;
else if (!XMLString::compareIString(argV[index], "/Namespaces"))
{
doNamespaces = true;
parserTest.setDoNamespaces(true);
}
else if (!XMLString::compareIString(argV[index], "/XML"))
parserTest.setOutputType(OutputType_XML);
else if (!XMLString::compareIString(argV[index], "/IntDTD"))
parserTest.setShowIntDTD(true);
else if (!XMLString::compareIString(argV[index], "/ShowWarnings"))
parserTest.setShowWarnings(true);
else if (!XMLString::compareIString(argV[index], "/ShowErrLoc"))
parserTest.setShowErrLoc(true);
else if (!XMLString::compareIString(argV[index], "/JCCanon"))
parserTest.setOutputType(OutputType_JCCanon);
else if (!XMLString::compareIString(argV[index], "/SunCanon"))
parserTest.setOutputType(OutputType_SunCanon);
else if (!XMLString::compareIString(argV[index], "/KeepGoing"))
keepGoing = true;
else if (!XMLString::compareNIString(argV[index], "/URL=", 5))
urlPath = XMLString::transcode(&argV[index][5]);
else
errStrm << "Unknown parameter: " << argV[index] << EndLn;
}
// We have to have a URL to work on
if (!urlPath)
{
errStrm << "A URL must be provided, /URL=xxxx" << EndLn;
return 1;
}
//
// Create a validator of the correct type so that we can install it
// on the scanner.
//
// <TBD> Later, when Schema validators exist, we'll have a parameter
// to select one or the other
//
XMLValidator* validator = 0;
DTDValidator* dtdVal = new DTDValidator(&parserTest);
dtdVal->setDocTypeHandler(&parserTest);
validator = dtdVal;
// And now create the scanner and give it all the handlers
XMLScanner scanner
(
&parserTest
, 0
, &parserTest
, validator
);
// Set the scanner flags that we were told to
scanner.setDoValidation(doValidation);
scanner.setDoNamespaces(doNamespaces);
scanner.setExitOnFirstFatal(!keepGoing);
// Tell the parser about the scanner
parserTest.setScanner(&scanner);
try
{
URLInputSource src(urlPath);
scanner.scanDocument(src);
}
catch(const XMLException& toCatch)
{
outStrm << "Exception during scan:\n "
<< toCatch.getMessage()
<< EndLn;
}
return 0;
}
<commit_msg>Changes for the new URL and InputSource changes.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.2 2000/01/12 00:29:49 roddey
* Changes for the new URL and InputSource changes.
*
* Revision 1.1.1.1 1999/11/09 01:02:14 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:42:25 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <util/XMLString.hpp>
#include <util/URL.hpp>
#include <internal/XMLScanner.hpp>
#include <validators/DTD/DTDValidator.hpp>
#include "ParserTest.hpp"
// ---------------------------------------------------------------------------
// Global data
//
// errStrm
// outStrm
// The streams we use to output our test data and error info. These are
// simple classes used just for XML4C2 samples and debug. They are not
// sufficient for real applications, nor are they supported for
// production code use. They merely provide a simple and portable means
// to output the Unicode data from the parser on the local host.
// ---------------------------------------------------------------------------
XMLStdErr errStrm;
XMLStdOut outStrm;
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char** argV)
{
// Init the XML platform
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
errStrm << "Error during platform init! Message:\n"
<< toCatch.getMessage() << EndLn;
return 1;
}
//
// Create our test parser object. This guy implements the internal event
// APIs and is plugged into the scanner.
//
TestParser parserTest;
// Figure out the parameters
bool doValidation = false;
bool doNamespaces = false;
bool keepGoing = false;
XMLCh* urlPath = 0;
for (int index = 1; index < argC; index++)
{
if (!XMLString::compareIString(argV[index], "/Debug"))
parserTest.setOutputType(OutputType_Debug);
else if (!XMLString::compareIString(argV[index], "/Validate"))
doValidation = true;
else if (!XMLString::compareIString(argV[index], "/Namespaces"))
{
doNamespaces = true;
parserTest.setDoNamespaces(true);
}
else if (!XMLString::compareIString(argV[index], "/XML"))
parserTest.setOutputType(OutputType_XML);
else if (!XMLString::compareIString(argV[index], "/IntDTD"))
parserTest.setShowIntDTD(true);
else if (!XMLString::compareIString(argV[index], "/ShowWarnings"))
parserTest.setShowWarnings(true);
else if (!XMLString::compareIString(argV[index], "/ShowErrLoc"))
parserTest.setShowErrLoc(true);
else if (!XMLString::compareIString(argV[index], "/JCCanon"))
parserTest.setOutputType(OutputType_JCCanon);
else if (!XMLString::compareIString(argV[index], "/SunCanon"))
parserTest.setOutputType(OutputType_SunCanon);
else if (!XMLString::compareIString(argV[index], "/KeepGoing"))
keepGoing = true;
else if (!XMLString::compareNIString(argV[index], "/URL=", 5))
urlPath = XMLString::transcode(&argV[index][5]);
else
errStrm << "Unknown parameter: " << argV[index] << EndLn;
}
// We have to have a URL to work on
if (!urlPath)
{
errStrm << "A URL must be provided, /URL=xxxx" << EndLn;
return 1;
}
//
// Create a validator of the correct type so that we can install it
// on the scanner.
//
// <TBD> Later, when Schema validators exist, we'll have a parameter
// to select one or the other
//
XMLValidator* validator = 0;
DTDValidator* dtdVal = new DTDValidator(&parserTest);
dtdVal->setDocTypeHandler(&parserTest);
validator = dtdVal;
// And now create the scanner and give it all the handlers
XMLScanner scanner
(
&parserTest
, 0
, &parserTest
, validator
);
// Set the scanner flags that we were told to
scanner.setDoValidation(doValidation);
scanner.setDoNamespaces(doNamespaces);
scanner.setExitOnFirstFatal(!keepGoing);
// Tell the parser about the scanner
parserTest.setScanner(&scanner);
try
{
scanner.scanDocument(urlPath);
}
catch(const XMLException& toCatch)
{
outStrm << "Exception during scan:\n "
<< toCatch.getMessage()
<< EndLn;
}
return 0;
}
<|endoftext|> |
<commit_before>/*=====================================================================
PIXHAWK Micro Air Vehicle Flying Robotics Toolkit
(c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch>
This file is part of the PIXHAWK project
PIXHAWK is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Waypoint list widget
*
* @author Lorenz Meier <[email protected]>
* @author Benjamin Knecht <[email protected]>
* @author Petri Tanskanen <[email protected]>
*
*/
#include "WaypointList.h"
#include "ui_WaypointList.h"
#include <UASInterface.h>
#include <UASManager.h>
#include <QDebug>
#include <QFileDialog>
WaypointList::WaypointList(QWidget *parent, UASInterface* uas) :
QWidget(parent),
uas(NULL),
m_ui(new Ui::WaypointList)
{
m_ui->setupUi(this);
listLayout = new QVBoxLayout(m_ui->listWidget);
listLayout->setSpacing(6);
listLayout->setMargin(0);
listLayout->setAlignment(Qt::AlignTop);
m_ui->listWidget->setLayout(listLayout);
wpViews = QMap<Waypoint*, WaypointView*>();
this->uas = NULL;
// ADD WAYPOINT
// Connect add action, set right button icon and connect action to this class
connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered()));
connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(add()));
// SEND WAYPOINTS
connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit()));
// REQUEST WAYPOINTS
connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read()));
// SAVE/LOAD WAYPOINTS
connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints()));
connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints()));
connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*)));
// STATUS LABEL
updateStatusLabel("");
// SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED
setUAS(uas);
}
WaypointList::~WaypointList()
{
delete m_ui;
}
void WaypointList::updateStatusLabel(const QString &string)
{
m_ui->statusLabel->setText(string);
}
void WaypointList::setUAS(UASInterface* uas)
{
if (this->uas == NULL && uas != NULL)
{
this->uas = uas;
connect(&uas->getWaypointManager(), SIGNAL(updateStatusString(const QString &)), this, SLOT(updateStatusLabel(const QString &)));
connect(&uas->getWaypointManager(), SIGNAL(waypointUpdated(int,quint16,double,double,double,double,bool,bool,double,int)), this, SLOT(setWaypoint(int,quint16,double,double,double,double,bool,bool,double,int)));
connect(&uas->getWaypointManager(), SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
connect(this, SIGNAL(sendWaypoints(const QVector<Waypoint*> &)), &uas->getWaypointManager(), SLOT(sendWaypoints(const QVector<Waypoint*> &)));
connect(this, SIGNAL(requestWaypoints()), &uas->getWaypointManager(), SLOT(requestWaypoints()));
connect(this, SIGNAL(clearWaypointList()), &uas->getWaypointManager(), SLOT(clearWaypointList()));
}
}
void WaypointList::setWaypoint(int uasId, quint16 id, double x, double y, double z, double yaw, bool autocontinue, bool current, double orbit, int holdTime)
{
if (uasId == this->uas->getUASID())
{
Waypoint* wp = new Waypoint(id, x, y, z, yaw, autocontinue, current, orbit, holdTime);
addWaypoint(wp);
}
}
void WaypointList::waypointReached(UASInterface* uas, quint16 waypointId)
{
Q_UNUSED(uas);
qDebug() << "Waypoint reached: " << waypointId;
updateStatusLabel(QString("Waypoint %1 reached.").arg(waypointId));
}
void WaypointList::currentWaypointChanged(quint16 seq)
{
if (seq < waypoints.size())
{
for(int i = 0; i < waypoints.size(); i++)
{
WaypointView* widget = wpViews.find(waypoints[i]).value();
if (waypoints[i]->getId() == seq)
{
waypoints[i]->setCurrent(true);
widget->setCurrent(true);
}
else
{
waypoints[i]->setCurrent(false);
widget->setCurrent(false);
}
}
redrawList();
}
}
void WaypointList::read()
{
while(waypoints.size()>0)
{
removeWaypoint(waypoints[0]);
}
emit requestWaypoints();
}
void WaypointList::transmit()
{
emit sendWaypoints(waypoints);
//emit requestWaypoints(); FIXME
}
void WaypointList::add()
{
// Only add waypoints if UAS is present
if (uas)
{
if (waypoints.size() > 0)
{
Waypoint *last = waypoints.at(waypoints.size()-1);
addWaypoint(new Waypoint(waypoints.size(), last->getX(), last->getY(), last->getZ(), last->getYaw(), last->getAutoContinue(), last->getCurrent(), last->getOrbit(), last->getHoldTime()));
}
else
{
addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.8, 0.0, true, true, 0.1, 1000));
}
}
}
void WaypointList::addWaypoint(Waypoint* wp)
{
waypoints.push_back(wp);
if (!wpViews.contains(wp))
{
WaypointView* wpview = new WaypointView(wp, this);
wpViews.insert(wp, wpview);
listLayout->addWidget(wpViews.value(wp));
connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*)));
connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*)));
connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*)));
connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
}
}
void WaypointList::redrawList()
{
// Clear list layout
if (!wpViews.empty())
{
QMapIterator<Waypoint*,WaypointView*> viewIt(wpViews);
viewIt.toFront();
while(viewIt.hasNext())
{
viewIt.next();
listLayout->removeWidget(viewIt.value());
}
// Re-add waypoints
for(int i = 0; i < waypoints.size(); i++)
{
listLayout->addWidget(wpViews.value(waypoints[i]));
}
}
}
void WaypointList::moveUp(Waypoint* wp)
{
int id = wp->getId();
if (waypoints.size() > 1 && waypoints.size() > id)
{
Waypoint* temp = waypoints[id];
if (id > 0)
{
waypoints[id] = waypoints[id-1];
waypoints[id-1] = temp;
waypoints[id-1]->setId(id-1);
waypoints[id]->setId(id);
}
else
{
waypoints[id] = waypoints[waypoints.size()-1];
waypoints[waypoints.size()-1] = temp;
waypoints[waypoints.size()-1]->setId(waypoints.size()-1);
waypoints[id]->setId(id);
}
redrawList();
}
}
void WaypointList::moveDown(Waypoint* wp)
{
int id = wp->getId();
if (waypoints.size() > 1 && waypoints.size() > id)
{
Waypoint* temp = waypoints[id];
if (id != waypoints.size()-1)
{
waypoints[id] = waypoints[id+1];
waypoints[id+1] = temp;
waypoints[id+1]->setId(id+1);
waypoints[id]->setId(id);
}
else
{
waypoints[id] = waypoints[0];
waypoints[0] = temp;
waypoints[0]->setId(0);
waypoints[id]->setId(id);
}
redrawList();
}
}
void WaypointList::removeWaypoint(Waypoint* wp)
{
// Delete from list
if (wp != NULL)
{
waypoints.remove(wp->getId());
for(int i = wp->getId(); i < waypoints.size(); i++)
{
waypoints[i]->setId(i);
}
// Remove from view
WaypointView* widget = wpViews.find(wp).value();
wpViews.remove(wp);
widget->hide();
listLayout->removeWidget(widget);
delete wp;
}
}
void WaypointList::changeEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::LanguageChange:
m_ui->retranslateUi(this);
break;
default:
break;
}
}
void WaypointList::saveWaypoints()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)"));
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream in(&file);
for (int i = 0; i < waypoints.size(); i++)
{
Waypoint* wp = waypoints[i];
in << "\t" << wp->getId() << "\t" << wp->getX() << "\t" << wp->getY() << "\t" << wp->getZ() << "\t" << wp->getYaw() << "\t" << wp->getAutoContinue() << "\t" << wp->getCurrent() << "\t" << wp->getOrbit() << "\t" << wp->getHoldTime() << "\n";
in.flush();
}
file.close();
}
void WaypointList::loadWaypoints()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)"));
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while(waypoints.size()>0)
{
removeWaypoint(waypoints[0]);
}
QTextStream in(&file);
while (!in.atEnd())
{
QStringList wpParams = in.readLine().split("\t");
if (wpParams.size() == 10)
addWaypoint(new Waypoint(wpParams[1].toInt(), wpParams[2].toDouble(), wpParams[3].toDouble(), wpParams[4].toDouble(), wpParams[5].toDouble(), (wpParams[6].toInt() == 1 ? true : false), (wpParams[7].toInt() == 1 ? true : false), wpParams[8].toDouble(), wpParams[9].toInt()));
}
file.close();
}
<commit_msg>fixed waypoint interface<commit_after>/*=====================================================================
PIXHAWK Micro Air Vehicle Flying Robotics Toolkit
(c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch>
This file is part of the PIXHAWK project
PIXHAWK is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Waypoint list widget
*
* @author Lorenz Meier <[email protected]>
* @author Benjamin Knecht <[email protected]>
* @author Petri Tanskanen <[email protected]>
*
*/
#include "WaypointList.h"
#include "ui_WaypointList.h"
#include <UASInterface.h>
#include <UASManager.h>
#include <QDebug>
#include <QFileDialog>
WaypointList::WaypointList(QWidget *parent, UASInterface* uas) :
QWidget(parent),
uas(NULL),
m_ui(new Ui::WaypointList)
{
m_ui->setupUi(this);
listLayout = new QVBoxLayout(m_ui->listWidget);
listLayout->setSpacing(6);
listLayout->setMargin(0);
listLayout->setAlignment(Qt::AlignTop);
m_ui->listWidget->setLayout(listLayout);
wpViews = QMap<Waypoint*, WaypointView*>();
this->uas = NULL;
// ADD WAYPOINT
// Connect add action, set right button icon and connect action to this class
connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered()));
connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(add()));
// SEND WAYPOINTS
connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit()));
// REQUEST WAYPOINTS
connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read()));
// SAVE/LOAD WAYPOINTS
connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints()));
connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints()));
connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*)));
// STATUS LABEL
updateStatusLabel("");
// SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED
setUAS(uas);
}
WaypointList::~WaypointList()
{
delete m_ui;
}
void WaypointList::updateStatusLabel(const QString &string)
{
m_ui->statusLabel->setText(string);
}
void WaypointList::setUAS(UASInterface* uas)
{
if (this->uas == NULL && uas != NULL)
{
this->uas = uas;
connect(&uas->getWaypointManager(), SIGNAL(updateStatusString(const QString &)), this, SLOT(updateStatusLabel(const QString &)));
connect(&uas->getWaypointManager(), SIGNAL(waypointUpdated(int,quint16,double,double,double,double,bool,bool,double,int)), this, SLOT(setWaypoint(int,quint16,double,double,double,double,bool,bool,double,int)));
connect(&uas->getWaypointManager(), SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
connect(this, SIGNAL(sendWaypoints(const QVector<Waypoint*> &)), &uas->getWaypointManager(), SLOT(sendWaypoints(const QVector<Waypoint*> &)));
connect(this, SIGNAL(requestWaypoints()), &uas->getWaypointManager(), SLOT(requestWaypoints()));
connect(this, SIGNAL(clearWaypointList()), &uas->getWaypointManager(), SLOT(clearWaypointList()));
}
}
void WaypointList::setWaypoint(int uasId, quint16 id, double x, double y, double z, double yaw, bool autocontinue, bool current, double orbit, int holdTime)
{
if (uasId == this->uas->getUASID())
{
Waypoint* wp = new Waypoint(id, x, y, z, yaw, autocontinue, current, orbit, holdTime);
addWaypoint(wp);
}
}
void WaypointList::waypointReached(UASInterface* uas, quint16 waypointId)
{
Q_UNUSED(uas);
qDebug() << "Waypoint reached: " << waypointId;
updateStatusLabel(QString("Waypoint %1 reached.").arg(waypointId));
}
void WaypointList::currentWaypointChanged(quint16 seq)
{
if (seq < waypoints.size())
{
for(int i = 0; i < waypoints.size(); i++)
{
WaypointView* widget = wpViews.find(waypoints[i]).value();
if (waypoints[i]->getId() == seq)
{
waypoints[i]->setCurrent(true);
widget->setCurrent(true);
}
else
{
waypoints[i]->setCurrent(false);
widget->setCurrent(false);
}
}
redrawList();
}
}
void WaypointList::read()
{
while(waypoints.size()>0)
{
removeWaypoint(waypoints[0]);
}
emit requestWaypoints();
}
void WaypointList::transmit()
{
emit sendWaypoints(waypoints);
//emit requestWaypoints(); FIXME
}
void WaypointList::add()
{
// Only add waypoints if UAS is present
if (uas)
{
if (waypoints.size() > 0)
{
Waypoint *last = waypoints.at(waypoints.size()-1);
addWaypoint(new Waypoint(waypoints.size(), last->getX(), last->getY(), last->getZ(), last->getYaw(), last->getAutoContinue(), false, last->getOrbit(), last->getHoldTime()));
}
else
{
addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.8, 0.0, true, true, 0.1, 1000));
}
}
}
void WaypointList::addWaypoint(Waypoint* wp)
{
waypoints.push_back(wp);
if (!wpViews.contains(wp))
{
WaypointView* wpview = new WaypointView(wp, this);
wpViews.insert(wp, wpview);
listLayout->addWidget(wpViews.value(wp));
connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*)));
connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*)));
connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*)));
connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
}
}
void WaypointList::redrawList()
{
// Clear list layout
if (!wpViews.empty())
{
QMapIterator<Waypoint*,WaypointView*> viewIt(wpViews);
viewIt.toFront();
while(viewIt.hasNext())
{
viewIt.next();
listLayout->removeWidget(viewIt.value());
}
// Re-add waypoints
for(int i = 0; i < waypoints.size(); i++)
{
listLayout->addWidget(wpViews.value(waypoints[i]));
}
}
}
void WaypointList::moveUp(Waypoint* wp)
{
int id = wp->getId();
if (waypoints.size() > 1 && waypoints.size() > id)
{
Waypoint* temp = waypoints[id];
if (id > 0)
{
waypoints[id] = waypoints[id-1];
waypoints[id-1] = temp;
waypoints[id-1]->setId(id-1);
waypoints[id]->setId(id);
}
else
{
waypoints[id] = waypoints[waypoints.size()-1];
waypoints[waypoints.size()-1] = temp;
waypoints[waypoints.size()-1]->setId(waypoints.size()-1);
waypoints[id]->setId(id);
}
redrawList();
}
}
void WaypointList::moveDown(Waypoint* wp)
{
int id = wp->getId();
if (waypoints.size() > 1 && waypoints.size() > id)
{
Waypoint* temp = waypoints[id];
if (id != waypoints.size()-1)
{
waypoints[id] = waypoints[id+1];
waypoints[id+1] = temp;
waypoints[id+1]->setId(id+1);
waypoints[id]->setId(id);
}
else
{
waypoints[id] = waypoints[0];
waypoints[0] = temp;
waypoints[0]->setId(0);
waypoints[id]->setId(id);
}
redrawList();
}
}
void WaypointList::removeWaypoint(Waypoint* wp)
{
// Delete from list
if (wp != NULL)
{
waypoints.remove(wp->getId());
for(int i = wp->getId(); i < waypoints.size(); i++)
{
waypoints[i]->setId(i);
}
// Remove from view
WaypointView* widget = wpViews.find(wp).value();
wpViews.remove(wp);
widget->hide();
listLayout->removeWidget(widget);
delete wp;
}
}
void WaypointList::changeEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::LanguageChange:
m_ui->retranslateUi(this);
break;
default:
break;
}
}
void WaypointList::saveWaypoints()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)"));
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream in(&file);
for (int i = 0; i < waypoints.size(); i++)
{
Waypoint* wp = waypoints[i];
in << "\t" << wp->getId() << "\t" << wp->getX() << "\t" << wp->getY() << "\t" << wp->getZ() << "\t" << wp->getYaw() << "\t" << wp->getAutoContinue() << "\t" << wp->getCurrent() << "\t" << wp->getOrbit() << "\t" << wp->getHoldTime() << "\n";
in.flush();
}
file.close();
}
void WaypointList::loadWaypoints()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)"));
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while(waypoints.size()>0)
{
removeWaypoint(waypoints[0]);
}
QTextStream in(&file);
while (!in.atEnd())
{
QStringList wpParams = in.readLine().split("\t");
if (wpParams.size() == 10)
addWaypoint(new Waypoint(wpParams[1].toInt(), wpParams[2].toDouble(), wpParams[3].toDouble(), wpParams[4].toDouble(), wpParams[5].toDouble(), (wpParams[6].toInt() == 1 ? true : false), (wpParams[7].toInt() == 1 ? true : false), wpParams[8].toDouble(), wpParams[9].toInt()));
}
file.close();
}
<|endoftext|> |
<commit_before>#include "multiverso/util/allocator.h"
#include "multiverso/util/log.h"
#include "multiverso/util/configure.h"
namespace multiverso {
MV_DEFINE_int(allocator_alignment, 16, "alignment for align malloc");
inline char* AlignMalloc(size_t size) {
#ifdef _MSC_VER
return (char*)_aligned_malloc(size,
MV_CONFIG_allocator_alignment);
#else
void *data;
CHECK(posix_memalign(&data,
MV_CONFIG_allocator_alignment, size) == 0);
return (char*)data;
#endif
}
inline void AlignFree(char *data) {
#ifdef _MSC_VER
_aligned_free(data);
#else
free(data);
#endif
}
inline FreeList::FreeList(size_t size) :
size_(size) {
free_ = new MemoryBlock(size, this);
}
FreeList::~FreeList() {
MemoryBlock*move = free_, *next;
while (move) {
next = move->next;
delete move;
move = next;
}
}
inline char* FreeList::Pop() {
std::lock_guard<std::mutex> lock(mutex_);
if (free_ == nullptr) {
free_ = new MemoryBlock(size_, this);
}
char* data = free_->data();
free_ = free_->next;
return data;
}
inline void FreeList::Push(MemoryBlock*block) {
std::lock_guard<std::mutex> lock(mutex_);
block->next = free_;
free_ = block;
}
inline MemoryBlock::MemoryBlock(size_t size, FreeList* list) :
next(nullptr), ref_(0) {
data_ = AlignMalloc(size + header_size_);
*(FreeList**)(data_) = list;
*(MemoryBlock**)(data_ + g_pointer_size) = this;
}
MemoryBlock::~MemoryBlock() {
AlignFree(data_);
}
inline void MemoryBlock::Unlink() {
if ((--ref_) == 0) {
(*(FreeList**)data_)->Push(this);
}
}
inline char* MemoryBlock::data() {
++ref_;
return data_ + header_size_;
}
inline void MemoryBlock::Link() {
++ref_;
}
char* SmartAllocator::Alloc(size_t size) {
if (size <= 32) {
size = 32;
}
else { // 2^n
size -= 1;
size |= size >> 32;
size |= size >> 16;
size |= size >> 8;
size |= size >> 4;
size |= size >> 2;
size |= size >> 1;
size += 1;
}
std::unique_lock<std::mutex> lock(mutex_);
if (pools_[size] == nullptr) {
pools_[size] = new FreeList(size);
}
lock.unlock();
return pools_[size]->Pop();
}
void SmartAllocator::Free(char *data) {
(*(MemoryBlock**)(data - g_pointer_size))->Unlink();
}
void SmartAllocator::Refer(char *data) {
(*(MemoryBlock**)(data - g_pointer_size))->Link();
}
SmartAllocator::~SmartAllocator() {
Log::Debug("~SmartAllocator, final pool size: %d\n", pools_.size());
for (auto i : pools_) {
delete i.second;
}
}
char* Allocator::Alloc(size_t size) {
char* data = AlignMalloc(size + header_size_);
// record ref
*(std::atomic<int>**)data = new std::atomic<int>(1);
return data + header_size_;
}
void Allocator::Free(char* data) {
data -= header_size_;
if (--(**(std::atomic<int>**)data) == 0) {
delete *(std::atomic<int>**)data;
AlignFree(data);
}
}
void Allocator::Refer(char* data) {
++(**(std::atomic<int>**)(data - header_size_));
}
MV_DEFINE_string(allocator_type, "smart", "use smart allocator by default");
Allocator* Allocator::Get() {
if (MV_CONFIG_allocator_type == "smart") {
static SmartAllocator allocator_;
return &allocator_;
}
static Allocator allocator_;
return &allocator_;
}
} // namespace multiverso
<commit_msg>Little change<commit_after>#include "multiverso/util/allocator.h"
#include "multiverso/util/log.h"
#include "multiverso/util/configure.h"
namespace multiverso {
MV_DEFINE_int(allocator_alignment, 16, "alignment for align malloc");
inline char* AlignMalloc(size_t size) {
#ifdef _MSC_VER
return (char*)_aligned_malloc(size,
MV_CONFIG_allocator_alignment);
#else
void *data;
CHECK(posix_memalign(&data,
MV_CONFIG_allocator_alignment, size) == 0);
return (char*)data;
#endif
}
inline void AlignFree(char *data) {
#ifdef _MSC_VER
_aligned_free(data);
#else
free(data);
#endif
}
inline FreeList::FreeList(size_t size) :
size_(size) {
free_ = new MemoryBlock(size, this);
}
FreeList::~FreeList() {
MemoryBlock*move = free_, *next;
while (move) {
next = move->next;
delete move;
move = next;
}
}
inline char* FreeList::Pop() {
std::lock_guard<std::mutex> lock(mutex_);
if (free_ == nullptr) {
free_ = new MemoryBlock(size_, this);
}
char* data = free_->data();
free_ = free_->next;
return data;
}
inline void FreeList::Push(MemoryBlock*block) {
std::lock_guard<std::mutex> lock(mutex_);
block->next = free_;
free_ = block;
}
inline MemoryBlock::MemoryBlock(size_t size, FreeList* list) :
next(nullptr), ref_(0) {
data_ = AlignMalloc(size + header_size_);
*(FreeList**)(data_) = list;
*(MemoryBlock**)(data_ + g_pointer_size) = this;
}
MemoryBlock::~MemoryBlock() {
AlignFree(data_);
}
inline void MemoryBlock::Unlink() {
if ((--ref_) == 0) {
(*(FreeList**)data_)->Push(this);
}
}
inline char* MemoryBlock::data() {
++ref_;
return data_ + header_size_;
}
inline void MemoryBlock::Link() {
++ref_;
}
char* SmartAllocator::Alloc(size_t size) {
if (size <= 32) {
size = 32;
}
else { // 2^n
size -= 1;
size |= size >> 32;
size |= size >> 16;
size |= size >> 8;
size |= size >> 4;
size |= size >> 2;
size |= size >> 1;
size += 1;
}
{
std::lock_guard<std::mutex> lock(mutex_);
if (pools_[size] == nullptr) {
pools_[size] = new FreeList(size);
}
}
return pools_[size]->Pop();
}
void SmartAllocator::Free(char *data) {
(*(MemoryBlock**)(data - g_pointer_size))->Unlink();
}
void SmartAllocator::Refer(char *data) {
(*(MemoryBlock**)(data - g_pointer_size))->Link();
}
SmartAllocator::~SmartAllocator() {
Log::Debug("~SmartAllocator, final pool size: %d\n", pools_.size());
for (auto i : pools_) {
delete i.second;
}
}
char* Allocator::Alloc(size_t size) {
char* data = AlignMalloc(size + header_size_);
// record ref
*(std::atomic<int>**)data = new std::atomic<int>(1);
return data + header_size_;
}
void Allocator::Free(char* data) {
data -= header_size_;
if (--(**(std::atomic<int>**)data) == 0) {
delete *(std::atomic<int>**)data;
AlignFree(data);
}
}
void Allocator::Refer(char* data) {
++(**(std::atomic<int>**)(data - header_size_));
}
MV_DEFINE_string(allocator_type, "smart", "use smart allocator by default");
Allocator* Allocator::Get() {
if (MV_CONFIG_allocator_type == "smart") {
static SmartAllocator allocator_;
return &allocator_;
}
static Allocator allocator_;
return &allocator_;
}
} // namespace multiverso
<|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 <unistd.h>
#include <stx/exception.h>
#include <stx/uri.h>
#include <stx/protobuf/msg.h>
#include <stx/csv/CSVInputStream.h>
#include <common/ConfigDirectory.h>
using namespace stx;
namespace cm {
ConfigDirectory::ConfigDirectory(
const String& path,
const InetAddr master_addr) :
master_addr_(master_addr),
watcher_running_(false) {
mdb::MDBOptions mdb_opts;
mdb_opts.data_filename = "cdb.db",
mdb_opts.lock_filename = "cdb.db.lck";
mdb_opts.duplicate_keys = false;
db_ = mdb::MDB::open(path, mdb_opts);
listCustomers([this] (const CustomerConfig& cfg) {
customers_.emplace(cfg.customer(), new CustomerConfigRef(cfg));
});
sync();
}
RefPtr<CustomerConfigRef> ConfigDirectory::configFor(
const String& customer_key) const {
std::unique_lock<std::mutex> lk(mutex_);
auto iter = customers_.find(customer_key);
if (iter == customers_.end()) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
return iter->second;
}
void ConfigDirectory::listCustomers(
Function<void (const CustomerConfig& cfg)> fn) const {
auto prefix = "cfg~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<CustomerConfig>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onCustomerConfigChange(
Function<void (const CustomerConfig& cfg)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_customer_change_.emplace_back(fn);
}
void ConfigDirectory::addTableDefinition(const TableDefinition& table) {
std::unique_lock<std::mutex> lk(mutex_);
if (!StringUtil::isShellSafe(table.table_name())) {
RAISEF(
kIllegalArgumentError,
"invalid table name: '$0'",
table.table_name());
}
if (!table.has_schema_name() && !table.has_schema_inline()) {
RAISEF(
kIllegalArgumentError,
"can't add table without a schema: '$0'",
table.table_name());
}
auto db_key = StringUtil::format(
"tbl~$0~$1",
table.customer(),
table.table_name());
auto buf = msg::encode(table);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->insert(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->commit();
for (const auto& cb : on_table_change_) {
cb(table);
}
}
void ConfigDirectory::updateTableDefinition(const TableDefinition& table) {
std::unique_lock<std::mutex> lk(mutex_);
if (!StringUtil::isShellSafe(table.table_name())) {
RAISEF(
kIllegalArgumentError,
"invalid table name: '$0'",
table.table_name());
}
if (!table.has_schema_name() && !table.has_schema_inline()) {
RAISEF(
kIllegalArgumentError,
"can't add table without a schema: '$0'",
table.table_name());
}
auto db_key = StringUtil::format(
"tbl~$0~$1",
table.customer(),
table.table_name());
auto buf = msg::encode(table);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->commit();
for (const auto& cb : on_table_change_) {
cb(table);
}
}
void ConfigDirectory::listTableDefinitions(
Function<void (const TableDefinition& table)> fn) const {
auto prefix = "tbl~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<TableDefinition>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onTableDefinitionChange(
Function<void (const TableDefinition& tbl)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_table_change_.emplace_back(fn);
}
void ConfigDirectory::sync() {
auto master_heads = fetchMasterHeads();
Set<String> needs_update;
{
auto txn = db_->startTransaction(true);
txn->autoAbort();
for (const auto& head : master_heads) {
auto db_key = StringUtil::format("head~$0", head.first);
auto vstr = StringUtil::toString(head.second);
auto lastver = txn->get(db_key);
if (lastver.isEmpty() || lastver.get().toString() != vstr) {
needs_update.emplace(head.first);
}
}
txn->abort();
}
for (const auto& obj : needs_update) {
syncObject(obj);
}
}
void ConfigDirectory::syncObject(const String& obj) {
logDebug("analyticsd", "Syncing config object '$0' from master", obj);
static const String kCustomerPrefix = "customers/";
if (StringUtil::beginsWith(obj, kCustomerPrefix)) {
syncCustomerConfig(obj.substr(kCustomerPrefix.size()));
}
}
void ConfigDirectory::syncCustomerConfig(const String& customer) {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/customer_config?customer=$1",
master_addr_.hostAndPort(),
URI::urlEncode(customer)));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
commitCustomerConfig(msg::decode<CustomerConfig>(res.body()));
}
void ConfigDirectory::commitCustomerConfig(const CustomerConfig& config) {
auto db_key = StringUtil::format("cfg~$0", config.customer());
auto hkey = StringUtil::format("head~customers/$0", config.customer());
auto buf = msg::encode(config);
auto vstr = StringUtil::toString(config.version());
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->update(hkey.data(), hkey.size(), vstr.data(), vstr.size());
txn->commit();
customers_.emplace(config.customer(), new CustomerConfigRef(config));
for (const auto& cb : on_customer_change_) {
cb(config);
}
}
HashMap<String, uint64_t> ConfigDirectory::fetchMasterHeads() const {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/heads",
master_addr_.hostAndPort()));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
DefaultCSVInputStream csv(BufferInputStream::fromBuffer(&res.body()), '=');
HashMap<String, uint64_t> heads;
Vector<String> row;
while (csv.readNextRow(&row)) {
if (row.size() != 2) {
RAISE(kRuntimeError, "invalid response");
}
heads[row[0]] = std::stoull(row[1]);
}
return heads;
}
void ConfigDirectory::startWatcher() {
watcher_running_ = true;
watcher_thread_ = std::thread([this] {
while (watcher_running_.load()) {
try {
sync();
} catch (const StandardException& e) {
logCritical("analyticsd", e, "error during master sync");
}
usleep(500000);
}
});
}
void ConfigDirectory::stopWatcher() {
if (!watcher_running_) {
return;
}
watcher_running_ = false;
watcher_thread_.join();
}
} // namespace cm
<commit_msg>version check in ConfigDirectory::commitCustomerConfig<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 <unistd.h>
#include <stx/exception.h>
#include <stx/uri.h>
#include <stx/protobuf/msg.h>
#include <stx/csv/CSVInputStream.h>
#include <common/ConfigDirectory.h>
using namespace stx;
namespace cm {
ConfigDirectory::ConfigDirectory(
const String& path,
const InetAddr master_addr) :
master_addr_(master_addr),
watcher_running_(false) {
mdb::MDBOptions mdb_opts;
mdb_opts.data_filename = "cdb.db",
mdb_opts.lock_filename = "cdb.db.lck";
mdb_opts.duplicate_keys = false;
db_ = mdb::MDB::open(path, mdb_opts);
listCustomers([this] (const CustomerConfig& cfg) {
customers_.emplace(cfg.customer(), new CustomerConfigRef(cfg));
});
sync();
}
RefPtr<CustomerConfigRef> ConfigDirectory::configFor(
const String& customer_key) const {
std::unique_lock<std::mutex> lk(mutex_);
auto iter = customers_.find(customer_key);
if (iter == customers_.end()) {
RAISEF(kNotFoundError, "customer not found: $0", customer_key);
}
return iter->second;
}
void ConfigDirectory::listCustomers(
Function<void (const CustomerConfig& cfg)> fn) const {
auto prefix = "cfg~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<CustomerConfig>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onCustomerConfigChange(
Function<void (const CustomerConfig& cfg)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_customer_change_.emplace_back(fn);
}
void ConfigDirectory::addTableDefinition(const TableDefinition& table) {
std::unique_lock<std::mutex> lk(mutex_);
if (!StringUtil::isShellSafe(table.table_name())) {
RAISEF(
kIllegalArgumentError,
"invalid table name: '$0'",
table.table_name());
}
if (!table.has_schema_name() && !table.has_schema_inline()) {
RAISEF(
kIllegalArgumentError,
"can't add table without a schema: '$0'",
table.table_name());
}
auto db_key = StringUtil::format(
"tbl~$0~$1",
table.customer(),
table.table_name());
auto buf = msg::encode(table);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->insert(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->commit();
for (const auto& cb : on_table_change_) {
cb(table);
}
}
void ConfigDirectory::updateTableDefinition(const TableDefinition& table) {
std::unique_lock<std::mutex> lk(mutex_);
if (!StringUtil::isShellSafe(table.table_name())) {
RAISEF(
kIllegalArgumentError,
"invalid table name: '$0'",
table.table_name());
}
if (!table.has_schema_name() && !table.has_schema_inline()) {
RAISEF(
kIllegalArgumentError,
"can't add table without a schema: '$0'",
table.table_name());
}
auto db_key = StringUtil::format(
"tbl~$0~$1",
table.customer(),
table.table_name());
auto buf = msg::encode(table);
auto txn = db_->startTransaction(false);
txn->autoAbort();
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->commit();
for (const auto& cb : on_table_change_) {
cb(table);
}
}
void ConfigDirectory::listTableDefinitions(
Function<void (const TableDefinition& table)> fn) const {
auto prefix = "tbl~";
Buffer key;
Buffer value;
auto txn = db_->startTransaction(true);
txn->autoAbort();
auto cursor = txn->getCursor();
key.append(prefix);
if (!cursor->getFirstOrGreater(&key, &value)) {
return;
}
do {
if (!StringUtil::beginsWith(key.toString(), prefix)) {
break;
}
fn(msg::decode<TableDefinition>(value));
} while (cursor->getNext(&key, &value));
cursor->close();
}
void ConfigDirectory::onTableDefinitionChange(
Function<void (const TableDefinition& tbl)> fn) {
std::unique_lock<std::mutex> lk(mutex_);
on_table_change_.emplace_back(fn);
}
void ConfigDirectory::sync() {
auto master_heads = fetchMasterHeads();
Set<String> needs_update;
{
auto txn = db_->startTransaction(true);
txn->autoAbort();
for (const auto& head : master_heads) {
auto db_key = StringUtil::format("head~$0", head.first);
auto vstr = StringUtil::toString(head.second);
auto lastver = txn->get(db_key);
if (lastver.isEmpty() || lastver.get().toString() != vstr) {
needs_update.emplace(head.first);
}
}
txn->abort();
}
for (const auto& obj : needs_update) {
syncObject(obj);
}
}
void ConfigDirectory::syncObject(const String& obj) {
logDebug("analyticsd", "Syncing config object '$0' from master", obj);
static const String kCustomerPrefix = "customers/";
if (StringUtil::beginsWith(obj, kCustomerPrefix)) {
syncCustomerConfig(obj.substr(kCustomerPrefix.size()));
}
}
void ConfigDirectory::syncCustomerConfig(const String& customer) {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/fetch_customer_config?customer=$1",
master_addr_.hostAndPort(),
URI::urlEncode(customer)));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
commitCustomerConfig(msg::decode<CustomerConfig>(res.body()));
}
void ConfigDirectory::commitCustomerConfig(const CustomerConfig& config) {
auto db_key = StringUtil::format("cfg~$0", config.customer());
auto hkey = StringUtil::format("head~customers/$0", config.customer());
auto buf = msg::encode(config);
auto vstr = StringUtil::toString(config.version());
std::unique_lock<std::mutex> lk(mutex_);
auto txn = db_->startTransaction(false);
auto last_version = 0;
auto last_version_str = txn->get(hkey);
if (!last_version_str.isEmpty()) {
last_version = std::stoull(last_version_str.get().toString());
}
if (last_version >= config.version()) {
RAISE(kRuntimeError, "refusing to commit outdated version");
}
txn->autoAbort();
txn->update(db_key.data(), db_key.size(), buf->data(), buf->size());
txn->update(hkey.data(), hkey.size(), vstr.data(), vstr.size());
txn->commit();
customers_.emplace(config.customer(), new CustomerConfigRef(config));
for (const auto& cb : on_customer_change_) {
cb(config);
}
}
HashMap<String, uint64_t> ConfigDirectory::fetchMasterHeads() const {
auto uri = URI(
StringUtil::format(
"http://$0/analytics/master/heads",
master_addr_.hostAndPort()));
http::HTTPClient http;
auto res = http.executeRequest(http::HTTPRequest::mkGet(uri));
if (res.statusCode() != 200) {
RAISEF(kRuntimeError, "error: $0", res.body().toString());
}
DefaultCSVInputStream csv(BufferInputStream::fromBuffer(&res.body()), '=');
HashMap<String, uint64_t> heads;
Vector<String> row;
while (csv.readNextRow(&row)) {
if (row.size() != 2) {
RAISE(kRuntimeError, "invalid response");
}
heads[row[0]] = std::stoull(row[1]);
}
return heads;
}
void ConfigDirectory::startWatcher() {
watcher_running_ = true;
watcher_thread_ = std::thread([this] {
while (watcher_running_.load()) {
try {
sync();
} catch (const StandardException& e) {
logCritical("analyticsd", e, "error during master sync");
}
usleep(500000);
}
});
}
void ConfigDirectory::stopWatcher() {
if (!watcher_running_) {
return;
}
watcher_running_ = false;
watcher_thread_.join();
}
} // namespace cm
<|endoftext|> |
<commit_before>#include "cppunit/TestSuite.h"
#include "cppunit/TestResult.h"
namespace CppUnit {
/// Deletes all tests in the suite.
void TestSuite::deleteContents ()
{
for (std::vector<Test *>::iterator it = m_tests.begin ();
it != m_tests.end ();
++it)
delete *it;
m_tests.clear();
}
/// Runs the tests and collects their result in a TestResult.
void TestSuite::run (TestResult *result)
{
for (std::vector<Test *>::iterator it = m_tests.begin ();
it != m_tests.end ();
++it) {
if (result->shouldStop ())
break;
Test *test = *it;
test->run (result);
}
}
/// Counts the number of test cases that will be run by this test.
int TestSuite::countTestCases () const
{
int count = 0;
for (std::vector<Test * const>::iterator it = m_tests.begin ();
it != m_tests.end ();
++it)
count += (*it)->countTestCases ();
return count;
}
/// Default constructor
TestSuite::TestSuite (std::string name)
: m_name (name)
{
}
/// Destructor
TestSuite::~TestSuite ()
{
deleteContents ();
}
/// Adds a test to the suite.
void
TestSuite::addTest (Test *test)
{
m_tests.push_back (test);
}
/// Returns a string representation of the test suite.
std::string
TestSuite::toString () const
{
return "suite " + getName();
}
/// Returns the name of the test suite.
std::string
TestSuite::getName () const
{
return m_name;
}
} // namespace CppUnit
<commit_msg>Fix compilation bug on Win32/MSVC++.<commit_after>#include "cppunit/TestSuite.h"
#include "cppunit/TestResult.h"
namespace CppUnit {
/// Deletes all tests in the suite.
void TestSuite::deleteContents ()
{
for (std::vector<Test *>::iterator it = m_tests.begin ();
it != m_tests.end ();
++it)
delete *it;
m_tests.clear();
}
/// Runs the tests and collects their result in a TestResult.
void TestSuite::run (TestResult *result)
{
for (std::vector<Test *>::iterator it = m_tests.begin ();
it != m_tests.end ();
++it) {
if (result->shouldStop ())
break;
Test *test = *it;
test->run (result);
}
}
/// Counts the number of test cases that will be run by this test.
int TestSuite::countTestCases () const
{
int count = 0;
for (std::vector<Test *>::const_iterator it = m_tests.begin ();
it != m_tests.end ();
++it)
count += (*it)->countTestCases ();
return count;
}
/// Default constructor
TestSuite::TestSuite (std::string name)
: m_name (name)
{
}
/// Destructor
TestSuite::~TestSuite ()
{
deleteContents ();
}
/// Adds a test to the suite.
void
TestSuite::addTest (Test *test)
{
m_tests.push_back (test);
}
/// Returns a string representation of the test suite.
std::string
TestSuite::toString () const
{
return "suite " + getName();
}
/// Returns the name of the test suite.
std::string
TestSuite::getName () const
{
return m_name;
}
} // namespace CppUnit
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
// Author: Martin Klemsa
//----------------------------------------------------------------------------
#ifndef _ctoolhu_random_generator_included_
#define _ctoolhu_random_generator_included_
#include "engine.hpp"
#include <boost/random/variate_generator.hpp>
#include <boost/random/uniform_smallint.hpp>
#ifdef _DEBUG_RAND
#include <ctoolhu/event/events.h>
#include <ctoolhu/event/firer.hpp>
#include <string>
#endif
namespace Ctoolhu {
namespace Random {
//shortcut for the generator template we'll be using
template <class Distribution>
using RandomGenerator = boost::variate_generator<Private::RandomEngine &, Distribution>;
//generator with run-time bounds
template <
class Distribution,
typename Boundary = int
>
class Generator : public RandomGenerator<Distribution> {
typedef RandomGenerator<Distribution> base_type;
public:
//for number generators
Generator(Boundary lower, Boundary upper)
: base_type(Private::SingleRandomEngine::Instance(), Distribution(lower, upper)) {}
//for bool generator
Generator()
: base_type(Private::SingleRandomEngine::Instance(), Distribution()) {}
#ifdef _DEBUG_RAND
result_type operator()()
{
auto res = this->base_type::operator()();
Event::Fire(Event::Message{"random: " + std::to_string(res)});
return res;
}
#endif
};
//generator with compile-time bounds
template <
int LowerBound,
int UpperBound,
class Distribution = std::uniform_int_distribution<>
>
class StaticGenerator : public RandomGenerator<Distribution> {
public:
StaticGenerator()
: RandomGenerator<Distribution>(Private::SingleRandomEngine::Instance(), Distribution(LowerBound, UpperBound)) {}
};
//expose typical usages of the dynamic generator
typedef Generator<std::uniform_int_distribution<>> IntGenerator;
typedef Generator<boost::uniform_smallint<>> SmallIntGenerator;
typedef Generator<std::uniform_real_distribution<float>, float> FloatGenerator;
typedef Generator<std::bernoulli_distribution> BoolGenerator;
} //ns Random
} //ns Ctoolhu
#endif
<commit_msg>Corrected random generator build with DEBUG_RAND defined<commit_after>//----------------------------------------------------------------------------
// Author: Martin Klemsa
//----------------------------------------------------------------------------
#ifndef _ctoolhu_random_generator_included_
#define _ctoolhu_random_generator_included_
#include "engine.hpp"
#include <boost/random/variate_generator.hpp>
#include <boost/random/uniform_smallint.hpp>
#ifdef _DEBUG_RAND
#include <ctoolhu/event/events.h>
#include <ctoolhu/event/firer.hpp>
#include <string>
#endif
namespace Ctoolhu {
namespace Random {
//shortcut for the generator template we'll be using
template <class Distribution>
using RandomGenerator = boost::variate_generator<Private::RandomEngine &, Distribution>;
//generator with run-time bounds
template <
class Distribution,
typename Boundary = int
>
class Generator : public RandomGenerator<Distribution> {
typedef RandomGenerator<Distribution> base_type;
public:
//for number generators
Generator(Boundary lower, Boundary upper)
: base_type(Private::SingleRandomEngine::Instance(), Distribution(lower, upper)) {}
//for bool generator
Generator()
: base_type(Private::SingleRandomEngine::Instance(), Distribution()) {}
#ifdef _DEBUG_RAND
auto operator()()
{
auto res = this->base_type::operator()();
Event::Fire(Event::Message{"random: " + std::to_string(res)});
return res;
}
#endif
};
//generator with compile-time bounds
template <
int LowerBound,
int UpperBound,
class Distribution = std::uniform_int_distribution<>
>
class StaticGenerator : public RandomGenerator<Distribution> {
public:
StaticGenerator()
: RandomGenerator<Distribution>(Private::SingleRandomEngine::Instance(), Distribution(LowerBound, UpperBound)) {}
};
//expose typical usages of the dynamic generator
typedef Generator<std::uniform_int_distribution<>> IntGenerator;
typedef Generator<boost::uniform_smallint<>> SmallIntGenerator;
typedef Generator<std::uniform_real_distribution<float>, float> FloatGenerator;
typedef Generator<std::bernoulli_distribution> BoolGenerator;
} //ns Random
} //ns Ctoolhu
#endif
<|endoftext|> |
<commit_before>#include "Benchmark.h"
#include "SkPMFloat.h"
#include "SkRandom.h"
struct PMFloatBench : public Benchmark {
explicit PMFloatBench(bool clamp) : fClamp(clamp) {}
const char* onGetName() SK_OVERRIDE { return fClamp ? "SkPMFloat_clamp" : "SkPMFloat_get"; }
bool isSuitableFor(Backend backend) SK_OVERRIDE { return backend == kNonRendering_Backend; }
void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
SkRandom rand;
for (int i = 0; i < loops; i++) {
SkPMColor c = SkPreMultiplyColor(rand.nextU());
SkPMFloat pmf;
pmf.set(c);
SkPMColor back = fClamp ? pmf.clamped() : pmf.get();
if (c != back) { SkFAIL("no joy"); } // This conditional makes this not compile away.
}
}
bool fClamp;
};
DEF_BENCH(return new PMFloatBench( true);)
DEF_BENCH(return new PMFloatBench(false);)
<commit_msg>Trim the fat off SkPMFloat bench.<commit_after>#include "Benchmark.h"
#include "SkPMFloat.h"
// Used to prevent the compiler from optimizing away the whole loop.
volatile uint32_t blackhole = 0;
// Not a great random number generator, but it's very fast.
// The code we're measuring is quite fast, so low overhead is essential.
static uint32_t lcg_rand(uint32_t* seed) {
*seed *= 1664525;
*seed += 1013904223;
return *seed;
}
struct PMFloatBench : public Benchmark {
explicit PMFloatBench(bool clamp) : fClamp(clamp) {}
const char* onGetName() SK_OVERRIDE { return fClamp ? "SkPMFloat_clamp" : "SkPMFloat_get"; }
bool isSuitableFor(Backend backend) SK_OVERRIDE { return backend == kNonRendering_Backend; }
void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
// Unlike blackhole, junk can and probably will be a register.
uint32_t junk = 0;
uint32_t seed = 0;
for (int i = 0; i < loops; i++) {
#ifdef SK_DEBUG
// Our SkASSERTs will remind us that it's technically required that we premultiply.
SkPMColor c = SkPreMultiplyColor(lcg_rand(&seed));
#else
// But it's a lot faster not to, and this code won't really mind the non-PM colors.
SkPMColor c = lcg_rand(&seed);
#endif
SkPMFloat pmf;
pmf.set(c);
SkPMColor back = fClamp ? pmf.clamped() : pmf.get();
junk ^= back;
}
blackhole ^= junk;
}
bool fClamp;
};
DEF_BENCH(return new PMFloatBench( true);)
DEF_BENCH(return new PMFloatBench(false);)
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// mvcc_test.cpp
//
// Identification: tests/concurrency/mvcc_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "harness.h"
#include "concurrency/transaction_tests_util.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Transaction Tests
//===--------------------------------------------------------------------===//
class MVCCTest : public PelotonTest {};
// Validate that MVCC storage is correct, it assumes an old-to-new chain
// Invariants
// 1. Transaction id should either be INVALID_TXNID or INITIAL_TXNID
// 2. Begin commit id should <= end commit id
// 3. Timestamp consistence
// 4. Version doubly linked list consistency
static void ValidateMVCC_OldToNew(storage::DataTable *table) {
auto &gc_manager = gc::GCManagerFactory::GetInstance();
auto &catalog_manager = catalog::Manager::GetInstance();
gc_manager.StopGC();
LOG_INFO("Validating MVCC storage");
int tile_group_count = table->GetTileGroupCount();
LOG_INFO("The table has %d tile groups in the table", tile_group_count);
for (int tile_group_offset = 0; tile_group_offset < tile_group_count; tile_group_offset++) {
LOG_INFO("Validate tile group #%d", tile_group_offset);
auto tile_group = table->GetTileGroup(tile_group_offset);
auto tile_group_header = tile_group->GetHeader();
size_t tuple_count = tile_group->GetAllocatedTupleCount();
LOG_INFO("Tile group #%d has allocated %lu tuples", tile_group_offset, tuple_count);
// 1. Transaction id should either be INVALID_TXNID or INITIAL_TXNID
for (oid_t tuple_slot = 0; tuple_slot < tuple_count; tuple_slot++) {
txn_id_t txn_id = tile_group_header->GetTransactionId(tuple_slot);
EXPECT_TRUE(txn_id == INVALID_TXN_ID || txn_id == INITIAL_TXN_ID) << "Transaction id is not INVALID_TXNID or INITIAL_TXNID";
}
LOG_INFO("[OK] All tuples have valid txn id");
// double avg_version_chain_length = 0.0;
for (oid_t tuple_slot = 0; tuple_slot < tuple_count; tuple_slot++) {
txn_id_t txn_id = tile_group_header->GetTransactionId(tuple_slot);
cid_t begin_cid = tile_group_header->GetBeginCommitId(tuple_slot);
cid_t end_cid = tile_group_header->GetEndCommitId(tuple_slot);
ItemPointer next_location = tile_group_header->GetNextItemPointer(tuple_slot);
ItemPointer prev_location = tile_group_header->GetPrevItemPointer(tuple_slot);
// 2. Begin commit id should <= end commit id
EXPECT_TRUE(begin_cid <= end_cid) << "Tuple begin commit id is less than or equal to end commit id";
// This test assumes a oldest-to-newest version chain
if (txn_id != INVALID_TXN_ID) {
EXPECT_TRUE(begin_cid != MAX_CID) << "Non invalid txn shouldn't have a MAX_CID begin commit id";
// The version is an oldest version
if (prev_location.IsNull()) {
if (next_location.IsNull()) {
EXPECT_EQ(end_cid, MAX_CID) << "Single version has a non MAX_CID end commit time";
} else {
cid_t prev_end_cid = end_cid;
ItemPointer prev_location(tile_group_offset, tuple_slot);
while (!next_location.IsNull()) {
auto next_tile_group = catalog_manager.GetTileGroup(next_location.block);
auto next_tile_group_header = next_tile_group->GetHeader();
txn_id_t next_txn_id = next_tile_group_header->GetTransactionId(next_location.offset);
if (next_txn_id == INVALID_TXN_ID) {
// If a version in the version chain has a INVALID_TXN_ID, it must be at the tail
// of the chain. It is either because we have deleted a tuple (so append a invalid tuple),
// or because this new version is aborted.
EXPECT_TRUE(next_tile_group_header->GetNextItemPointer(next_location.offset).IsNull()) << "Invalid version in a version chain and is not delete";
}
cid_t next_begin_cid = next_tile_group_header->GetBeginCommitId(next_location.offset);
cid_t next_end_cid = next_tile_group_header->GetEndCommitId(next_location.offset);
// 3. Timestamp consistence
if (next_begin_cid == MAX_CID) {
// It must be an aborted version, it should be at the end of the chain
EXPECT_TRUE(next_tile_group_header->GetNextItemPointer(next_location.offset).IsNull()) << "Version with MAX_CID begin cid is not version tail";
} else {
EXPECT_EQ(prev_end_cid, next_begin_cid) << "Prev end commit id should equal net begin commit id";
ItemPointer next_prev_location = next_tile_group_header->GetPrevItemPointer(next_location.offset);
// 4. Version doubly linked list consistency
EXPECT_TRUE(next_prev_location.offset == prev_location.offset &&
next_prev_location.block == prev_location.block) << "Next version's prev version does not match";
}
prev_location = next_location;
prev_end_cid = next_end_cid;
next_location = next_tile_group_header->GetNextItemPointer(next_location.offset);
}
// Now prev_location is at the tail of the version chain
ItemPointer last_location = prev_location;
auto last_tile_group = catalog_manager.GetTileGroup(last_location.block);
auto last_tile_group_header = last_tile_group->GetHeader();
// txn_id_t last_txn_id = last_tile_group_header->GetTransactionId(last_location.offset);
cid_t last_end_cid = last_tile_group_header->GetEndCommitId(last_location.offset);
EXPECT_TRUE(last_tile_group_header->GetNextItemPointer(last_location.offset).IsNull()) << "Last version has a next pointer";
EXPECT_EQ(last_end_cid , MAX_CID) << "Last version doesn't end with MAX_CID";
}
}
} else {
EXPECT_TRUE(tile_group_header->GetNextItemPointer(tuple_slot).IsNull()) << "Invalid tuple must not have next item pointer";
}
}
LOG_INFO("[OK] oldest-to-newest version chain validated");
}
gc_manager.StartGC();
}
TEST_F(MVCCTest, SingleThreadVersionChainTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
// read, read, read, read, update, read, read not exist
// another txn read
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(100);
scheduler.Txn(0).Commit();
scheduler.Txn(1).Read(0);
scheduler.Txn(1).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
// update, update, update, update, read
{
TransactionScheduler scheduler(1, table.get(), &txn_manager);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Update(0, 2);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Update(0, 4);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
// delete not exist, delete exist, read deleted, update deleted,
// read deleted, insert back, update inserted, read newly updated,
// delete inserted, read deleted
{
TransactionScheduler scheduler(1, table.get(), &txn_manager);
scheduler.Txn(0).Delete(100);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Insert(0, 2);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
// insert, delete inserted, read deleted, insert again, delete again
// read deleted, insert again, read inserted, update inserted, read updated
{
TransactionScheduler scheduler(1, table.get(), &txn_manager);
scheduler.Txn(0).Insert(1000, 0);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 1);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 2);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Update(1000, 3);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
}
TEST_F(MVCCTest, VersionChainTest) {
const int num_txn = 5;
const int scale = 20;
const int num_key = 256;
srand(15721);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable(num_key));
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
TransactionScheduler scheduler(num_txn, table.get(), &txn_manager);
scheduler.SetConcurrent(true);
for (int i = 0; i < num_txn; i++) {
for (int j = 0; j < scale; j++) {
// randomly select two uniq keys
int key1 = rand() % num_key;
int key2 = rand() % num_key;
int delta = rand() % 1000;
// Store substracted value
scheduler.Txn(i).ReadStore(key1, -delta);
scheduler.Txn(i).Update(key1, TXN_STORED_VALUE);
// Store increased value
scheduler.Txn(i).ReadStore(key2, delta);
scheduler.Txn(i).Update(key2, TXN_STORED_VALUE);
}
scheduler.Txn(i).Commit();
}
scheduler.Run();
// Read all values
TransactionScheduler scheduler2(1, table.get(), &txn_manager);
for (int i = 0; i < num_key; i++) {
scheduler2.Txn(0).Read(i);
}
scheduler2.Txn(0).Commit();
scheduler2.Run();
ValidateMVCC_OldToNew(table.get());
}
} // End test namespace
} // End peloton namespace
<commit_msg>add abort version chain test<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// mvcc_test.cpp
//
// Identification: tests/concurrency/mvcc_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "harness.h"
#include "concurrency/transaction_tests_util.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Transaction Tests
//===--------------------------------------------------------------------===//
class MVCCTest : public PelotonTest {};
// Validate that MVCC storage is correct, it assumes an old-to-new chain
// Invariants
// 1. Transaction id should either be INVALID_TXNID or INITIAL_TXNID
// 2. Begin commit id should <= end commit id
// 3. Timestamp consistence
// 4. Version doubly linked list consistency
static void ValidateMVCC_OldToNew(storage::DataTable *table) {
auto &gc_manager = gc::GCManagerFactory::GetInstance();
auto &catalog_manager = catalog::Manager::GetInstance();
gc_manager.StopGC();
LOG_INFO("Validating MVCC storage");
int tile_group_count = table->GetTileGroupCount();
LOG_INFO("The table has %d tile groups in the table", tile_group_count);
for (int tile_group_offset = 0; tile_group_offset < tile_group_count; tile_group_offset++) {
LOG_INFO("Validate tile group #%d", tile_group_offset);
auto tile_group = table->GetTileGroup(tile_group_offset);
auto tile_group_header = tile_group->GetHeader();
size_t tuple_count = tile_group->GetAllocatedTupleCount();
LOG_INFO("Tile group #%d has allocated %lu tuples", tile_group_offset, tuple_count);
// 1. Transaction id should either be INVALID_TXNID or INITIAL_TXNID
for (oid_t tuple_slot = 0; tuple_slot < tuple_count; tuple_slot++) {
txn_id_t txn_id = tile_group_header->GetTransactionId(tuple_slot);
EXPECT_TRUE(txn_id == INVALID_TXN_ID || txn_id == INITIAL_TXN_ID) << "Transaction id is not INVALID_TXNID or INITIAL_TXNID";
}
LOG_INFO("[OK] All tuples have valid txn id");
// double avg_version_chain_length = 0.0;
for (oid_t tuple_slot = 0; tuple_slot < tuple_count; tuple_slot++) {
txn_id_t txn_id = tile_group_header->GetTransactionId(tuple_slot);
cid_t begin_cid = tile_group_header->GetBeginCommitId(tuple_slot);
cid_t end_cid = tile_group_header->GetEndCommitId(tuple_slot);
ItemPointer next_location = tile_group_header->GetNextItemPointer(tuple_slot);
ItemPointer prev_location = tile_group_header->GetPrevItemPointer(tuple_slot);
// 2. Begin commit id should <= end commit id
EXPECT_TRUE(begin_cid <= end_cid) << "Tuple begin commit id is less than or equal to end commit id";
// This test assumes a oldest-to-newest version chain
if (txn_id != INVALID_TXN_ID) {
EXPECT_TRUE(begin_cid != MAX_CID) << "Non invalid txn shouldn't have a MAX_CID begin commit id";
// The version is an oldest version
if (prev_location.IsNull()) {
if (next_location.IsNull()) {
EXPECT_EQ(end_cid, MAX_CID) << "Single version has a non MAX_CID end commit time";
} else {
cid_t prev_end_cid = end_cid;
ItemPointer prev_location(tile_group_offset, tuple_slot);
while (!next_location.IsNull()) {
auto next_tile_group = catalog_manager.GetTileGroup(next_location.block);
auto next_tile_group_header = next_tile_group->GetHeader();
txn_id_t next_txn_id = next_tile_group_header->GetTransactionId(next_location.offset);
if (next_txn_id == INVALID_TXN_ID) {
// If a version in the version chain has a INVALID_TXN_ID, it must be at the tail
// of the chain. It is either because we have deleted a tuple (so append a invalid tuple),
// or because this new version is aborted.
EXPECT_TRUE(next_tile_group_header->GetNextItemPointer(next_location.offset).IsNull()) << "Invalid version in a version chain and is not delete";
}
cid_t next_begin_cid = next_tile_group_header->GetBeginCommitId(next_location.offset);
cid_t next_end_cid = next_tile_group_header->GetEndCommitId(next_location.offset);
// 3. Timestamp consistence
if (next_begin_cid == MAX_CID) {
// It must be an aborted version, it should be at the end of the chain
EXPECT_TRUE(next_tile_group_header->GetNextItemPointer(next_location.offset).IsNull()) << "Version with MAX_CID begin cid is not version tail";
} else {
EXPECT_EQ(prev_end_cid, next_begin_cid) << "Prev end commit id should equal net begin commit id";
ItemPointer next_prev_location = next_tile_group_header->GetPrevItemPointer(next_location.offset);
// 4. Version doubly linked list consistency
EXPECT_TRUE(next_prev_location.offset == prev_location.offset &&
next_prev_location.block == prev_location.block) << "Next version's prev version does not match";
}
prev_location = next_location;
prev_end_cid = next_end_cid;
next_location = next_tile_group_header->GetNextItemPointer(next_location.offset);
}
// Now prev_location is at the tail of the version chain
ItemPointer last_location = prev_location;
auto last_tile_group = catalog_manager.GetTileGroup(last_location.block);
auto last_tile_group_header = last_tile_group->GetHeader();
// txn_id_t last_txn_id = last_tile_group_header->GetTransactionId(last_location.offset);
cid_t last_end_cid = last_tile_group_header->GetEndCommitId(last_location.offset);
EXPECT_TRUE(last_tile_group_header->GetNextItemPointer(last_location.offset).IsNull()) << "Last version has a next pointer";
EXPECT_EQ(last_end_cid , MAX_CID) << "Last version doesn't end with MAX_CID";
}
}
} else {
EXPECT_TRUE(tile_group_header->GetNextItemPointer(tuple_slot).IsNull()) << "Invalid tuple must not have next item pointer";
}
}
LOG_INFO("[OK] oldest-to-newest version chain validated");
}
gc_manager.StartGC();
}
TEST_F(MVCCTest, SingleThreadVersionChainTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
// read, read, read, read, update, read, read not exist
// another txn read
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(100);
scheduler.Txn(0).Commit();
scheduler.Txn(1).Read(0);
scheduler.Txn(1).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
// update, update, update, update, read
{
TransactionScheduler scheduler(1, table.get(), &txn_manager);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Update(0, 2);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Update(0, 4);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
// delete not exist, delete exist, read deleted, update deleted,
// read deleted, insert back, update inserted, read newly updated,
// delete inserted, read deleted
{
TransactionScheduler scheduler(1, table.get(), &txn_manager);
scheduler.Txn(0).Delete(100);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Insert(0, 2);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
// insert, delete inserted, read deleted, insert again, delete again
// read deleted, insert again, read inserted, update inserted, read updated
{
TransactionScheduler scheduler(1, table.get(), &txn_manager);
scheduler.Txn(0).Insert(1000, 0);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 1);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 2);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Update(1000, 3);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
}
TEST_F(MVCCTest, AbortVersionChainTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.Txn(0).Update(0, 100);
scheduler.Txn(0).Abort();
scheduler.Txn(1).Read(0);
scheduler.Txn(1).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.Txn(0).Insert(100, 0);
scheduler.Txn(0).Abort();
scheduler.Txn(1).Read(100);
scheduler.Txn(1).Commit();
scheduler.Run();
ValidateMVCC_OldToNew(table.get());
}
}
TEST_F(MVCCTest, VersionChainTest) {
const int num_txn = 5;
const int scale = 20;
const int num_key = 256;
srand(15721);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable(num_key));
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
TransactionScheduler scheduler(num_txn, table.get(), &txn_manager);
scheduler.SetConcurrent(true);
for (int i = 0; i < num_txn; i++) {
for (int j = 0; j < scale; j++) {
// randomly select two uniq keys
int key1 = rand() % num_key;
int key2 = rand() % num_key;
int delta = rand() % 1000;
// Store substracted value
scheduler.Txn(i).ReadStore(key1, -delta);
scheduler.Txn(i).Update(key1, TXN_STORED_VALUE);
// Store increased value
scheduler.Txn(i).ReadStore(key2, delta);
scheduler.Txn(i).Update(key2, TXN_STORED_VALUE);
}
scheduler.Txn(i).Commit();
}
scheduler.Run();
// Read all values
TransactionScheduler scheduler2(1, table.get(), &txn_manager);
for (int i = 0; i < num_key; i++) {
scheduler2.Txn(0).Read(i);
}
scheduler2.Txn(0).Commit();
scheduler2.Run();
ValidateMVCC_OldToNew(table.get());
}
} // End test namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>#include <boost/version.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <iostream>
#include <mapnik/params.hpp>
#include <mapnik/boolean.hpp>
int main( int, char*[] )
{
mapnik::parameters params;
// true
//params["bool"] = true;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "true";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
//params["bool"] = 1;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "1";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "True";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "on";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "yes";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
// false
//params["bool"] = false;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false) );
params["bool"] = "false";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false) );
//params["bool"] = 0;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "0";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "False";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "off";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "no";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
// strings
params["string"] = "hello";
BOOST_TEST( (params.get<std::string>("string") && *params.get<std::string>("string") == "hello") );
// int
params["int"] = 1LL;
BOOST_TEST( (params.get<int>("int") && *params.get<int>("int") == 1) );
// double
params["double"] = 1.5;
BOOST_TEST( (params.get<double>("double") && *params.get<double>("double") == 1.5) );
// value_null
params["null"] = mapnik::value_null();
//BOOST_TEST( (params.get<mapnik::value_null>("null")/* && *params.get<mapnik::value_null>("null") == mapnik::value_null()*/) );
if (!::boost::detail::test_errors()) {
std::clog << "C++ parameters: \x1b[1;32m✓ \x1b[0m\n";
#if BOOST_VERSION >= 104600
::boost::detail::report_errors_remind().called_report_errors_function = true;
#endif
} else {
return ::boost::report_errors();
}
}
<commit_msg>+ remove LL<commit_after>#include <boost/version.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <iostream>
#include <mapnik/params.hpp>
#include <mapnik/boolean.hpp>
int main( int, char*[] )
{
mapnik::parameters params;
// true
//params["bool"] = true;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "true";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
//params["bool"] = 1;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "1";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "True";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "on";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
params["bool"] = "yes";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == true));
// false
//params["bool"] = false;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false) );
params["bool"] = "false";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false) );
//params["bool"] = 0;
//BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "0";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "False";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "off";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
params["bool"] = "no";
BOOST_TEST( (params.get<mapnik::boolean>("bool") && *params.get<mapnik::boolean>("bool") == false));
// strings
params["string"] = "hello";
BOOST_TEST( (params.get<std::string>("string") && *params.get<std::string>("string") == "hello") );
// int
params["int"] = 1;
BOOST_TEST( (params.get<int>("int") && *params.get<int>("int") == 1) );
// double
params["double"] = 1.5;
BOOST_TEST( (params.get<double>("double") && *params.get<double>("double") == 1.5) );
// value_null
params["null"] = mapnik::value_null();
//BOOST_TEST( (params.get<mapnik::value_null>("null")/* && *params.get<mapnik::value_null>("null") == mapnik::value_null()*/) );
if (!::boost::detail::test_errors()) {
std::clog << "C++ parameters: \x1b[1;32m✓ \x1b[0m\n";
#if BOOST_VERSION >= 104600
::boost::detail::report_errors_remind().called_report_errors_function = true;
#endif
} else {
return ::boost::report_errors();
}
}
<|endoftext|> |
<commit_before>#include "instanciate.h"
using namespace Yuni;
namespace Nany
{
namespace Pass
{
namespace Instanciate
{
void SequenceBuilder::tryUnrefObject(uint32_t lvid)
{
auto& frame = atomStack.back();
if (not frame.verify(lvid))
return;
auto& cdef = cdeftable.classdefFollowClassMember(CLID{frame.atomid, lvid});
if (not canBeAcquired(cdef)) // do nothing if builtin
return;
auto* atom = cdeftable.findClassdefAtom(cdef);
if (unlikely(nullptr == atom))
{
ICE() << "invalid atom for 'unref' opcode";
return;
}
if (0 == atom->classinfo.dtor.atomid)
{
if (unlikely(not instanciateAtomClassDestructor(*atom, lvid)))
return;
assert(atom->classinfo.dtor.atomid != 0);
}
if (canGenerateCode())
out.emitUnref(lvid, atom->classinfo.dtor.atomid, atom->classinfo.dtor.instanceid);
}
void SequenceBuilder::visit(const IR::ISA::Operand<IR::ISA::Op::ref>& operands)
{
if (not atomStack.back().verify(operands.lvid))
return;
if (canGenerateCode())
{
if (canBeAcquired(operands.lvid))
out.emitRef(operands.lvid); // manual var acquisition
}
}
} // namespace Instanciate
} // namespace Pass
} // namespace Nany
<commit_msg>suppress spurious err messages when a dtor can't be called<commit_after>#include "instanciate.h"
using namespace Yuni;
namespace Nany
{
namespace Pass
{
namespace Instanciate
{
void SequenceBuilder::tryUnrefObject(uint32_t lvid)
{
auto& frame = atomStack.back();
if (not frame.verify(lvid))
return;
auto& cdef = cdeftable.classdefFollowClassMember(CLID{frame.atomid, lvid});
if (not canBeAcquired(cdef)) // do nothing if builtin
return;
auto* atom = cdeftable.findClassdefAtom(cdef);
if (unlikely(nullptr == atom))
{
ICE() << "invalid atom for 'unref' opcode";
return frame.invalidate(lvid);
}
if (0 == atom->classinfo.dtor.atomid)
{
if (unlikely(not instanciateAtomClassDestructor(*atom, lvid)))
return frame.invalidate(lvid);
assert(atom->classinfo.dtor.atomid != 0);
}
if (canGenerateCode())
out.emitUnref(lvid, atom->classinfo.dtor.atomid, atom->classinfo.dtor.instanceid);
}
void SequenceBuilder::visit(const IR::ISA::Operand<IR::ISA::Op::ref>& operands)
{
if (not atomStack.back().verify(operands.lvid))
return;
if (canGenerateCode())
{
if (canBeAcquired(operands.lvid))
out.emitRef(operands.lvid); // manual var acquisition
}
}
} // namespace Instanciate
} // namespace Pass
} // namespace Nany
<|endoftext|> |
<commit_before>/* Brainfuck interpreter using interpreter and composite patterns :) */
#include <exception>
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <memory>
using namespace std;
struct Data
{
vector<int> array;
int ptr;
};
class AbstractExpression
{
public:
AbstractExpression() {}
virtual ~AbstractExpression() {}
virtual void add(shared_ptr<AbstractExpression>) {}
virtual bool isComposite() {return false;}
virtual void interpret(Data &) = 0;
virtual void parse(const string &) {}
};
class IncrementByte: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.array[data.ptr]++;
}
};
class DecrementByte: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.array[data.ptr]--;
}
};
class IncrementPtr: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.ptr++;
if(data.array.size()==data.ptr) data.array.push_back(0);
}
};
class DecrementPtr: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.ptr--;
if(data.ptr<0) throw out_of_range("Negative value of pointer");
}
};
class Output: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
cout<<char(data.array[data.ptr]);
}
};
class Input: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
char input;
cin>>input;
data.array[data.ptr] = static_cast<char>(input);
}
};
typedef shared_ptr<AbstractExpression> AbstractExpressionPtr;
class CompositeExpression: public AbstractExpression
{
private:
list<AbstractExpressionPtr> expTree;
public:
CompositeExpression(): expTree() {}
virtual ~CompositeExpression() {}
virtual bool isComposite() {return true;}
virtual void add(AbstractExpressionPtr exp) {expTree.push_back(exp);}
virtual void interpret(Data &data) {
for(list<AbstractExpressionPtr>::iterator it=expTree.begin(); it!=expTree.end(); it++) {
if((*it)->isComposite()) {
while(data.array[data.ptr])
(*it)->interpret(data);
}
else {
(*it)->interpret(data);
}
}
}
};
class Parser
{
private:
map<char, AbstractExpressionPtr> expMap;
list<char> chars;
public:
Parser() {
chars.push_back('+'); expMap[chars.back()] = AbstractExpressionPtr(new IncrementByte);
chars.push_back('-'); expMap[chars.back()] = AbstractExpressionPtr(new DecrementByte);
chars.push_back('>'); expMap[chars.back()] = AbstractExpressionPtr(new IncrementPtr);
chars.push_back('<'); expMap[chars.back()] = AbstractExpressionPtr(new DecrementPtr);
chars.push_back('.'); expMap[chars.back()] = AbstractExpressionPtr(new Output);
chars.push_back(','); expMap[chars.back()] = AbstractExpressionPtr(new Input);
}
AbstractExpressionPtr buildTree(const string & code) {
AbstractExpressionPtr syntaxTreePtr(new CompositeExpression);
int skip(0);
for(int i=0; i<code.size(); i++) {
if(skip) {
if(code[i] == '[') skip++;
if(code[i] == ']') skip--;
continue;
}
if(find(chars.begin(), chars.end(), code[i]) != chars.end()) {
syntaxTreePtr->add(expMap[code[i]]);
}
else if (code[i] == '[') {
AbstractExpressionPtr exp = buildTree(code.substr(i+1));
syntaxTreePtr->add(exp);
skip = 1;
}
else if(code[i]==']') break;
}
return syntaxTreePtr;
}
};
int main()
{
Data data; data.array.assign(1,0); data.ptr = 0;
string code("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
//string code(",[.[-],]");
Parser parser;
AbstractExpressionPtr syntaxTreePtr = parser.buildTree(code);
syntaxTreePtr->interpret(data);
}
<commit_msg>Simplify Parser class<commit_after>/* Brainfuck interpreter using interpreter and composite patterns :) */
#include <exception>
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <memory>
using namespace std;
struct Data
{
vector<int> array;
int ptr;
};
class AbstractExpression
{
public:
AbstractExpression() {}
virtual ~AbstractExpression() {}
virtual void add(shared_ptr<AbstractExpression>) {}
virtual bool isComposite() {return false;}
virtual void interpret(Data &) = 0;
virtual void parse(const string &) {}
};
class IncrementByte: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.array[data.ptr]++;
}
};
class DecrementByte: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.array[data.ptr]--;
}
};
class IncrementPtr: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.ptr++;
if(data.array.size()==data.ptr) data.array.push_back(0);
}
};
class DecrementPtr: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
data.ptr--;
if(data.ptr<0) throw out_of_range("Negative value of pointer");
}
};
class Output: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
cout<<char(data.array[data.ptr]);
}
};
class Input: public AbstractExpression
{
public:
virtual void interpret(Data &data) {
char input;
cin>>input;
data.array[data.ptr] = static_cast<char>(input);
}
};
typedef shared_ptr<AbstractExpression> AbstractExpressionPtr;
class CompositeExpression: public AbstractExpression
{
private:
list<AbstractExpressionPtr> expTree;
public:
CompositeExpression(): expTree() {}
virtual ~CompositeExpression() {}
virtual bool isComposite() {return true;}
virtual void add(AbstractExpressionPtr exp) {expTree.push_back(exp);}
virtual void interpret(Data &data) {
for(list<AbstractExpressionPtr>::iterator it=expTree.begin(); it!=expTree.end(); it++) {
if((*it)->isComposite()) {
while(data.array[data.ptr])
(*it)->interpret(data);
}
else {
(*it)->interpret(data);
}
}
}
};
class Parser
{
private:
map<char, AbstractExpressionPtr> expMap;
public:
Parser() {
expMap['+'] = AbstractExpressionPtr(new IncrementByte);
expMap['-'] = AbstractExpressionPtr(new DecrementByte);
expMap['>'] = AbstractExpressionPtr(new IncrementPtr);
expMap['<'] = AbstractExpressionPtr(new DecrementPtr);
expMap['.'] = AbstractExpressionPtr(new Output);
expMap[','] = AbstractExpressionPtr(new Input);
}
AbstractExpressionPtr buildTree(const string & code) {
AbstractExpressionPtr syntaxTreePtr(new CompositeExpression);
int skip(0);
for(int i=0; i<code.size(); i++) {
if(skip) {
if(code[i] == '[') skip++;
if(code[i] == ']') skip--;
continue;
}
if(expMap.find(code[i]) != expMap.end()) {
syntaxTreePtr->add(expMap[code[i]]);
}
else if (code[i] == '[') {
AbstractExpressionPtr exp = buildTree(code.substr(i+1));
syntaxTreePtr->add(exp);
skip = 1;
}
else if(code[i]==']') break;
}
return syntaxTreePtr;
}
};
int main()
{
Data data; data.array.assign(1,0); data.ptr = 0;
string code("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
//string code(",[.[-],]");
Parser parser;
AbstractExpressionPtr syntaxTreePtr = parser.buildTree(code);
syntaxTreePtr->interpret(data);
}
<|endoftext|> |
<commit_before><commit_msg>doubly_linked_list<commit_after><|endoftext|> |
<commit_before>#ifndef BFC_COMBINE_INC_VISITOR_HPP
#define BFC_COMBINE_INC_VISITOR_HPP
#include "ast/mod.hpp"
#include "ast/base.hpp"
#include "test_visitor.hpp"
#include "types.h"
namespace bfc {
namespace ast {
class combine_inc_visitor : public opt_seq_base_visitor {
public:
enum node_type {
ADD = 0,
SUB
};
status visit(add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(const add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
return CONTINUE;
}
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
status visit(const sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
return CONTINUE;
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
private:
class try_combine_inc_visitor : public test_visitor {
public:
try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) :
next_off(offset), next_val(val), isAdd(isAdd) {}
bf_value new_value() {
return new_val;
}
node_type type() {
return type;
}
status visit(add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(const add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
status visit(const sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
private:
bool isAdd;
ptrdiff_t next_off;
bf_value next_val;
bf_value new_val;
node_type type;
};
};
}
}
#endif /* !BFC_COMBINE_INC_VISITOR_HPP */
<commit_msg>Rename var<commit_after>#ifndef BFC_COMBINE_INC_VISITOR_HPP
#define BFC_COMBINE_INC_VISITOR_HPP
#include "ast/mod.hpp"
#include "ast/base.hpp"
#include "test_visitor.hpp"
#include "types.h"
namespace bfc {
namespace ast {
class combine_inc_visitor : public opt_seq_base_visitor {
public:
enum node_type {
ADD = 0,
SUB
};
status visit(add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(const add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
return CONTINUE;
}
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
status visit(const sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value()));
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()));
}
return CONTINUE;
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
private:
class try_combine_inc_visitor : public test_visitor {
public:
try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) :
next_off(offset), next_val(val), isAdd(isAdd) {}
bf_value new_value() {
return new_val;
}
node_type type() {
return this_type;
}
status visit(add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(const add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
status visit(const sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
private:
bool isAdd;
ptrdiff_t next_off;
bf_value next_val;
bf_value new_val;
node_type this_type;
};
};
}
}
#endif /* !BFC_COMBINE_INC_VISITOR_HPP */
<|endoftext|> |
<commit_before>#include "TPAdapter.h"
#include <fstream>
#include <drag2d.h>
namespace libcoco
{
void TPAdapter::Load(const char* filename)
{
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filename);
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
m_width = value["meta"]["size"]["w"].asInt();
m_height = value["meta"]["size"]["h"].asInt();
std::string str = value["meta"]["scale"].asString();
m_invscale = atof(str.c_str());
int i = 0;
Json::Value frameValue = value["frames"][i++];
while (!frameValue.isNull()) {
Entry entry;
Load(frameValue, entry);
m_frames.push_back(entry);
frameValue = value["frames"][i++];
}
}
void TPAdapter::Load(const Json::Value& value, Entry& entry)
{
entry.filename = value["filename"].asString();
StringTools::toLower(entry.filename);
Load(value["frame"], entry.frame);
entry.rotated = value["rotated"].asBool();
entry.trimmed = value["trimmed"].asBool();
Load(value["spriteSourceSize"], entry.sprite_source_size);
entry.src_width = value["sourceSize"]["w"].asInt();
entry.src_height = value["sourceSize"]["h"].asInt();
}
void TPAdapter::Load(const Json::Value& value, Region& region)
{
region.x = value["x"].asInt();
region.y = value["y"].asInt();
region.w = value["w"].asInt();
region.h = value["h"].asInt();
}
} // d2d<commit_msg>[FIXED] 打包时路径\和/的处理<commit_after>#include "TPAdapter.h"
#include <fstream>
#include <drag2d.h>
namespace libcoco
{
void TPAdapter::Load(const char* filename)
{
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filename);
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
m_width = value["meta"]["size"]["w"].asInt();
m_height = value["meta"]["size"]["h"].asInt();
std::string str = value["meta"]["scale"].asString();
m_invscale = atof(str.c_str());
int i = 0;
Json::Value frameValue = value["frames"][i++];
while (!frameValue.isNull()) {
Entry entry;
Load(frameValue, entry);
m_frames.push_back(entry);
frameValue = value["frames"][i++];
}
}
void TPAdapter::Load(const Json::Value& value, Entry& entry)
{
entry.filename = value["filename"].asString();
StringTools::toLower(entry.filename);
d2d::FilenameTools::formatSeparators(entry.filename);
Load(value["frame"], entry.frame);
entry.rotated = value["rotated"].asBool();
entry.trimmed = value["trimmed"].asBool();
Load(value["spriteSourceSize"], entry.sprite_source_size);
entry.src_width = value["sourceSize"]["w"].asInt();
entry.src_height = value["sourceSize"]["h"].asInt();
}
void TPAdapter::Load(const Json::Value& value, Region& region)
{
region.x = value["x"].asInt();
region.y = value["y"].asInt();
region.w = value["w"].asInt();
region.h = value["h"].asInt();
}
} // d2d<|endoftext|> |
<commit_before>#ifndef __CONCURRENCY_CORO_POOL_HPP__
#define __CONCURRENCY_CORO_POOL_HPP__
#include "errors.hpp"
#include "concurrency/queue/passive_producer.hpp"
#include "concurrency/drain_semaphore.hpp"
/* coro_pool_t maintains a bunch of coroutines; when you give it tasks, it
distributes them among the coroutines. It draws its tasks from a
`passive_producer_t<boost::function<void()> >*`. */
class coro_pool_t :
public home_thread_mixin_t,
private watchable_t<bool>::watcher_t
{
public:
coro_pool_t(size_t worker_count_, passive_producer_t<boost::function<void()> > *source) :
source(source),
max_worker_count(worker_count_),
active_worker_count(0)
{
rassert(max_worker_count > 0);
on_watchable_changed(); // Start process if necessary
source->available->add_watcher(this);
}
~coro_pool_t() {
assert_thread();
source->available->remove_watcher(this);
coro_drain_semaphore.drain();
rassert(active_worker_count == 0);
}
void rethread(int new_thread) {
/* Can't rethread while there are active operations */
rassert(active_worker_count == 0);
rassert(!source->available->get());
real_home_thread = new_thread;
}
private:
passive_producer_t<boost::function<void()> > *source;
void on_watchable_changed() {
assert_thread();
while (source->available->get() && active_worker_count < max_worker_count) {
coro_t::spawn_now(boost::bind(
&coro_pool_t::worker_run,
this,
drain_semaphore_t::lock_t(&coro_drain_semaphore)
));
}
}
int max_worker_count, active_worker_count;
drain_semaphore_t coro_drain_semaphore;
void worker_run(UNUSED drain_semaphore_t::lock_t coro_drain_semaphore_lock) {
assert_thread();
++active_worker_count;
rassert(active_worker_count <= max_worker_count);
while (source->available->get()) {
/* Pop the task that we are going to do off the queue */
boost::function<void()> task = source->pop();
task(); // Perform the task
assert_thread(); // Make sure that `task()` didn't mess with us
}
--active_worker_count;
}
};
#endif /* __CONCURRENCY_CORO_POOL_HPP__ */
<commit_msg>Added a note about coro_pool_t.<commit_after>#ifndef __CONCURRENCY_CORO_POOL_HPP__
#define __CONCURRENCY_CORO_POOL_HPP__
#include "errors.hpp"
#include "concurrency/queue/passive_producer.hpp"
#include "concurrency/drain_semaphore.hpp"
/* coro_pool_t maintains a bunch of coroutines; when you give it tasks, it
distributes them among the coroutines. It draws its tasks from a
`passive_producer_t<boost::function<void()> >*`.
Right now, a number of different things depent on the `coro_pool_t` finishing
all of its tasks and draining its `passive_producer_t` before its destructor
returns. */
class coro_pool_t :
public home_thread_mixin_t,
private watchable_t<bool>::watcher_t
{
public:
coro_pool_t(size_t worker_count_, passive_producer_t<boost::function<void()> > *source) :
source(source),
max_worker_count(worker_count_),
active_worker_count(0)
{
rassert(max_worker_count > 0);
on_watchable_changed(); // Start process if necessary
source->available->add_watcher(this);
}
~coro_pool_t() {
assert_thread();
source->available->remove_watcher(this);
coro_drain_semaphore.drain();
rassert(active_worker_count == 0);
}
void rethread(int new_thread) {
/* Can't rethread while there are active operations */
rassert(active_worker_count == 0);
rassert(!source->available->get());
real_home_thread = new_thread;
}
private:
passive_producer_t<boost::function<void()> > *source;
void on_watchable_changed() {
assert_thread();
while (source->available->get() && active_worker_count < max_worker_count) {
coro_t::spawn_now(boost::bind(
&coro_pool_t::worker_run,
this,
drain_semaphore_t::lock_t(&coro_drain_semaphore)
));
}
}
int max_worker_count, active_worker_count;
drain_semaphore_t coro_drain_semaphore;
void worker_run(UNUSED drain_semaphore_t::lock_t coro_drain_semaphore_lock) {
assert_thread();
++active_worker_count;
rassert(active_worker_count <= max_worker_count);
while (source->available->get()) {
/* Pop the task that we are going to do off the queue */
boost::function<void()> task = source->pop();
task(); // Perform the task
assert_thread(); // Make sure that `task()` didn't mess with us
}
--active_worker_count;
}
};
#endif /* __CONCURRENCY_CORO_POOL_HPP__ */
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "asgard/driver.hpp"
extern "C" {
#include <lirc/lirc_client.h>
}
namespace {
// Configuration (this should be in a configuration file)
const char* server_socket_path = "/tmp/asgard_socket";
const char* client_socket_path = "/tmp/asgard_ir_socket";
asgard::driver_connector driver;
// The remote IDs
int source_id = -1;
int button_actuator_id = -1;
void stop(){
std::cout << "asgard:ir: stop the driver" << std::endl;
//Closes LIRC
lirc_deinit();
asgard::unregister_actuator(driver, source_id, button_actuator_id);
asgard::unregister_source(driver, source_id);
// Unlink the client socket
unlink(client_socket_path);
// Close the socket
close(driver.socket_fd);
}
void terminate(int){
stop();
std::exit(0);
}
void ir_received(char* raw_code){
std::string full_code(raw_code);
auto code_end = full_code.find(' ');
std::string code(full_code.begin(), full_code.begin() + code_end);
auto repeat_end = full_code.find(' ', code_end + 1);
std::string repeat(full_code.begin() + code_end + 1, full_code.begin() + repeat_end);
auto key_end = full_code.find(' ', repeat_end + 1);
std::string key(full_code.begin() + repeat_end + 1, full_code.begin() + key_end);
std::cout << "asgard:ir: Received: " << code << ":" << repeat << ":" << key << std::endl;
asgard::send_event(driver, source_id, button_actuator_id, key);
}
} //End of anonymous namespace
int main(){
//Initiate LIRC. Exit on failure
char lirc_name[] = "lirc";
if(lirc_init(lirc_name, 1) == -1){
std::cout << "asgard:ir: Failed to init LIRC" << std::endl;
return 1;
}
// Open the connection
if(!asgard::open_driver_connection(driver, client_socket_path, server_socket_path)){
return 1;
}
//Register signals for "proper" shutdown
signal(SIGTERM, terminate);
signal(SIGINT, terminate);
// Register the source and sensors
source_id = asgard::register_source(driver, "ir");
button_actuator_id = asgard::register_actuator(driver, source_id, "ir_button_1");
//Read the default LIRC config
struct lirc_config* config;
if(lirc_readconfig(NULL,&config,NULL)==0){
char* code;
//Do stuff while LIRC socket is open 0=open -1=closed.
while(lirc_nextcode(&code)==0){
//If code = NULL, nothing was returned from LIRC socket
if(code){
//Send code further
ir_received(code);
//Need to free up code before the next loop
free(code);
}
}
//Frees the data structures associated with config.
lirc_freeconfig(config);
} else {
std::cout << "asgard:ir: Failed to read LIRC config" << std::endl;
}
stop();
return 0;
}
<commit_msg>Use PI configuration file<commit_after>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "asgard/driver.hpp"
extern "C" {
#include <lirc/lirc_client.h>
}
namespace {
std::vector<asgard::KeyValue> config;
asgard::driver_connector driver;
// The remote IDs
int source_id = -1;
int button_actuator_id = -1;
void stop(){
std::cout << "asgard:ir: stop the driver" << std::endl;
//Closes LIRC
lirc_deinit();
asgard::unregister_actuator(driver, source_id, button_actuator_id);
asgard::unregister_source(driver, source_id);
// Unlink the client socket
unlink(asgard::get_string_value(config, "ir_client_socket_path"));
// Close the socket
close(driver.socket_fd);
}
void terminate(int){
stop();
std::exit(0);
}
void ir_received(char* raw_code){
std::string full_code(raw_code);
auto code_end = full_code.find(' ');
std::string code(full_code.begin(), full_code.begin() + code_end);
auto repeat_end = full_code.find(' ', code_end + 1);
std::string repeat(full_code.begin() + code_end + 1, full_code.begin() + repeat_end);
auto key_end = full_code.find(' ', repeat_end + 1);
std::string key(full_code.begin() + repeat_end + 1, full_code.begin() + key_end);
std::cout << "asgard:ir: Received: " << code << ":" << repeat << ":" << key << std::endl;
asgard::send_event(driver, source_id, button_actuator_id, key);
}
} //End of anonymous namespace
int main(){
//Initiate LIRC. Exit on failure
char lirc_name[] = "lirc";
if(lirc_init(lirc_name, 1) == -1){
std::cout << "asgard:ir: Failed to init LIRC" << std::endl;
return 1;
}
load_config(config);
// Open the connection
if(!asgard::open_driver_connection(driver, asgard::get_string_value(config, "ir_client_socket_path"), asgard::get_string_value(config, "server_socket_path"))){
return 1;
}
//Register signals for "proper" shutdown
signal(SIGTERM, terminate);
signal(SIGINT, terminate);
// Register the source and sensors
source_id = asgard::register_source(driver, "ir");
button_actuator_id = asgard::register_actuator(driver, source_id, "ir_button_1");
//Read the default LIRC config
struct lirc_config* config;
if(lirc_readconfig(NULL,&config,NULL)==0){
char* code;
//Do stuff while LIRC socket is open 0=open -1=closed.
while(lirc_nextcode(&code)==0){
//If code = NULL, nothing was returned from LIRC socket
if(code){
//Send code further
ir_received(code);
//Need to free up code before the next loop
free(code);
}
}
//Frees the data structures associated with config.
lirc_freeconfig(config);
} else {
std::cout << "asgard:ir: Failed to read LIRC config" << std::endl;
}
stop();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/watchable.hpp"
#include <functional>
#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include "concurrency/cond_var.hpp"
#include "concurrency/wait_any.hpp"
template <class result_type, class outer_type, class callable_type>
class subview_watchable_t : public watchable_t<result_type> {
public:
subview_watchable_t(const callable_type &l, watchable_t<outer_type> *p) :
cache(new lensed_value_cache_t(l, p)) { }
subview_watchable_t *clone() const {
return new subview_watchable_t(cache);
}
result_type get() {
return *cache->get();
}
virtual void apply_read(const std::function<void(const result_type*)> &read) {
ASSERT_NO_CORO_WAITING;
read(cache->get());
}
publisher_t<boost::function<void()> > *get_publisher() {
return cache->get_publisher();
}
rwi_lock_assertion_t *get_rwi_lock_assertion() {
return cache->parent->get_rwi_lock_assertion();
}
private:
// TODO (daniel): Document how incremental lenses work.
class lensed_value_cache_t : public home_thread_mixin_t {
public:
lensed_value_cache_t(const callable_type &l, watchable_t<outer_type> *p) :
parent(p->clone()),
lens(l),
parent_subscription(boost::bind(
&subview_watchable_t<result_type, outer_type, callable_type>::lensed_value_cache_t::on_parent_changed,
this), parent->get_publisher()) {
compute_value();
}
~lensed_value_cache_t() {
assert_thread();
}
const result_type *get() {
assert_thread();
return &cached_value;
}
publisher_t<boost::function<void()> > *get_publisher() {
assert_thread();
return publisher_controller.get_publisher();
}
clone_ptr_t<watchable_t<outer_type> > parent;
private:
bool compute_value() {
// The closure is to avoid copying the whole value from the parent.
bool value_changed = false;
/* C++11: auto op = [&] (const outer_type *val) -> void { ... }
Because we cannot use C++11 lambdas yet due to missing support in
GCC 4.4, this is the messy work-around: */
struct op_closure_t {
void operator()(const outer_type *val) {
value_changed = lens(*val, &cached_value);
}
op_closure_t(callable_type &c1, bool &c2, result_type &c3) :
lens(c1),
value_changed(c2),
cached_value(c3) {
}
callable_type &lens;
bool &value_changed;
result_type &cached_value;
};
op_closure_t op(lens, value_changed, cached_value);
parent->apply_read(std::bind(&op_closure_t::operator(), &op, std::placeholders::_1));
return value_changed;
}
void on_parent_changed() {
assert_thread();
const bool value_changed = compute_value();
if (value_changed) {
publisher_controller.publish(&call_function);
}
}
callable_type lens;
result_type cached_value;
publisher_controller_t<boost::function<void()> > publisher_controller;
publisher_t<boost::function<void()> >::subscription_t parent_subscription;
};
subview_watchable_t(const boost::shared_ptr<lensed_value_cache_t> &_cache) :
cache(_cache) { }
boost::shared_ptr<lensed_value_cache_t> cache;
};
// TODO! Document
template<class outer_type, class callable_type>
class non_incremental_lens_wrapper_t {
public:
typedef typename boost::result_of<callable_type(outer_type)>::type result_type;
explicit non_incremental_lens_wrapper_t(const callable_type &_inner) :
inner(_inner) {
}
bool operator()(const outer_type &input, result_type *current_out) {
guarantee(current_out != NULL);
result_type old_value = *current_out;
*current_out = inner(input);
return old_value != *current_out;
}
private:
callable_type inner;
};
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename callable_type::result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<typename callable_type::result_type> >(
new subview_watchable_t<typename callable_type::result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class result_type, class callable_type>
clone_ptr_t<watchable_t<result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<result_type> >(
new subview_watchable_t<result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename boost::result_of<callable_type(value_type)>::type> > watchable_t<value_type>::subview(const callable_type &lens) {
assert_thread();
typedef non_incremental_lens_wrapper_t<value_type, callable_type> wrapped_callable_type;
wrapped_callable_type wrapped_lens(lens);
return clone_ptr_t<watchable_t<typename wrapped_callable_type::result_type> >(
new subview_watchable_t<typename wrapped_callable_type::result_type, value_type, wrapped_callable_type>(wrapped_lens, this));
}
template<class value_type>
template<class callable_type>
void watchable_t<value_type>::run_until_satisfied(const callable_type &fun, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
assert_thread();
clone_ptr_t<watchable_t<value_type> > clone_this(this->clone());
while (true) {
cond_t changed;
typename watchable_t<value_type>::subscription_t subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<value_type>::freeze_t freeze(clone_this);
ASSERT_FINITE_CORO_WAITING;
if (fun(clone_this->get())) {
return;
}
subs.reset(clone_this, &freeze);
}
wait_interruptible(&changed, interruptor);
}
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2(
const clone_ptr_t<watchable_t<a_type> > &a,
const clone_ptr_t<watchable_t<b_type> > &b,
const callable_type &fun,
signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
a->assert_thread();
b->assert_thread();
while (true) {
cond_t changed;
typename watchable_t<a_type>::subscription_t a_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
typename watchable_t<b_type>::subscription_t b_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<a_type>::freeze_t a_freeze(a);
typename watchable_t<b_type>::freeze_t b_freeze(b);
ASSERT_FINITE_CORO_WAITING;
if (fun(a->get(), b->get())) {
return;
}
a_subs.reset(a, &a_freeze);
b_subs.reset(b, &b_freeze);
}
wait_interruptible(&changed, interruptor);
}
}
<commit_msg>Use watchable subscription_t together with a freeze_t in subview_watchable_t constructor.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/watchable.hpp"
#include <functional>
#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include "concurrency/cond_var.hpp"
#include "concurrency/wait_any.hpp"
template <class result_type, class outer_type, class callable_type>
class subview_watchable_t : public watchable_t<result_type> {
public:
subview_watchable_t(const callable_type &l, watchable_t<outer_type> *p) :
cache(new lensed_value_cache_t(l, p)) { }
subview_watchable_t *clone() const {
return new subview_watchable_t(cache);
}
result_type get() {
return *cache->get();
}
virtual void apply_read(const std::function<void(const result_type*)> &read) {
ASSERT_NO_CORO_WAITING;
read(cache->get());
}
publisher_t<boost::function<void()> > *get_publisher() {
return cache->get_publisher();
}
rwi_lock_assertion_t *get_rwi_lock_assertion() {
return cache->parent->get_rwi_lock_assertion();
}
private:
// TODO (daniel): Document how incremental lenses work.
class lensed_value_cache_t : public home_thread_mixin_t {
public:
lensed_value_cache_t(const callable_type &l, watchable_t<outer_type> *p) :
parent(p->clone()),
lens(l),
parent_subscription(boost::bind(
&subview_watchable_t<result_type, outer_type, callable_type>::lensed_value_cache_t::on_parent_changed,
this)) {
typename watchable_t<outer_type>::freeze_t freeze(parent);
ASSERT_FINITE_CORO_WAITING;
compute_value();
parent_subscription.reset(parent, &freeze);
}
~lensed_value_cache_t() {
assert_thread();
}
const result_type *get() {
assert_thread();
return &cached_value;
}
publisher_t<boost::function<void()> > *get_publisher() {
assert_thread();
return publisher_controller.get_publisher();
}
clone_ptr_t<watchable_t<outer_type> > parent;
private:
bool compute_value() {
// The closure is to avoid copying the whole value from the parent.
bool value_changed = false;
/* C++11: auto op = [&] (const outer_type *val) -> void { ... }
Because we cannot use C++11 lambdas yet due to missing support in
GCC 4.4, this is the messy work-around: */
struct op_closure_t {
void operator()(const outer_type *val) {
value_changed = lens(*val, &cached_value);
}
op_closure_t(callable_type &c1, bool &c2, result_type &c3) :
lens(c1),
value_changed(c2),
cached_value(c3) {
}
callable_type &lens;
bool &value_changed;
result_type &cached_value;
};
op_closure_t op(lens, value_changed, cached_value);
parent->apply_read(std::bind(&op_closure_t::operator(), &op, std::placeholders::_1));
return value_changed;
}
void on_parent_changed() {
assert_thread();
const bool value_changed = compute_value();
if (value_changed) {
publisher_controller.publish(&call_function);
}
}
callable_type lens;
result_type cached_value;
publisher_controller_t<boost::function<void()> > publisher_controller;
typename watchable_t<outer_type>::subscription_t parent_subscription;
};
subview_watchable_t(const boost::shared_ptr<lensed_value_cache_t> &_cache) :
cache(_cache) { }
boost::shared_ptr<lensed_value_cache_t> cache;
};
// TODO! Document
template<class outer_type, class callable_type>
class non_incremental_lens_wrapper_t {
public:
typedef typename boost::result_of<callable_type(outer_type)>::type result_type;
explicit non_incremental_lens_wrapper_t(const callable_type &_inner) :
inner(_inner) {
}
bool operator()(const outer_type &input, result_type *current_out) {
guarantee(current_out != NULL);
result_type old_value = *current_out;
*current_out = inner(input);
return old_value != *current_out;
}
private:
callable_type inner;
};
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename callable_type::result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<typename callable_type::result_type> >(
new subview_watchable_t<typename callable_type::result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class result_type, class callable_type>
clone_ptr_t<watchable_t<result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<result_type> >(
new subview_watchable_t<result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename boost::result_of<callable_type(value_type)>::type> > watchable_t<value_type>::subview(const callable_type &lens) {
assert_thread();
typedef non_incremental_lens_wrapper_t<value_type, callable_type> wrapped_callable_type;
wrapped_callable_type wrapped_lens(lens);
return clone_ptr_t<watchable_t<typename wrapped_callable_type::result_type> >(
new subview_watchable_t<typename wrapped_callable_type::result_type, value_type, wrapped_callable_type>(wrapped_lens, this));
}
template<class value_type>
template<class callable_type>
void watchable_t<value_type>::run_until_satisfied(const callable_type &fun, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
assert_thread();
clone_ptr_t<watchable_t<value_type> > clone_this(this->clone());
while (true) {
cond_t changed;
typename watchable_t<value_type>::subscription_t subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<value_type>::freeze_t freeze(clone_this);
ASSERT_FINITE_CORO_WAITING;
if (fun(clone_this->get())) {
return;
}
subs.reset(clone_this, &freeze);
}
wait_interruptible(&changed, interruptor);
}
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2(
const clone_ptr_t<watchable_t<a_type> > &a,
const clone_ptr_t<watchable_t<b_type> > &b,
const callable_type &fun,
signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
a->assert_thread();
b->assert_thread();
while (true) {
cond_t changed;
typename watchable_t<a_type>::subscription_t a_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
typename watchable_t<b_type>::subscription_t b_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<a_type>::freeze_t a_freeze(a);
typename watchable_t<b_type>::freeze_t b_freeze(b);
ASSERT_FINITE_CORO_WAITING;
if (fun(a->get(), b->get())) {
return;
}
a_subs.reset(a, &a_freeze);
b_subs.reset(b, &b_freeze);
}
wait_interruptible(&changed, interruptor);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cacheoptions.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:11:42 $
*
* 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
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_CACHEOPTIONS_HXX
#define INCLUDED_SVTOOLS_CACHEOPTIONS_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtCacheOptions_Impl;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about startup features
@descr -
@implements -
@base -
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVL_DLLPUBLIC SvtCacheOptions
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtCacheOptions();
~SvtCacheOptions();
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short interface methods to get and set value of config key "org.openoffice.Office.Common/_3D-Engine/..."
@descr These options describe internal states to enable/disable features of installed office.
GetWriterOLE_Objects()
SetWriterOLE_Objects() => set the number of Writer OLE objects to be cached
GetDrawingEngineOLE_Objects()
SetDrawingEngineOLE_Objects() => set the number of DrawingEngine OLE objects to be cached
GetGraphicManagerTotalCacheSize()
SetGraphicManagerTotalCacheSize() => set the maximum cache size used by GraphicManager to cache graphic objects
GetGraphicManagerObjectCacheSize()
SetGraphicManagerObjectCacheSize() => set the maximum cache size for one GraphicObject to be cached by GraphicManager
@seealso configuration package "org.openoffice.Office.Common/_3D-Engine"
*//*-*****************************************************************************************************/
sal_Int32 GetWriterOLE_Objects() const;
sal_Int32 GetDrawingEngineOLE_Objects() const;
sal_Int32 GetGraphicManagerTotalCacheSize() const;
sal_Int32 GetGraphicManagerObjectCacheSize() const;
sal_Int32 GetGraphicManagerObjectReleaseTime() const;
void SetWriterOLE_Objects( sal_Int32 nObjects );
void SetDrawingEngineOLE_Objects( sal_Int32 nObjects );
void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize );
void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize );
void SetGraphicManagerObjectReleaseTime( sal_Int32 nReleaseTimeSeconds );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class use his own static mutex to be threadsafe.
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVL_DLLPRIVATE static ::osl::Mutex& GetOwnStaticMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtCacheOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtOptions3D
#endif // #ifndef INCLUDED_SVTOOLS_CACHEOPTIONS_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.4.62); FILE MERGED 2005/10/25 12:43:51 pl 1.4.62.1: #i55991# removed warnings for linux platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cacheoptions.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 20:11:10 $
*
* 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
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_CACHEOPTIONS_HXX
#define INCLUDED_SVTOOLS_CACHEOPTIONS_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtCacheOptions_Impl;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about startup features
@descr -
@implements -
@base -
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVL_DLLPUBLIC SvtCacheOptions
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtCacheOptions();
~SvtCacheOptions();
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short interface methods to get and set value of config key "org.openoffice.Office.Common/_3D-Engine/..."
@descr These options describe internal states to enable/disable features of installed office.
GetWriterOLE_Objects()
SetWriterOLE_Objects() => set the number of Writer OLE objects to be cached
GetDrawingEngineOLE_Objects()
SetDrawingEngineOLE_Objects() => set the number of DrawingEngine OLE objects to be cached
GetGraphicManagerTotalCacheSize()
SetGraphicManagerTotalCacheSize() => set the maximum cache size used by GraphicManager to cache graphic objects
GetGraphicManagerObjectCacheSize()
SetGraphicManagerObjectCacheSize() => set the maximum cache size for one GraphicObject to be cached by GraphicManager
@seealso configuration package "org.openoffice.Office.Common/_3D-Engine"
*//*-*****************************************************************************************************/
sal_Int32 GetWriterOLE_Objects() const;
sal_Int32 GetDrawingEngineOLE_Objects() const;
sal_Int32 GetGraphicManagerTotalCacheSize() const;
sal_Int32 GetGraphicManagerObjectCacheSize() const;
sal_Int32 GetGraphicManagerObjectReleaseTime() const;
void SetWriterOLE_Objects( sal_Int32 nObjects );
void SetDrawingEngineOLE_Objects( sal_Int32 nObjects );
void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize );
void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize );
void SetGraphicManagerObjectReleaseTime( sal_Int32 nReleaseTimeSeconds );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class use his own static mutex to be threadsafe.
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVL_DLLPRIVATE static ::osl::Mutex& GetOwnStaticMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtCacheOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtOptions3D
#endif // #ifndef INCLUDED_SVTOOLS_CACHEOPTIONS_HXX
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <chrono>
#include <thread>
#include <xmmintrin.h>
#include "engine.hpp"
#include "util.hpp"
namespace rack {
float sampleRate;
float sampleTime;
bool gPaused = false;
static bool running = false;
static std::mutex mutex;
static std::thread thread;
static VIPMutex vipMutex;
static std::vector<Module*> modules;
static std::vector<Wire*> wires;
// Parameter interpolation
static Module *smoothModule = NULL;
static int smoothParamId;
static float smoothValue;
float Light::getBrightness() {
return sqrtf(fmaxf(0.0, value));
}
void Light::setBrightnessSmooth(float brightness) {
// lambda = 3 * framerate
value += (brightness * brightness - value) * sampleTime * (60.0 * 3.0);
}
void Wire::step() {
float value = outputModule->outputs[outputId].value;
inputModule->inputs[inputId].value = value;
}
void engineInit() {
engineSetSampleRate(44100.0);
}
void engineDestroy() {
// Make sure there are no wires or modules in the rack on destruction. This suggests that a module failed to remove itself before the GUI was destroyed.
assert(wires.empty());
assert(modules.empty());
}
static void engineStep() {
// Param interpolation
if (smoothModule) {
float value = smoothModule->params[smoothParamId].value;
const float lambda = 60.0; // decay rate is 1 graphics frame
const float snap = 0.0001;
float delta = smoothValue - value;
if (fabsf(delta) < snap) {
smoothModule->params[smoothParamId].value = smoothValue;
smoothModule = NULL;
}
else {
value += delta * lambda * sampleTime;
smoothModule->params[smoothParamId].value = value;
}
}
// Step modules
for (Module *module : modules) {
module->step();
}
// Step cables by moving their output values to inputs
for (Wire *wire : wires) {
wire->step();
}
}
static void engineRun() {
// Set CPU to denormals-are-zero mode
// http://carlh.net/plugins/denormals.php
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
// Every time the engine waits and locks a mutex, it steps this many frames
const int mutexSteps = 64;
// Time in seconds that the engine is rushing ahead of the estimated clock time
double ahead = 0.0;
auto lastTime = std::chrono::high_resolution_clock::now();
while (running) {
vipMutex.wait();
if (!gPaused) {
std::lock_guard<std::mutex> lock(mutex);
for (int i = 0; i < mutexSteps; i++) {
engineStep();
}
}
double stepTime = mutexSteps * sampleTime;
ahead += stepTime;
auto currTime = std::chrono::high_resolution_clock::now();
const double aheadFactor = 2.0;
ahead -= aheadFactor * std::chrono::duration<double>(currTime - lastTime).count();
lastTime = currTime;
ahead = fmaxf(ahead, 0.0);
// Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate
// The number of steps to wait before possibly sleeping
const double aheadMax = 1.0; // seconds
if (ahead > aheadMax) {
std::this_thread::sleep_for(std::chrono::duration<double>(stepTime));
}
}
}
void engineStart() {
running = true;
thread = std::thread(engineRun);
}
void engineStop() {
running = false;
thread.join();
}
void engineAddModule(Module *module) {
assert(module);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Check that the module is not already added
auto it = std::find(modules.begin(), modules.end(), module);
assert(it == modules.end());
modules.push_back(module);
}
void engineRemoveModule(Module *module) {
assert(module);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// If a param is being smoothed on this module, stop smoothing it immediately
if (module == smoothModule) {
smoothModule = NULL;
}
// Check that all wires are disconnected
for (Wire *wire : wires) {
assert(wire->outputModule != module);
assert(wire->inputModule != module);
}
// Check that the module actually exists
auto it = std::find(modules.begin(), modules.end(), module);
assert(it != modules.end());
// Remove it
modules.erase(it);
}
static void updateActive() {
// Set everything to inactive
for (Module *module : modules) {
for (Input &input : module->inputs) {
input.active = false;
}
for (Output &output : module->outputs) {
output.active = false;
}
}
// Set inputs/outputs to active
for (Wire *wire : wires) {
wire->outputModule->outputs[wire->outputId].active = true;
wire->inputModule->inputs[wire->inputId].active = true;
}
}
void engineAddWire(Wire *wire) {
assert(wire);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Check wire properties
assert(wire->outputModule);
assert(wire->inputModule);
// Check that the wire is not already added, and that the input is not already used by another cable
for (Wire *wire2 : wires) {
assert(wire2 != wire);
assert(!(wire2->inputModule == wire->inputModule && wire2->inputId == wire->inputId));
}
// Add the wire
wires.push_back(wire);
updateActive();
}
void engineRemoveWire(Wire *wire) {
assert(wire);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Check that the wire is already added
auto it = std::find(wires.begin(), wires.end(), wire);
assert(it != wires.end());
// Set input to 0V
wire->inputModule->inputs[wire->inputId].value = 0.0;
// Remove the wire
wires.erase(it);
updateActive();
}
void engineSetParam(Module *module, int paramId, float value) {
module->params[paramId].value = value;
}
void engineSetParamSmooth(Module *module, int paramId, float value) {
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Since only one param can be smoothed at a time, if another param is currently being smoothed, skip to its final state
if (smoothModule && !(smoothModule == module && smoothParamId == paramId)) {
smoothModule->params[smoothParamId].value = smoothValue;
}
smoothModule = module;
smoothParamId = paramId;
smoothValue = value;
}
void engineSetSampleRate(float newSampleRate) {
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
sampleRate = newSampleRate;
sampleTime = 1.0 / sampleRate;
// onSampleRateChange
for (Module *module : modules) {
module->onSampleRateChange();
}
}
float engineGetSampleRate() {
return sampleRate;
}
float engineGetSampleTime() {
return sampleTime;
}
} // namespace rack
<commit_msg>Light::setBrightnessSmooth() turns on high values immediately, fades out low values<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <chrono>
#include <thread>
#include <xmmintrin.h>
#include "engine.hpp"
#include "util.hpp"
namespace rack {
float sampleRate;
float sampleTime;
bool gPaused = false;
static bool running = false;
static std::mutex mutex;
static std::thread thread;
static VIPMutex vipMutex;
static std::vector<Module*> modules;
static std::vector<Wire*> wires;
// Parameter interpolation
static Module *smoothModule = NULL;
static int smoothParamId;
static float smoothValue;
float Light::getBrightness() {
return sqrtf(fmaxf(0.0, value));
}
void Light::setBrightnessSmooth(float brightness) {
float v = brightness * brightness;
if (v < value) {
// Fade out light with lambda = 3 * framerate
value += (v - value) * sampleTime * (60.0 * 3.0);
}
else {
// Immediately illuminate light
value = v;
}
}
void Wire::step() {
float value = outputModule->outputs[outputId].value;
inputModule->inputs[inputId].value = value;
}
void engineInit() {
engineSetSampleRate(44100.0);
}
void engineDestroy() {
// Make sure there are no wires or modules in the rack on destruction. This suggests that a module failed to remove itself before the GUI was destroyed.
assert(wires.empty());
assert(modules.empty());
}
static void engineStep() {
// Param interpolation
if (smoothModule) {
float value = smoothModule->params[smoothParamId].value;
const float lambda = 60.0; // decay rate is 1 graphics frame
const float snap = 0.0001;
float delta = smoothValue - value;
if (fabsf(delta) < snap) {
smoothModule->params[smoothParamId].value = smoothValue;
smoothModule = NULL;
}
else {
value += delta * lambda * sampleTime;
smoothModule->params[smoothParamId].value = value;
}
}
// Step modules
for (Module *module : modules) {
module->step();
}
// Step cables by moving their output values to inputs
for (Wire *wire : wires) {
wire->step();
}
}
static void engineRun() {
// Set CPU to denormals-are-zero mode
// http://carlh.net/plugins/denormals.php
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
// Every time the engine waits and locks a mutex, it steps this many frames
const int mutexSteps = 64;
// Time in seconds that the engine is rushing ahead of the estimated clock time
double ahead = 0.0;
auto lastTime = std::chrono::high_resolution_clock::now();
while (running) {
vipMutex.wait();
if (!gPaused) {
std::lock_guard<std::mutex> lock(mutex);
for (int i = 0; i < mutexSteps; i++) {
engineStep();
}
}
double stepTime = mutexSteps * sampleTime;
ahead += stepTime;
auto currTime = std::chrono::high_resolution_clock::now();
const double aheadFactor = 2.0;
ahead -= aheadFactor * std::chrono::duration<double>(currTime - lastTime).count();
lastTime = currTime;
ahead = fmaxf(ahead, 0.0);
// Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate
// The number of steps to wait before possibly sleeping
const double aheadMax = 1.0; // seconds
if (ahead > aheadMax) {
std::this_thread::sleep_for(std::chrono::duration<double>(stepTime));
}
}
}
void engineStart() {
running = true;
thread = std::thread(engineRun);
}
void engineStop() {
running = false;
thread.join();
}
void engineAddModule(Module *module) {
assert(module);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Check that the module is not already added
auto it = std::find(modules.begin(), modules.end(), module);
assert(it == modules.end());
modules.push_back(module);
}
void engineRemoveModule(Module *module) {
assert(module);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// If a param is being smoothed on this module, stop smoothing it immediately
if (module == smoothModule) {
smoothModule = NULL;
}
// Check that all wires are disconnected
for (Wire *wire : wires) {
assert(wire->outputModule != module);
assert(wire->inputModule != module);
}
// Check that the module actually exists
auto it = std::find(modules.begin(), modules.end(), module);
assert(it != modules.end());
// Remove it
modules.erase(it);
}
static void updateActive() {
// Set everything to inactive
for (Module *module : modules) {
for (Input &input : module->inputs) {
input.active = false;
}
for (Output &output : module->outputs) {
output.active = false;
}
}
// Set inputs/outputs to active
for (Wire *wire : wires) {
wire->outputModule->outputs[wire->outputId].active = true;
wire->inputModule->inputs[wire->inputId].active = true;
}
}
void engineAddWire(Wire *wire) {
assert(wire);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Check wire properties
assert(wire->outputModule);
assert(wire->inputModule);
// Check that the wire is not already added, and that the input is not already used by another cable
for (Wire *wire2 : wires) {
assert(wire2 != wire);
assert(!(wire2->inputModule == wire->inputModule && wire2->inputId == wire->inputId));
}
// Add the wire
wires.push_back(wire);
updateActive();
}
void engineRemoveWire(Wire *wire) {
assert(wire);
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Check that the wire is already added
auto it = std::find(wires.begin(), wires.end(), wire);
assert(it != wires.end());
// Set input to 0V
wire->inputModule->inputs[wire->inputId].value = 0.0;
// Remove the wire
wires.erase(it);
updateActive();
}
void engineSetParam(Module *module, int paramId, float value) {
module->params[paramId].value = value;
}
void engineSetParamSmooth(Module *module, int paramId, float value) {
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
// Since only one param can be smoothed at a time, if another param is currently being smoothed, skip to its final state
if (smoothModule && !(smoothModule == module && smoothParamId == paramId)) {
smoothModule->params[smoothParamId].value = smoothValue;
}
smoothModule = module;
smoothParamId = paramId;
smoothValue = value;
}
void engineSetSampleRate(float newSampleRate) {
VIPLock vipLock(vipMutex);
std::lock_guard<std::mutex> lock(mutex);
sampleRate = newSampleRate;
sampleTime = 1.0 / sampleRate;
// onSampleRateChange
for (Module *module : modules) {
module->onSampleRateChange();
}
}
float engineGetSampleRate() {
return sampleRate;
}
float engineGetSampleTime() {
return sampleTime;
}
} // namespace rack
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: e3ditem.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:11:15 $
*
* 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
*
************************************************************************/
#ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_
#include <com/sun/star/drawing/Direction3D.hpp>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#include "e3ditem.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
DBG_NAMEEX(SvxVector3DItem);
DBG_NAME(SvxVector3DItem);
// -----------------------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxVector3DItem, SfxPoolItem);
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem()
{
DBG_CTOR(SvxVector3DItem, 0);
}
SvxVector3DItem::~SvxVector3DItem()
{
DBG_DTOR(SvxVector3DItem, 0);
}
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem( USHORT _nWhich, const Vector3D& rVal ) :
SfxPoolItem( _nWhich ),
aVal( rVal )
{
DBG_CTOR(SvxVector3DItem, 0);
}
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem( USHORT _nWhich, SvStream& rStream ) :
SfxPoolItem( _nWhich )
{
DBG_CTOR(SvxVector3DItem, 0);
rStream >> aVal;
}
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem( const SvxVector3DItem& rItem ) :
SfxPoolItem( rItem ),
aVal( rItem.aVal )
{
DBG_CTOR(SvxVector3DItem, 0);
}
// -----------------------------------------------------------------------
int SvxVector3DItem::operator==( const SfxPoolItem &rItem ) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
return ((SvxVector3DItem&)rItem).aVal == aVal;
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxVector3DItem::Clone( SfxItemPool * ) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
return new SvxVector3DItem( *this );
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxVector3DItem::Create(SvStream &rStream, USHORT /*nVersion*/) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
Vector3D aStr;
rStream >> aStr;
return new SvxVector3DItem(Which(), aStr);
}
// -----------------------------------------------------------------------
SvStream& SvxVector3DItem::Store(SvStream &rStream, USHORT /*nItemVersion*/) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
// ## if (nItemVersion)
rStream << aVal;
return rStream;
}
// -----------------------------------------------------------------------
sal_Bool SvxVector3DItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
drawing::Direction3D aDirection;
// Werte eintragen
aDirection.DirectionX = aVal.X();
aDirection.DirectionY = aVal.Y();
aDirection.DirectionZ = aVal.Z();
rVal <<= aDirection;
return( sal_True );
}
// -----------------------------------------------------------------------
sal_Bool SvxVector3DItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
drawing::Direction3D aDirection;
if(!(rVal >>= aDirection))
return sal_False;
aVal.X() = aDirection.DirectionX;
aVal.Y() = aDirection.DirectionY;
aVal.Z() = aDirection.DirectionZ;
return sal_True;
}
// -----------------------------------------------------------------------
USHORT SvxVector3DItem::GetVersion (USHORT nFileFormatVersion) const
{
return (nFileFormatVersion == SOFFICE_FILEFORMAT_31) ? USHRT_MAX : 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.114); FILE MERGED 2006/09/01 17:46:59 kaib 1.5.114.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: e3ditem.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:19:29 $
*
* 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_svx.hxx"
#ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_
#include <com/sun/star/drawing/Direction3D.hpp>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#include "e3ditem.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
DBG_NAMEEX(SvxVector3DItem);
DBG_NAME(SvxVector3DItem);
// -----------------------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxVector3DItem, SfxPoolItem);
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem()
{
DBG_CTOR(SvxVector3DItem, 0);
}
SvxVector3DItem::~SvxVector3DItem()
{
DBG_DTOR(SvxVector3DItem, 0);
}
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem( USHORT _nWhich, const Vector3D& rVal ) :
SfxPoolItem( _nWhich ),
aVal( rVal )
{
DBG_CTOR(SvxVector3DItem, 0);
}
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem( USHORT _nWhich, SvStream& rStream ) :
SfxPoolItem( _nWhich )
{
DBG_CTOR(SvxVector3DItem, 0);
rStream >> aVal;
}
// -----------------------------------------------------------------------
SvxVector3DItem::SvxVector3DItem( const SvxVector3DItem& rItem ) :
SfxPoolItem( rItem ),
aVal( rItem.aVal )
{
DBG_CTOR(SvxVector3DItem, 0);
}
// -----------------------------------------------------------------------
int SvxVector3DItem::operator==( const SfxPoolItem &rItem ) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
return ((SvxVector3DItem&)rItem).aVal == aVal;
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxVector3DItem::Clone( SfxItemPool * ) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
return new SvxVector3DItem( *this );
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxVector3DItem::Create(SvStream &rStream, USHORT /*nVersion*/) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
Vector3D aStr;
rStream >> aStr;
return new SvxVector3DItem(Which(), aStr);
}
// -----------------------------------------------------------------------
SvStream& SvxVector3DItem::Store(SvStream &rStream, USHORT /*nItemVersion*/) const
{
DBG_CHKTHIS(SvxVector3DItem, 0);
// ## if (nItemVersion)
rStream << aVal;
return rStream;
}
// -----------------------------------------------------------------------
sal_Bool SvxVector3DItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
drawing::Direction3D aDirection;
// Werte eintragen
aDirection.DirectionX = aVal.X();
aDirection.DirectionY = aVal.Y();
aDirection.DirectionZ = aVal.Z();
rVal <<= aDirection;
return( sal_True );
}
// -----------------------------------------------------------------------
sal_Bool SvxVector3DItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
drawing::Direction3D aDirection;
if(!(rVal >>= aDirection))
return sal_False;
aVal.X() = aDirection.DirectionX;
aVal.Y() = aDirection.DirectionY;
aVal.Z() = aDirection.DirectionZ;
return sal_True;
}
// -----------------------------------------------------------------------
USHORT SvxVector3DItem::GetVersion (USHORT nFileFormatVersion) const
{
return (nFileFormatVersion == SOFFICE_FILEFORMAT_31) ? USHRT_MAX : 0;
}
<|endoftext|> |
<commit_before>#include "rune/engine.h"
rune::Engine::Engine()
{
_basePath = "./";
}
rune::Engine::~Engine()
{
close();
}
void rune::Engine::init()
{
_init_entities();
_open = true;
_glThread = NULL;
}
void rune::Engine::setBasePath(QString basePath)
{
if(!basePath.endsWith("/"))
{
_basePath += "/";
}
_basePath = basePath;
}
QString rune::Engine::basePath()
{
return _basePath;
}
void rune::Engine::close()
{
if(!_open)
return;
_close_entities();
if(_loadedMaps.size() > 0)
{
// unload all loaded maps
for(QMap<QString, WorldMap*>::iterator it = _loadedMaps.begin();
it != _loadedMaps.end();
++it)
{
qDebug() << "free map " << it.key() << " at " << it.value();
delete it.value();
}
}
_open = false;
}
bool rune::Engine::loadEntity(QString path)
{
if(path.isEmpty())
{
return false;
}
QString loadPath = path;
if(!loadPath.endsWith(".yml"))
{
loadPath += ".yml";
}else
{
path = path.left(path.length()-4);
}
if(loadPath.startsWith("/")) {
loadPath = loadPath.right(loadPath.length()-1);
}
// build complete path
loadPath = _basePath + "entity/" + loadPath;
QFile yFile(loadPath);
if(!yFile.exists() || yFile.size() <= 0)
{
qDebug() << "error: entity definition '" << loadPath << "' does not exist" << endl;
return false;
}
// create entity for blueprint base
Entity* entity = new Entity(this);
YAML::Node yEntity = YAML::LoadFile(loadPath.toUtf8().constData());
// inherit from base
if(yEntity[rune::PROP_BASE.toStdString()])
{
QString baseEntity = QString::fromStdString(yEntity[rune::PROP_BASE.toStdString()].as<std::string>());
if(!g_blueprintRegister->contains(baseEntity)) // load base entity
if(!loadEntity(baseEntity))
{
delete entity;
return false;
}
entity->copyFrom(*getBlueprint(baseEntity));
}
// set entity properties from yaml
for(YAML::iterator it=yEntity.begin(); it != yEntity.end(); ++it){
entity->setProperty(QString::fromStdString(it->first.as<std::string>()), QString::fromStdString(it->second.as<std::string>()));
}
// set entity property
entity->setProperty(rune::PROP_ENTITY, path);
if(g_blueprintRegister->contains(path))
{
unloadEntity(path);
}
// add to blueprint register
g_blueprintRegister->insert(path, entity);
return true;
}
bool rune::Engine::unloadEntity(QString path)
{
if(path.isEmpty())
{
return false;
}
if(path.endsWith(".yml"))
{
path = path.left(path.length()-4);
}
if(!g_blueprintRegister->contains(path))
{
return false;
}
// delete entity
Entity* e = g_blueprintRegister->value(path);
g_blueprintRegister->remove(path);
// TODO remove existing clones?
delete e;
return true;
}
QString rune::Engine::cloneEntity(QString path)
{
if(!g_blueprintRegister->contains(path))
{
// blueprint was not loaded yet -> try to load
if(!loadEntity(path))
return ""; // blueprint could not be loaded -> error
}
// copy entity
Entity* clone = new Entity(this);
clone->copyFrom(*(g_blueprintRegister->value(path)));
/* check if clone register is already available
if(g_activeEntities == NULL)
{
// create if not
g_activeEntities = new QMap<QString, rune::Entity*>();
}*/
// generate entity id
QUuid uid = QUuid::createUuid();
clone->setProperty(rune::PROP_UID, uid.toString());
g_activeEntities->insert(uid.toString(), clone);
// init interpreter
ScriptInterpreter* si = new ScriptInterpreter(clone);
si->bind(clone);
return clone->getProperty(PROP_UID);
}
bool rune::Engine::modifyEntityProperty(QString uid, QString prop, QString value)
{
// TODO modification stack
Entity* e = getClone(uid);
if(e == NULL)
return false; // TODO error handling
e->setProperty(prop, value);
return true;
}
void rune::Engine::startGameLoop()
{
if(_glThread != NULL)
return; // game loop already in progress
_glThread = new GameLoopThread(this);
_glThread->start();
return;
}
void rune::Engine::stopGameLoop()
{
if(_glThread == NULL)
return; // no game loop running
_glThread->terminate();
return;
}
void rune::Engine::callAction(QString uid, QString action, uint timestamp)
{
QMutexLocker mlock(&_actionQueueMutex); // thread safe
rune_action_queue_item i;
i.uid = uid;
i.action = action;
i.timestamp = timestamp;
_actionQueue.enqueue(i);
return;
}
void rune::Engine::glFinished()
{
emit(gameStateChanged());
}
rune::Entity *rune::Engine::getBlueprint(QString path)
{
if(!g_blueprintRegister->contains(path))
{
return NULL;
}
return (g_blueprintRegister->value(path));
}
QQueue<rune_action_queue_item> rune::Engine::getReadyActions()
{
QMutexLocker mlock(&_actionQueueMutex);
uint now = QDateTime().toTime_t();
QQueue<rune_action_queue_item> ready;
QQueue<rune_action_queue_item> notReady;
while(!_actionQueue.isEmpty())
{
rune_action_queue_item i = _actionQueue.dequeue();
if(i.timestamp <= now)
ready.enqueue(i);
else
notReady.enqueue(i);
}
_actionQueue = notReady;
return ready;
}
rune::Entity *rune::Engine::getClone(QString uid)
{
if(!g_activeEntities->contains(uid))
return NULL;
return g_activeEntities->value(uid);
}
rune::WorldMap *rune::Engine::loadMap(QString path)
{
QString absPath = path;
if(!path.startsWith("/"))
path = "/" + path;
if(_loadedMaps.contains(path))
{
if(_loadedMaps[path] != NULL)
{
rune::setError(RUNE_ERR_MAP_LOADED_BEFORE);
return NULL;
}
}
absPath = path.right(path.length() - 1);
absPath = _basePath + "map/" + absPath + ".yml";
WorldMap* map = new WorldMap(this);
if(!map->loadMap(absPath))
return NULL;
map->setName(path);
_loadedMaps[path] = map;
return map;
}
void rune::Engine::unloadMap(QString path)
{
if(!path.startsWith("/"))
path = "/" + path;
if(!_loadedMaps.contains(path))
return;
WorldMap* map = _loadedMaps[path];
if(map == NULL)
return;
delete map;
_loadedMaps[path] = NULL;
return;
}
rune::WorldMap *rune::Engine::getMap(QString path)
{
if(!path.startsWith("/"))
path = "/" + path;
if(!_loadedMaps.contains(path))
return NULL;
return _loadedMaps[path];
}
void rune::Engine::_init_entities()
{
g_blueprintRegister = new QMap<QString, Entity*>();
g_activeEntities = new QMap<QString, rune::Entity*>();
}
void rune::Engine::_close_entities()
{
if(g_blueprintRegister == NULL){
//qWarn("rune entity environment is not initialised");
return;
}
// remove all registered entity blueprints
// TODO not thread safe! (use mutex or something)
QList<Entity*> entities = g_blueprintRegister->values();
for(int i=0; i<entities.size(); ++i){
delete entities[i];
}
delete g_blueprintRegister;
}
<commit_msg>improved game loop handling<commit_after>#include "rune/engine.h"
rune::Engine::Engine()
{
_basePath = "./";
}
rune::Engine::~Engine()
{
close();
}
void rune::Engine::init()
{
_init_entities();
_open = true;
_glThread = NULL;
}
void rune::Engine::setBasePath(QString basePath)
{
if(!basePath.endsWith("/"))
{
_basePath += "/";
}
_basePath = basePath;
}
QString rune::Engine::basePath()
{
return _basePath;
}
void rune::Engine::close()
{
if(!_open)
return;
_close_entities();
if(_loadedMaps.size() > 0)
{
// unload all loaded maps
for(QMap<QString, WorldMap*>::iterator it = _loadedMaps.begin();
it != _loadedMaps.end();
++it)
{
qDebug() << "free map " << it.key() << " at " << it.value();
delete it.value();
}
}
if(_glThread != NULL)
{
stopGameLoop();
}
_open = false;
}
bool rune::Engine::loadEntity(QString path)
{
if(path.isEmpty())
{
return false;
}
QString loadPath = path;
if(!loadPath.endsWith(".yml"))
{
loadPath += ".yml";
}else
{
path = path.left(path.length()-4);
}
if(loadPath.startsWith("/")) {
loadPath = loadPath.right(loadPath.length()-1);
}
// build complete path
loadPath = _basePath + "entity/" + loadPath;
QFile yFile(loadPath);
if(!yFile.exists() || yFile.size() <= 0)
{
qDebug() << "error: entity definition '" << loadPath << "' does not exist" << endl;
return false;
}
// create entity for blueprint base
Entity* entity = new Entity(this);
YAML::Node yEntity = YAML::LoadFile(loadPath.toUtf8().constData());
// inherit from base
if(yEntity[rune::PROP_BASE.toStdString()])
{
QString baseEntity = QString::fromStdString(yEntity[rune::PROP_BASE.toStdString()].as<std::string>());
if(!g_blueprintRegister->contains(baseEntity)) // load base entity
if(!loadEntity(baseEntity))
{
delete entity;
return false;
}
entity->copyFrom(*getBlueprint(baseEntity));
}
// set entity properties from yaml
for(YAML::iterator it=yEntity.begin(); it != yEntity.end(); ++it){
entity->setProperty(QString::fromStdString(it->first.as<std::string>()), QString::fromStdString(it->second.as<std::string>()));
}
// set entity property
entity->setProperty(rune::PROP_ENTITY, path);
if(g_blueprintRegister->contains(path))
{
unloadEntity(path);
}
// add to blueprint register
g_blueprintRegister->insert(path, entity);
return true;
}
bool rune::Engine::unloadEntity(QString path)
{
if(path.isEmpty())
{
return false;
}
if(path.endsWith(".yml"))
{
path = path.left(path.length()-4);
}
if(!g_blueprintRegister->contains(path))
{
return false;
}
// delete entity
Entity* e = g_blueprintRegister->value(path);
g_blueprintRegister->remove(path);
// TODO remove existing clones?
delete e;
return true;
}
QString rune::Engine::cloneEntity(QString path)
{
if(!g_blueprintRegister->contains(path))
{
// blueprint was not loaded yet -> try to load
if(!loadEntity(path))
return ""; // blueprint could not be loaded -> error
}
// copy entity
Entity* clone = new Entity(this);
clone->copyFrom(*(g_blueprintRegister->value(path)));
/* check if clone register is already available
if(g_activeEntities == NULL)
{
// create if not
g_activeEntities = new QMap<QString, rune::Entity*>();
}*/
// generate entity id
QUuid uid = QUuid::createUuid();
clone->setProperty(rune::PROP_UID, uid.toString());
g_activeEntities->insert(uid.toString(), clone);
// init interpreter
ScriptInterpreter* si = new ScriptInterpreter(clone);
si->bind(clone);
return clone->getProperty(PROP_UID);
}
bool rune::Engine::modifyEntityProperty(QString uid, QString prop, QString value)
{
// TODO modification stack
Entity* e = getClone(uid);
if(e == NULL)
return false; // TODO error handling
e->setProperty(prop, value);
return true;
}
void rune::Engine::startGameLoop()
{
if(_glThread != NULL && _glThread->isRunning())
return; // game loop already in progress
if(_glThread == NULL)
_glThread = new GameLoopThread(this);
connect(_glThread, SIGNAL(gameLoopFinished()), this, SLOT(glFinished()));
_glThread->start();
return;
}
void rune::Engine::stopGameLoop()
{
if(_glThread == NULL)
return; // no game loop running
if(!_glThread->isRunning())
return;
_glThread->invalidateEngine();
return;
}
void rune::Engine::callAction(QString uid, QString action, uint timestamp)
{
QMutexLocker mlock(&_actionQueueMutex); // thread safe
rune_action_queue_item i;
i.uid = uid;
i.action = action;
i.timestamp = timestamp;
_actionQueue.enqueue(i);
return;
}
void rune::Engine::glFinished()
{
emit(gameStateChanged());
}
rune::Entity *rune::Engine::getBlueprint(QString path)
{
if(!g_blueprintRegister->contains(path))
{
return NULL;
}
return (g_blueprintRegister->value(path));
}
QQueue<rune_action_queue_item> rune::Engine::getReadyActions()
{
QMutexLocker mlock(&_actionQueueMutex);
uint now = QDateTime().toTime_t();
QQueue<rune_action_queue_item> ready;
QQueue<rune_action_queue_item> notReady;
while(!_actionQueue.isEmpty())
{
rune_action_queue_item i = _actionQueue.dequeue();
if(i.timestamp <= now)
ready.enqueue(i);
else
notReady.enqueue(i);
}
_actionQueue = notReady;
return ready;
}
rune::Entity *rune::Engine::getClone(QString uid)
{
if(!g_activeEntities->contains(uid))
return NULL;
return g_activeEntities->value(uid);
}
rune::WorldMap *rune::Engine::loadMap(QString path)
{
QString absPath = path;
if(!path.startsWith("/"))
path = "/" + path;
if(_loadedMaps.contains(path))
{
if(_loadedMaps[path] != NULL)
{
rune::setError(RUNE_ERR_MAP_LOADED_BEFORE);
return NULL;
}
}
absPath = path.right(path.length() - 1);
absPath = _basePath + "map/" + absPath + ".yml";
WorldMap* map = new WorldMap(this);
if(!map->loadMap(absPath))
return NULL;
map->setName(path);
_loadedMaps[path] = map;
return map;
}
void rune::Engine::unloadMap(QString path)
{
if(!path.startsWith("/"))
path = "/" + path;
if(!_loadedMaps.contains(path))
return;
WorldMap* map = _loadedMaps[path];
if(map == NULL)
return;
delete map;
_loadedMaps[path] = NULL;
return;
}
rune::WorldMap *rune::Engine::getMap(QString path)
{
if(!path.startsWith("/"))
path = "/" + path;
if(!_loadedMaps.contains(path))
return NULL;
return _loadedMaps[path];
}
void rune::Engine::_init_entities()
{
g_blueprintRegister = new QMap<QString, Entity*>();
g_activeEntities = new QMap<QString, rune::Entity*>();
}
void rune::Engine::_close_entities()
{
if(g_blueprintRegister == NULL){
//qWarn("rune entity environment is not initialised");
return;
}
// remove all registered entity blueprints
// TODO not thread safe! (use mutex or something)
QList<Entity*> entities = g_blueprintRegister->values();
for(int i=0; i<entities.size(); ++i){
delete entities[i];
}
delete g_blueprintRegister;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2015 Wojciech Migda
* All rights reserved
* Distributed under the terms of the GNU LGPL v3
*******************************************************************************
*
* Filename: fmincg.hpp
*
* Description:
* description
*
* Authors:
* Wojciech Migda (wm)
*
*******************************************************************************
* History:
* --------
* Date Who Ticket Description
* ---------- --- --------- ------------------------------------------------
* 2015-02-04 wm Initial version
*
******************************************************************************/
/*
* Minimize a continuous differentialble multivariate function. Starting point <br/>
* is given by "X" (D by 1), and the function named in the string "f", must<br/>
* return a function value and a vector of partial derivatives. The Polack-<br/>
* Ribiere flavour of conjugate gradients is used to compute search directions,<br/>
* and a line search using quadratic and cubic polynomial approximations and the<br/>
* Wolfe-Powell stopping criteria is used together with the slope ratio method<br/>
* for guessing initial step sizes. Additionally a bunch of checks are made to<br/>
* make sure that exploration is taking place and that extrapolation will not<br/>
* be unboundedly large. The "length" gives the length of the run: if it is<br/>
* positive, it gives the maximum number of line searches, if negative its<br/>
* absolute gives the maximum allowed number of function evaluations. You can<br/>
* (optionally) give "length" a second component, which will indicate the<br/>
* reduction in function value to be expected in the first line-search (defaults<br/>
* to 1.0). The function returns when either its length is up, or if no further<br/>
* progress can be made (ie, we are at a minimum, or so close that due to<br/>
* numerical problems, we cannot get any closer). If the function terminates<br/>
* within a few iterations, it could be an indication that the function value<br/>
* and derivatives are not consistent (ie, there may be a bug in the<br/>
* implementation of your "f" function). The function returns the found<br/>
* solution "X", a vector of function values "fX" indicating the progress made<br/>
* and "i" the number of iterations (line searches or function evaluations,<br/>
* depending on the sign of "length") used.<br/>
* <br/>
* Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)<br/>
* <br/>
* See also: checkgrad <br/>
* <br/>
* Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13<br/>
* <br/>
* <br/>
* (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen <br/>
* Permission is granted for anyone to copy, use, or modify these<br/>
* programs and accompanying documents for purposes of research or<br/>
* education, provided this copyright notice is retained, and note is<br/>
* made of any changes that have been made.<br/>
* <br/>
* These programs and documents are distributed without any warranty,<br/>
* express or implied. As the programs were written for research<br/>
* purposes only, they have not been tested to the degree that would be<br/>
* advisable in any important application. All use of these programs is<br/>
* entirely at the user's own risk.<br/>
* <br/>
*/
#ifndef FMINCG_HPP_
#define FMINCG_HPP_
#include <utility>
#include <valarray>
#include <cmath>
#include <algorithm>
namespace num
{
// based on:
// https://github.com/thomasjungblut/tjungblut-math-cpp/blob/master/tjungblut-math%2B%2B/source/src/Fmincg.cpp
template<typename _ValueType>
std::valarray<_ValueType>
fmincg(
std::function<std::pair<_ValueType, std::valarray<_ValueType>> (const std::valarray<_ValueType>)> cost_gradient_fn,
std::valarray<_ValueType> theta,
int maxiter,
bool verbose=false
)
{
typedef _ValueType value_type;
typedef std::valarray<value_type> vector;
// number of extrapolation runs, set to a higher value for smaller ravine landscapes
constexpr value_type EXT = 3.0;
// a bunch of constants for line searches
constexpr value_type RHO = 0.01;
// RHO and SIG are the constants in the Wolfe-Powell conditions
constexpr value_type SIG = 0.5;
// don't reevaluate within 0.1 of the limit of the current bracket
constexpr value_type INT = 0.1;
// max 20 function evaluations per line search
constexpr int MAX = 20;
// maximum allowed slope ratio
constexpr value_type RATIO = 100.0;
// we start by setting up all memory that we will need in terms of vectors,
// while calculating we will just fill this memory (overloaded << uses memcpy)
// input will be the pointer to our current active parameter set
vector & input(theta);
vector X0 = vector(input);
// search directions
vector s = vector(input.size());
// gradients
vector df0 = vector(input.size());
vector df1 = vector(input.size());
vector df2 = vector(input.size());
// define some integers for bookkeeping and then start
int M = 0;
int i = 0; // zero the run length counter
constexpr int red = 1; // starting point
int ls_failed = 0; // no previous line search has failed
const std::pair<value_type, vector> cost_gradient = cost_gradient_fn(input);
value_type f1 = cost_gradient.first;
df1 = std::move(cost_gradient.second);
i = i + (maxiter < 0 ? 1 : 0);
// search direction is steepest
s = -df1;
value_type d1 = -(s * s).sum(); // this is the slope
value_type z1 = red / (1.0 - d1); // initial step is red/(|s|+1)
while (i < std::abs(maxiter)) // while not finished
{
i = i + (maxiter > 0 ? 1 : 0); // count iterations?!
// make a copy of current values
X0 = input;
value_type f0 = f1;
df0 = df1;
// begin line search
// fill our new line searched parameters
input = input + (s * z1);
const std::pair<value_type, vector> evaluateCost2 = cost_gradient_fn(input);
value_type f2 = evaluateCost2.first;
df2 = std::move(evaluateCost2.second);
i = i + (maxiter < 0 ? 1 : 0); // count epochs
value_type d2 = (df2 * s).sum();
// initialize point 3 equal to point 1
value_type f3 = f1;
value_type d3 = d1;
value_type z3 = -z1;
if (maxiter > 0)
{
M = MAX;
}
else
{
M = std::min(MAX, - maxiter - i);
}
// initialize quantities
int success = 0;
value_type limit = -1;
while (true)
{
while (((f2 > f1 + z1 * RHO * d1) | (d2 > -SIG * d1)) && (M > 0))
{
// tighten the bracket
limit = z1;
value_type z2 = 0.0;
if (f2 > f1)
{
// quadratic fit
z2 = z3 - (0.5 * d3 * z3 * z3) / (d3 * z3 + f2 - f3);
}
else
{
// cubic fit
const value_type A = 6 * (f2 - f3) / z3 + 3 * (d2 + d3);
const value_type B = 3 * (f3 - f2) - z3 * (d3 + 2 * d2);
// numerical error possible - ok!
z2 = (std::sqrt(B * B - A * d2 * z3 * z3) - B) / A;
}
if (std::isnan(z2) || !std::isfinite(z2))
{
// if we had a numerical problem then bisect
z2 = z3 / 2.0;
}
// don't accept too close to limits
z2 = std::max(std::min(z2, INT * z3), (1 - INT) * z3);
// update the step
z1 = z1 + z2;
input += (s * z2);
std::pair<value_type, vector> evaluateCost3 = cost_gradient_fn(input);
f2 = evaluateCost3.first;
df2 = std::move(evaluateCost3.second);
M = M - 1;
i = i + (maxiter < 0 ? 1 : 0); // count epochs
d2 = (df2 * s).sum();
// z3 is now relative to the location of z2
z3 = z3 - z2;
}
if (f2 > f1 + z1 * RHO * d1 || d2 > -SIG * d1)
{
break; // this is a failure
}
else if (d2 > SIG * d1)
{
success = 1;
break; // success
}
else if (M == 0)
{
break; // failure
}
// make cubic extrapolation
const value_type A = 6 * (f2 - f3) / z3 + 3 * (d2 + d3);
const value_type B = 3 * (f3 - f2) - z3 * (d3 + 2 * d2);
value_type z2 = -d2 * z3 * z3 / (B + std::sqrt(B * B - A * d2 * z3 * z3));
// num prob or wrong sign?
if (std::isnan(z2) || !std::isfinite(z2) || z2 < 0)
{
// if we have no upper limit
if (limit < -0.5)
{
// the extrapolate the maximum amount
z2 = z1 * (EXT - 1);
}
else
{
// otherwise bisect
z2 = (limit - z1) / 2;
}
}
else if ((limit > -0.5) && (z2 + z1 > limit))
{
// extraplation beyond max?
z2 = (limit - z1) / 2; // bisect
}
else if ((limit < -0.5) && (z2 + z1 > z1 * EXT))
{
// extrapolationbeyond limit
z2 = z1 * (EXT - 1.0); // set to extrapolation limit
}
else if (z2 < -z3 * INT)
{
z2 = -z3 * INT;
}
else if ((limit > -0.5) && (z2 < (limit - z1) * (1.0 - INT)))
{
// too close to the limit
z2 = (limit - z1) * (1.0 - INT);
}
// set point 3 equal to point 2
f3 = f2;
d3 = d2;
z3 = -z2;
z1 = z1 + z2;
// update current estimates
input += (s * z2);
const std::pair<value_type, vector> evaluateCost3 = cost_gradient_fn(input);
f2 = evaluateCost3.first;
df2 = std::move(evaluateCost3.second);
M = M - 1;
i = i + (maxiter < 0 ? 1 : 0); // count epochs?!
d2 = (df2 * s).sum();
} // end of line search
if (success == 1) // if line search succeeded
{
f1 = f2;
if (verbose)
{
std::cout << "Iteration " << i << " | Cost: " << f1 << std::endl;
}
// Polack-Ribiere direction: s =
// (df2'*df2-df1'*df2)/(df1'*df1)*s - df2;
const value_type df2len = (df2 * df2).sum();
const value_type df12len = (df1* df2).sum();
const value_type df1len = (df1 * df1).sum();
const value_type numerator = (df2len - df12len) / df1len;
s = (s * numerator) - df2;
std::swap(df1, df2); // swap derivatives
d2 = (df1 * s).sum();
// new slope must be negative
if (d2 > 0)
{
// otherwise use steepest direction
s = -df1;
d2 = -(s * s).sum();
}
// realmin in octave = 2.2251e-308
// slope ratio but max RATIO
const value_type thres = d1 / (d2 - std::numeric_limits<value_type>::min());
z1 = z1 * std::min(RATIO, thres);
d1 = d2;
ls_failed = 0; // this line search did not fail
}
else
{
// restore data from the beginning of the iteration
input = X0;
f1 = f0;
df1 = df0; // restore point from before failed line search
// line search failed twice in a row?
if (ls_failed == 1 || i > std::abs(maxiter))
{
break; // or we ran out of time, so we give up
}
// swap derivatives
std::swap(df1, df2);
// try steepest
s = -df1;
d1 = -(s * s).sum();
z1 = 1.0 / (1.0 - d1);
ls_failed = 1; // this line search failed
}
}
return theta;
}
}
#endif /* FMINCG_HPP_ */
<commit_msg>missing #include <iostream><commit_after>/*******************************************************************************
* Copyright (c) 2015 Wojciech Migda
* All rights reserved
* Distributed under the terms of the GNU LGPL v3
*******************************************************************************
*
* Filename: fmincg.hpp
*
* Description:
* description
*
* Authors:
* Wojciech Migda (wm)
*
*******************************************************************************
* History:
* --------
* Date Who Ticket Description
* ---------- --- --------- ------------------------------------------------
* 2015-02-04 wm Initial version
*
******************************************************************************/
/*
* Minimize a continuous differentialble multivariate function. Starting point <br/>
* is given by "X" (D by 1), and the function named in the string "f", must<br/>
* return a function value and a vector of partial derivatives. The Polack-<br/>
* Ribiere flavour of conjugate gradients is used to compute search directions,<br/>
* and a line search using quadratic and cubic polynomial approximations and the<br/>
* Wolfe-Powell stopping criteria is used together with the slope ratio method<br/>
* for guessing initial step sizes. Additionally a bunch of checks are made to<br/>
* make sure that exploration is taking place and that extrapolation will not<br/>
* be unboundedly large. The "length" gives the length of the run: if it is<br/>
* positive, it gives the maximum number of line searches, if negative its<br/>
* absolute gives the maximum allowed number of function evaluations. You can<br/>
* (optionally) give "length" a second component, which will indicate the<br/>
* reduction in function value to be expected in the first line-search (defaults<br/>
* to 1.0). The function returns when either its length is up, or if no further<br/>
* progress can be made (ie, we are at a minimum, or so close that due to<br/>
* numerical problems, we cannot get any closer). If the function terminates<br/>
* within a few iterations, it could be an indication that the function value<br/>
* and derivatives are not consistent (ie, there may be a bug in the<br/>
* implementation of your "f" function). The function returns the found<br/>
* solution "X", a vector of function values "fX" indicating the progress made<br/>
* and "i" the number of iterations (line searches or function evaluations,<br/>
* depending on the sign of "length") used.<br/>
* <br/>
* Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)<br/>
* <br/>
* See also: checkgrad <br/>
* <br/>
* Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13<br/>
* <br/>
* <br/>
* (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen <br/>
* Permission is granted for anyone to copy, use, or modify these<br/>
* programs and accompanying documents for purposes of research or<br/>
* education, provided this copyright notice is retained, and note is<br/>
* made of any changes that have been made.<br/>
* <br/>
* These programs and documents are distributed without any warranty,<br/>
* express or implied. As the programs were written for research<br/>
* purposes only, they have not been tested to the degree that would be<br/>
* advisable in any important application. All use of these programs is<br/>
* entirely at the user's own risk.<br/>
* <br/>
*/
#ifndef FMINCG_HPP_
#define FMINCG_HPP_
#include <utility>
#include <valarray>
#include <cmath>
#include <algorithm>
#include <iostream>
namespace num
{
// based on:
// https://github.com/thomasjungblut/tjungblut-math-cpp/blob/master/tjungblut-math%2B%2B/source/src/Fmincg.cpp
template<typename _ValueType>
std::valarray<_ValueType>
fmincg(
std::function<std::pair<_ValueType, std::valarray<_ValueType>> (const std::valarray<_ValueType>)> cost_gradient_fn,
std::valarray<_ValueType> theta,
int maxiter,
bool verbose=false
)
{
typedef _ValueType value_type;
typedef std::valarray<value_type> vector;
// number of extrapolation runs, set to a higher value for smaller ravine landscapes
constexpr value_type EXT = 3.0;
// a bunch of constants for line searches
constexpr value_type RHO = 0.01;
// RHO and SIG are the constants in the Wolfe-Powell conditions
constexpr value_type SIG = 0.5;
// don't reevaluate within 0.1 of the limit of the current bracket
constexpr value_type INT = 0.1;
// max 20 function evaluations per line search
constexpr int MAX = 20;
// maximum allowed slope ratio
constexpr value_type RATIO = 100.0;
// we start by setting up all memory that we will need in terms of vectors,
// while calculating we will just fill this memory (overloaded << uses memcpy)
// input will be the pointer to our current active parameter set
vector & input(theta);
vector X0 = vector(input);
// search directions
vector s = vector(input.size());
// gradients
vector df0 = vector(input.size());
vector df1 = vector(input.size());
vector df2 = vector(input.size());
// define some integers for bookkeeping and then start
int M = 0;
int i = 0; // zero the run length counter
constexpr int red = 1; // starting point
int ls_failed = 0; // no previous line search has failed
const std::pair<value_type, vector> cost_gradient = cost_gradient_fn(input);
value_type f1 = cost_gradient.first;
df1 = std::move(cost_gradient.second);
i = i + (maxiter < 0 ? 1 : 0);
// search direction is steepest
s = -df1;
value_type d1 = -(s * s).sum(); // this is the slope
value_type z1 = red / (1.0 - d1); // initial step is red/(|s|+1)
while (i < std::abs(maxiter)) // while not finished
{
i = i + (maxiter > 0 ? 1 : 0); // count iterations?!
// make a copy of current values
X0 = input;
value_type f0 = f1;
df0 = df1;
// begin line search
// fill our new line searched parameters
input = input + (s * z1);
const std::pair<value_type, vector> evaluateCost2 = cost_gradient_fn(input);
value_type f2 = evaluateCost2.first;
df2 = std::move(evaluateCost2.second);
i = i + (maxiter < 0 ? 1 : 0); // count epochs
value_type d2 = (df2 * s).sum();
// initialize point 3 equal to point 1
value_type f3 = f1;
value_type d3 = d1;
value_type z3 = -z1;
if (maxiter > 0)
{
M = MAX;
}
else
{
M = std::min(MAX, - maxiter - i);
}
// initialize quantities
int success = 0;
value_type limit = -1;
while (true)
{
while (((f2 > f1 + z1 * RHO * d1) | (d2 > -SIG * d1)) && (M > 0))
{
// tighten the bracket
limit = z1;
value_type z2 = 0.0;
if (f2 > f1)
{
// quadratic fit
z2 = z3 - (0.5 * d3 * z3 * z3) / (d3 * z3 + f2 - f3);
}
else
{
// cubic fit
const value_type A = 6 * (f2 - f3) / z3 + 3 * (d2 + d3);
const value_type B = 3 * (f3 - f2) - z3 * (d3 + 2 * d2);
// numerical error possible - ok!
z2 = (std::sqrt(B * B - A * d2 * z3 * z3) - B) / A;
}
if (std::isnan(z2) || !std::isfinite(z2))
{
// if we had a numerical problem then bisect
z2 = z3 / 2.0;
}
// don't accept too close to limits
z2 = std::max(std::min(z2, INT * z3), (1 - INT) * z3);
// update the step
z1 = z1 + z2;
input += (s * z2);
std::pair<value_type, vector> evaluateCost3 = cost_gradient_fn(input);
f2 = evaluateCost3.first;
df2 = std::move(evaluateCost3.second);
M = M - 1;
i = i + (maxiter < 0 ? 1 : 0); // count epochs
d2 = (df2 * s).sum();
// z3 is now relative to the location of z2
z3 = z3 - z2;
}
if (f2 > f1 + z1 * RHO * d1 || d2 > -SIG * d1)
{
break; // this is a failure
}
else if (d2 > SIG * d1)
{
success = 1;
break; // success
}
else if (M == 0)
{
break; // failure
}
// make cubic extrapolation
const value_type A = 6 * (f2 - f3) / z3 + 3 * (d2 + d3);
const value_type B = 3 * (f3 - f2) - z3 * (d3 + 2 * d2);
value_type z2 = -d2 * z3 * z3 / (B + std::sqrt(B * B - A * d2 * z3 * z3));
// num prob or wrong sign?
if (std::isnan(z2) || !std::isfinite(z2) || z2 < 0)
{
// if we have no upper limit
if (limit < -0.5)
{
// the extrapolate the maximum amount
z2 = z1 * (EXT - 1);
}
else
{
// otherwise bisect
z2 = (limit - z1) / 2;
}
}
else if ((limit > -0.5) && (z2 + z1 > limit))
{
// extraplation beyond max?
z2 = (limit - z1) / 2; // bisect
}
else if ((limit < -0.5) && (z2 + z1 > z1 * EXT))
{
// extrapolationbeyond limit
z2 = z1 * (EXT - 1.0); // set to extrapolation limit
}
else if (z2 < -z3 * INT)
{
z2 = -z3 * INT;
}
else if ((limit > -0.5) && (z2 < (limit - z1) * (1.0 - INT)))
{
// too close to the limit
z2 = (limit - z1) * (1.0 - INT);
}
// set point 3 equal to point 2
f3 = f2;
d3 = d2;
z3 = -z2;
z1 = z1 + z2;
// update current estimates
input += (s * z2);
const std::pair<value_type, vector> evaluateCost3 = cost_gradient_fn(input);
f2 = evaluateCost3.first;
df2 = std::move(evaluateCost3.second);
M = M - 1;
i = i + (maxiter < 0 ? 1 : 0); // count epochs?!
d2 = (df2 * s).sum();
} // end of line search
if (success == 1) // if line search succeeded
{
f1 = f2;
if (verbose)
{
std::cout << "Iteration " << i << " | Cost: " << f1 << std::endl;
}
// Polack-Ribiere direction: s =
// (df2'*df2-df1'*df2)/(df1'*df1)*s - df2;
const value_type df2len = (df2 * df2).sum();
const value_type df12len = (df1* df2).sum();
const value_type df1len = (df1 * df1).sum();
const value_type numerator = (df2len - df12len) / df1len;
s = (s * numerator) - df2;
std::swap(df1, df2); // swap derivatives
d2 = (df1 * s).sum();
// new slope must be negative
if (d2 > 0)
{
// otherwise use steepest direction
s = -df1;
d2 = -(s * s).sum();
}
// realmin in octave = 2.2251e-308
// slope ratio but max RATIO
const value_type thres = d1 / (d2 - std::numeric_limits<value_type>::min());
z1 = z1 * std::min(RATIO, thres);
d1 = d2;
ls_failed = 0; // this line search did not fail
}
else
{
// restore data from the beginning of the iteration
input = X0;
f1 = f0;
df1 = df0; // restore point from before failed line search
// line search failed twice in a row?
if (ls_failed == 1 || i > std::abs(maxiter))
{
break; // or we ran out of time, so we give up
}
// swap derivatives
std::swap(df1, df2);
// try steepest
s = -df1;
d1 = -(s * s).sum();
z1 = 1.0 / (1.0 - d1);
ls_failed = 1; // this line search failed
}
}
return theta;
}
}
#endif /* FMINCG_HPP_ */
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.